Caffe2 - Python API
A deep learning, cross platform ML framework
dyndep.py
1 # Copyright (c) 2016-present, Facebook, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 ##############################################################################
15 
16 ## @package dyndep
17 # Module caffe2.python.dyndep
18 from __future__ import absolute_import
19 from __future__ import division
20 from __future__ import print_function
21 from __future__ import unicode_literals
22 
23 import ctypes
24 import os
25 
26 from caffe2.python import core, extension_loader
27 
28 
29 def InitOpsLibrary(name):
30  """Loads a dynamic library that contains custom operators into Caffe2.
31 
32  Since Caffe2 uses static variable registration, you can optionally load a
33  separate .so file that contains custom operators and registers that into
34  the caffe2 core binary. In C++, this is usually done by either declaring
35  dependency during compilation time, or via dynload. This allows us to do
36  registration similarly on the Python side.
37 
38  Args:
39  name: a name that ends in .so, such as "my_custom_op.so". Otherwise,
40  the command will simply be ignored.
41  Returns:
42  None
43  """
44  if not os.path.exists(name):
45  # Note(jiayq): if the name does not exist, instead of immediately
46  # failing we will simply print a warning, deferring failure to the
47  # time when an actual call is made.
48  print('Ignoring {} as it is not a valid file.'.format(name))
49  return
50  _init_impl(name)
51 
52 
53 _IMPORTED_DYNDEPS = set()
54 
55 
56 def GetImportedOpsLibraries():
57  return _IMPORTED_DYNDEPS
58 
59 
60 def _init_impl(path):
61  _IMPORTED_DYNDEPS.add(path)
62  with extension_loader.DlopenGuard():
63  ctypes.CDLL(path)
64  # reinitialize available ops
65  core.RefreshRegisteredOperators()