From 1423c0d9f1f1924d94868c1e2c991878b9ea15b9 Mon Sep 17 00:00:00 2001 From: Zhiping Xiu Date: Wed, 12 Dec 2018 01:32:28 -0800 Subject: [PATCH] Add EmptyNameScope to allow you jump out from current scope. (#14631) Summary: Pull Request resolved: https://github.com/pytorch/pytorch/pull/14631 adding a empty name scope to allow people jump out from current namescope. This could be useful when you want to access blob from parent or sibling scope. Facebook: e.g: we encoutered a potential usecase in D13124249 (it's a large diff, please search by EmptyNameScope in that diff), we need to access to a blob declared in root namescope from a device namescope (device namescope has been used by parallel_GPU API). `EmptyNameScope` can help us do that with ease. I referenced to `EmptyDeviceScope` D6103412 while implementing this one. Reviewed By: yinghai Differential Revision: D13272240 fbshipit-source-id: d4cde5abcc2336e456b6c6ef086266ef94d86da8 --- caffe2/python/scope.py | 17 +++++++++++++++++ caffe2/python/scope_test.py | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/caffe2/python/scope.py b/caffe2/python/scope.py index 47e89f1..be05aa4 100644 --- a/caffe2/python/scope.py +++ b/caffe2/python/scope.py @@ -87,6 +87,23 @@ def DeviceScope(scope, node_name=None): @contextlib.contextmanager +def EmptyNameScope(): + """ + Allow users to 'disable' the name scope behaviour. + + This sets the CurrentNameScope() to None, so that the field is + not set in CreateOperator(...), etc. + """ + old_scope = CurrentNameScope() + try: + _threadlocal_scope.namescope = '' + yield + finally: + _threadlocal_scope.namescope = old_scope + return + + +@contextlib.contextmanager def EmptyDeviceScope(): """ Allow users to 'disable' the device scope behaviour (so it can be diff --git a/caffe2/python/scope_test.py b/caffe2/python/scope_test.py index d51488d..b24fc68 100644 --- a/caffe2/python/scope_test.py +++ b/caffe2/python/scope_test.py @@ -55,6 +55,14 @@ class TestScope(unittest.TestCase): self.assertEquals(scope.CurrentNameScope(), "") + def testEmptyNamescopeBasic(self): + self.assertEquals(scope.CurrentNameScope(), "") + + with scope.NameScope("test_scope"): + with scope.EmptyNameScope(): + self.assertEquals(scope.CurrentNameScope(), "") + self.assertEquals(scope.CurrentNameScope(), "test_scope/") + def testDevicescopeBasic(self): self.assertEquals(scope.CurrentDeviceScope(), None) -- 2.7.4