4 from google.protobuf.message
import Message
5 from multiprocessing
import Process
12 from six
import string_types
15 from caffe2.proto
import caffe2_pb2
16 from caffe2.python
import scope, utils
18 import caffe2.python._import_c_extension
as C
20 logger = logging.getLogger(__name__)
23 CreateBlob = C.create_blob
24 CurrentWorkspace = C.current_workspace
25 DeserializeBlob = C.deserialize_blob
26 GlobalInit = C.global_init
28 RegisteredOperators = C.registered_operators
29 SerializeBlob = C.serialize_blob
30 SwitchWorkspace = C.switch_workspace
31 RootFolder = C.root_folder
32 Workspaces = C.workspaces
33 BenchmarkNet = C.benchmark_net
34 Predictor = C.Predictor
37 has_gpu_support = C.has_gpu_support
39 NumCudaDevices = C.num_cuda_devices
40 SetDefaultGPUID = C.set_default_gpu_id
41 GetDefaultGPUID = C.get_default_gpu_id
42 GetCuDNNVersion = C.get_cudnn_version
44 def GetCudaPeerAccessPattern():
45 return np.asarray(C.get_cuda_peer_access_pattern())
47 NumCudaDevices =
lambda: 0
48 SetDefaultGPUID =
lambda x:
None 49 GetDefaultGPUID =
lambda: 0
50 GetCuDNNVersion =
lambda: 0
51 GetCudaPeerAccessPattern =
lambda: np.array([])
62 def _GetFreeFlaskPort():
63 """Get a free flask port.""" 65 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
66 result = sock.connect_ex((
'127.0.0.1', 5000))
72 port = s.getsockname()[1]
82 """Start a mint instance. 84 TODO(Yangqing): this does not work well under ipython yet. According to 85 https://github.com/ipython/ipython/issues/5862 86 writing up some fix is a todo item. 88 from caffe2.python.mint
import app
89 if root_folder
is None:
91 root_folder = C.root_folder()
93 port = _GetFreeFlaskPort()
97 [
'-p', str(port),
'-r', root_folder],
101 print(
'Mint running at http://{}:{}'.format(socket.getfqdn(), port))
106 """Stringify a protocol buffer object. 109 obj: a protocol buffer object, or a Pycaffe2 object that has a Proto() 112 string: the output protobuf string. 114 AttributeError: if the passed in object does not have the right attribute. 116 if isinstance(obj, string_types):
119 if isinstance(obj, Message):
122 return obj.SerializeToString()
123 elif hasattr(obj,
'Proto'):
124 return obj.Proto().SerializeToString()
126 raise ValueError(
"Unexpected argument to StringifyProto of type " +
130 def ResetWorkspace(root_folder=None):
131 if root_folder
is None:
133 return C.reset_workspace(C.root_folder())
135 if not os.path.exists(root_folder):
136 os.makedirs(root_folder)
137 return C.reset_workspace(root_folder)
140 def CreateNet(net, overwrite=False, input_blobs=None):
141 if input_blobs
is None:
143 for input_blob
in input_blobs:
144 C.create_blob(input_blob)
148 def RunOperatorOnce(operator):
152 def RunOperatorsOnce(operators):
154 success = RunOperatorOnce(op)
168 name: the name of the net, or a reference to the net. 169 num_iter: number of iterations to run 171 True or an exception. 173 return C.run_net(StringifyNetName(name), num_iter)
176 def RunPlan(plan_or_step):
178 import caffe2.python.core
as core
185 """Infers the shapes and types for the specified nets. 188 nets: the list of nets 189 blob_dimensions (optional): a dictionary of blobs and their dimensions. 190 If not specified, the workspace blobs are used. 192 A tuple of (shapes, types) dictionaries keyed by blob name. 195 if blob_dimensions
is None:
196 blobdesc_prototxt = C.infer_shapes_and_types_from_workspace(net_protos)
198 blobdesc_prototxt = C.infer_shapes_and_types_from_map(
199 net_protos, blob_dimensions
201 blobdesc_proto = caffe2_pb2.TensorShapes()
202 blobdesc_proto.ParseFromString(blobdesc_prototxt)
205 for ts
in blobdesc_proto.shapes:
206 if not ts.unknown_shape:
207 shapes[ts.name] = list(ts.dims)
208 types[ts.name] = ts.data_type
210 return (shapes, types)
213 def _StringifyName(name, expected_type):
214 if isinstance(name, basestring):
216 assert type(name).__name__ == expected_type, \
217 "Expected a string or %s" % expected_type
221 def StringifyBlobName(name):
222 return _StringifyName(name,
"BlobReference")
225 def StringifyNetName(name):
226 return _StringifyName(name,
"Net")
230 """Feeds a blob into the workspace. 233 name: the name of the blob. 234 arr: either a TensorProto object or a numpy array object to be fed into 236 device_option (optional): the device option to feed the data with. 238 True or False, stating whether the feed is successful. 240 if type(arr)
is caffe2_pb2.TensorProto:
242 if type(arr)
is np.ndarray
and arr.dtype.kind ==
'S':
244 arr = arr.astype(np.object)
246 if device_option
is None:
249 if device_option
and device_option.device_type == caffe2_pb2.CUDA:
250 if arr.dtype == np.dtype(
'float64'):
252 "CUDA operators do not support 64-bit doubles, " +
253 "please use arr.astype(np.float32) or np.int32 for ints." +
254 " Blob: {}".format(name) +
255 " type: {}".format(str(arr.dtype))
258 name = StringifyBlobName(name)
259 if device_option
is not None:
262 return C.feed_blob(name, arr)
266 """Fetches a list of blobs from the workspace. 269 names: list of names of blobs - strings or BlobReferences 271 list of fetched blobs 273 return [
FetchBlob(name)
for name
in names]
277 """Fetches a blob from the workspace. 280 name: the name of the blob - a string or a BlobReference 282 Fetched blob (numpy array or string) if successful 284 return C.fetch_blob(StringifyBlobName(name))
288 """Return the current namescope string. To be used to fetch blobs""" 293 """Provides python dict compatible way to do fetching and feeding""" 295 def __getitem__(self, key):
298 def __setitem__(self, key, value):
302 return len(C.blobs())
305 return C.blobs().__iter__()
307 def __contains__(self, item):
308 return C.has_blob(item)
334 _immediate_mode =
False 335 _immediate_workspace_name =
"_CAFFE2_IMMEDIATE" 336 _immediate_root_folder =
'' 340 return _immediate_mode
343 @contextlib.contextmanager
344 def WorkspaceGuard(workspace_name):
345 current = CurrentWorkspace()
346 SwitchWorkspace(workspace_name,
True)
348 SwitchWorkspace(current)
351 def StartImmediate(i_know=False):
352 global _immediate_mode
353 global _immediate_root_folder
358 _immediate_mode =
True 359 with WorkspaceGuard(_immediate_workspace_name):
360 _immediate_root_folder = tempfile.mkdtemp()
361 ResetWorkspace(_immediate_root_folder)
366 Enabling immediate mode in caffe2 python is an EXTREMELY EXPERIMENTAL 367 feature and may very easily go wrong. This is because Caffe2 uses a 368 declarative way of defining operators and models, which is essentially 369 not meant to run things in an interactive way. Read the following carefully 370 to make sure that you understand the caveats. 372 (1) You need to make sure that the sequences of operators you create are 373 actually runnable sequentially. For example, if you create an op that takes 374 an input X, somewhere earlier you should have already created X. 376 (2) Caffe2 immediate uses one single workspace, so if the set of operators 377 you run are intended to be under different workspaces, they will not run. 378 To create boundaries between such use cases, you can call FinishImmediate() 379 and StartImmediate() manually to flush out everything no longer needed. 381 (3) Underlying objects held by the immediate mode may interfere with your 382 normal run. For example, if there is a leveldb that you opened in immediate 383 mode and did not close, your main run will fail because leveldb does not 384 support double opening. Immediate mode may also occupy a lot of memory esp. 385 on GPUs. Call FinishImmediate() as soon as possible when you no longer 388 (4) Immediate is designed to be slow. Every immediate call implicitly 389 creates a temp operator object, runs it, and destroys the operator. This 390 slow-speed run is by design to discourage abuse. For most use cases other 391 than debugging, do NOT turn on immediate mode. 393 (5) If there is anything FATAL happening in the underlying C++ code, the 394 immediate mode will immediately (pun intended) cause the runtime to crash. 396 Thus you should use immediate mode with extra care. If you still would 397 like to, have fun [https://xkcd.com/149/]. 402 """Stops an immediate mode run.""" 404 global _immediate_mode
405 global _immediate_root_folder
406 if not IsImmediate():
408 with WorkspaceGuard(_immediate_workspace_name):
410 shutil.rmtree(_immediate_root_folder)
411 _immediate_root_folder =
'' 412 _immediate_mode =
False 415 def ImmediateBlobs():
416 with WorkspaceGuard(_immediate_workspace_name):
420 def RunOperatorImmediate(op):
421 with WorkspaceGuard(_immediate_workspace_name):
425 def FetchImmediate(*args, **kwargs):
426 with WorkspaceGuard(_immediate_workspace_name):
430 def FeedImmediate(*args, **kwargs):
431 with WorkspaceGuard(_immediate_workspace_name):
437 def _Workspace_create_net(ws, net, overwrite=False):
441 C.Workspace.create_net = _Workspace_create_net
444 def _Workspace_run(ws, obj):
445 if hasattr(obj,
'Proto'):
447 if isinstance(obj, caffe2_pb2.PlanDef):
448 return ws._run_plan(obj.SerializeToString())
449 if isinstance(obj, caffe2_pb2.NetDef):
450 return ws._run_net(obj.SerializeToString())
451 if isinstance(obj, caffe2_pb2.OperatorDef):
452 return ws._run_operator(obj.SerializeToString())
454 "Don't know how to do Workspace.run() on {}".format(type(obj)))
457 C.Workspace.run = _Workspace_run
460 def _Blob_feed(blob, arg, device_option=None):
461 if device_option
is not None:
463 return blob._feed(arg, device_option)
466 C.Blob.feed = _Blob_feed
def Caffe2TensorToNumpyArray(tensor)
def RunNet(name, num_iter=1)
def InferShapesAndTypes(nets, blob_dimensions=None)
def FeedBlob(name, arr, device_option=None)
def StartMint(root_folder=None, port=None)