Caffe2 - Python API
A deep learning, cross platform ML framework
scope.py
1 
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 contextlib
9 import threading
10 
11 from caffe2.proto import caffe2_pb2
12 
13 # Python 2 and 3 compatibility: test if basestring exists
14 try:
15  basestring # NOQA
16 except NameError:
17  # This is python3 so we define basestring.
18  basestring = str
19 
20 # The name scope and device scope when creating a new operator.
21 _NAMESCOPE_SEPARATOR = '/'
22 
23 _threadlocal_scope = threading.local()
24 
25 
26 def CurrentNameScope():
27  global _threadlocal_scope
28  if not hasattr(_threadlocal_scope, "namescope"):
29  _threadlocal_scope.namescope = ''
30  return _threadlocal_scope.namescope
31 
32 
33 def CurrentDeviceScope():
34  global _threadlocal_scope
35  if not hasattr(_threadlocal_scope, "devicescope"):
36  _threadlocal_scope.devicescope = None
37  return _threadlocal_scope.devicescope
38 
39 
40 @contextlib.contextmanager
41 def NameScope(prefix, reset=False):
42  global _threadlocal_scope
43  assert isinstance(prefix, basestring), \
44  "NameScope takes in a string as its argument."
45  old_scope = CurrentNameScope()
46  prefix = prefix + _NAMESCOPE_SEPARATOR if prefix is not '' else ''
47  if reset:
48  _threadlocal_scope.namescope = prefix
49  else:
50  _threadlocal_scope.namescope = _threadlocal_scope.namescope + prefix
51  yield
52  assert _threadlocal_scope.namescope.endswith(prefix), \
53  "The namescope variable is changed from outside NameScope() calls."
54  _threadlocal_scope.namescope = old_scope
55 
56 
57 @contextlib.contextmanager
58 def DeviceScope(scope):
59  assert isinstance(scope, caffe2_pb2.DeviceOption), \
60  "DeviceScope takes in a caffe2_pb2.DeviceOption as its argument."
61  global _threadlocal_scope
62  old_scope = CurrentDeviceScope()
63  _threadlocal_scope.devicescope = scope
64  yield
65  assert _threadlocal_scope.devicescope == scope, \
66  "The device scope is changed from outside DeviceScope() calls."
67  _threadlocal_scope.devicescope = old_scope