diff --git a/paddle/fluid/imperative/variable_wrapper.h b/paddle/fluid/imperative/variable_wrapper.h index fec12f2da13c1ef724d3b94dbab86e4bae1e6cba..5922bfcdb9fbb99b993b532de7f012afd9edf019 100644 --- a/paddle/fluid/imperative/variable_wrapper.h +++ b/paddle/fluid/imperative/variable_wrapper.h @@ -35,6 +35,8 @@ class VariableWrapper { explicit VariableWrapper(const std::string& name) : name_(name) {} + ~VariableWrapper() { VLOG(10) << "Destruct VariableWrapper: " << Name(); } + const framework::Variable& Var() const { return var_; } framework::Variable* MutableVar() { return &var_; } diff --git a/python/paddle/fluid/dygraph/base.py b/python/paddle/fluid/dygraph/base.py index 5868c9d078c2348161f7004556cc580b2ff65187..78cc9afde071687548ab74db601739aef226e218 100644 --- a/python/paddle/fluid/dygraph/base.py +++ b/python/paddle/fluid/dygraph/base.py @@ -326,13 +326,13 @@ class no_grad_: def __enter__(self): tracer = framework._dygraph_tracer() if tracer: - self.orig = tracer._train_mode - tracer._train_mode = False + self.orig = tracer._has_grad + tracer._has_grad = False def __exit__(self, *args): tracer = framework._dygraph_tracer() if tracer: - tracer._train_mode = self.orig + tracer._has_grad = self.orig @signature_safe_contextmanager diff --git a/python/paddle/fluid/tests/unittests/test_imperative_basic.py b/python/paddle/fluid/tests/unittests/test_imperative_basic.py index d2f143d7ad44035ff2241bd6d830b88a6a3b548a..e33e7247d02380d8a68534a6eae80a5e0b9ffdf6 100644 --- a/python/paddle/fluid/tests/unittests/test_imperative_basic.py +++ b/python/paddle/fluid/tests/unittests/test_imperative_basic.py @@ -288,13 +288,13 @@ class TestImperative(unittest.TestCase): self.assertTrue(l1.weight.stop_gradient is False) tmp = l1.weight * 2 print(tmp) - self.assertFalse(tmp.stop_gradient) + self.assertTrue(tmp.stop_gradient) x = fluid.dygraph.to_variable(data) y = l0(x) + tmp o = l1(y) o.backward() - self.assertTrue(tmp._grad_ivar() is not None) + self.assertTrue(tmp._grad_ivar() is None) self.assertTrue(l0.weight._grad_ivar() is not None) def test_sum_op(self): diff --git a/python/paddle/fluid/tests/unittests/test_imperative_decorator.py b/python/paddle/fluid/tests/unittests/test_imperative_decorator.py index 7d20a9b952e998191f786bb5d2d0505edd9d3d2f..6f86a0c0d65227f772bf33caddc94679459b196a 100644 --- a/python/paddle/fluid/tests/unittests/test_imperative_decorator.py +++ b/python/paddle/fluid/tests/unittests/test_imperative_decorator.py @@ -79,7 +79,8 @@ class TestTracerMode2(TestTracerMode): class TestNoGradClass(unittest.TestCase): @paddle.no_grad() def no_grad_func(self, a): - self.assertEqual(self.tracer._train_mode, False) + self.assertEqual(self.tracer._train_mode, True) + self.assertEqual(self.tracer._has_grad, False) return a def test_main(self):