Caffe2 - Python API
A deep learning, cross platform ML framework
dyndep.py
1 ## @package dyndep
2 # Module caffe2.python.dyndep
3 from __future__ import absolute_import
4 from __future__ import division
5 from __future__ import print_function
6 from __future__ import unicode_literals
7 
8 import ctypes
9 import os
10 
11 from caffe2.python import core, extension_loader
12 
13 
14 def InitOpsLibrary(name):
15  """Loads a dynamic library that contains custom operators into Caffe2.
16 
17  Since Caffe2 uses static variable registration, you can optionally load a
18  separate .so file that contains custom operators and registers that into
19  the caffe2 core binary. In C++, this is usually done by either declaring
20  dependency during compilation time, or via dynload. This allows us to do
21  registration similarly on the Python side.
22 
23  Args:
24  name: a name that ends in .so, such as "my_custom_op.so". Otherwise,
25  the command will simply be ignored.
26  Returns:
27  None
28  """
29  if not os.path.exists(name):
30  # Note(jiayq): if the name does not exist, instead of immediately
31  # failing we will simply print a warning, deferring failure to the
32  # time when an actual call is made.
33  print('Ignoring {} as it is not a valid file.'.format(name))
34  return
35  _init_impl(name)
36 
37 
38 _IMPORTED_DYNDEPS = set()
39 
40 
41 def GetImportedOpsLibraries():
42  return _IMPORTED_DYNDEPS
43 
44 
45 def _init_impl(path):
46  _IMPORTED_DYNDEPS.add(path)
47  with extension_loader.DlopenGuard():
48  ctypes.CDLL(path)
49  # reinitialize available ops
50  core.RefreshRegisteredOperators()