From 4cf96cd307910047f65282afb20d5ae50ccf2d64 Mon Sep 17 00:00:00 2001 From: Huihuang Zheng Date: Tue, 5 Nov 2019 11:35:40 +0800 Subject: [PATCH] Add grad_name Property for Class Variable (#20991) --- python/paddle/fluid/framework.py | 20 +++++++++++++++++++ .../fluid/tests/unittests/test_variable.py | 2 ++ 2 files changed, 22 insertions(+) diff --git a/python/paddle/fluid/framework.py b/python/paddle/fluid/framework.py index 5a68fe449ce..45cca7ad588 100644 --- a/python/paddle/fluid/framework.py +++ b/python/paddle/fluid/framework.py @@ -1131,6 +1131,26 @@ class Variable(object): else: return cpt.to_text(self.desc.name()) + @property + def grad_name(self): + """ + Indicating name of the gradient Variable of current Variable. + + **Notes: This is a read-only property. It simply returns name of + gradient Variable from a naming convention but doesn't guarantee + the gradient exists.** + + Examples: + .. code-block:: python + + import paddle.fluid as fluid + + x = fluid.data(name="x", shape=[-1, 23, 48], dtype='float32') + print(x.grad_name) # output is "x@GRAD" + + """ + return self.name + "@GRAD" + @name.setter def name(self, new_name): if in_dygraph_mode(): diff --git a/python/paddle/fluid/tests/unittests/test_variable.py b/python/paddle/fluid/tests/unittests/test_variable.py index d72511ee0f0..79e73aa8ea5 100644 --- a/python/paddle/fluid/tests/unittests/test_variable.py +++ b/python/paddle/fluid/tests/unittests/test_variable.py @@ -44,12 +44,14 @@ class TestVariable(unittest.TestCase): self.assertEqual(core.VarDesc.VarType.FP64, w.dtype) self.assertEqual((784, 100), w.shape) self.assertEqual("fc.w", w.name) + self.assertEqual("fc.w@GRAD", w.grad_name) self.assertEqual(0, w.lod_level) w = b.create_var(name='fc.w') self.assertEqual(core.VarDesc.VarType.FP64, w.dtype) self.assertEqual((784, 100), w.shape) self.assertEqual("fc.w", w.name) + self.assertEqual("fc.w@GRAD", w.grad_name) self.assertEqual(0, w.lod_level) self.assertRaises(ValueError, -- GitLab