Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Dy2stat]fix no_grad context error in dy2stat #35725

Merged
merged 4 commits into from
Sep 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions paddle/fluid/pybind/pybind.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1241,6 +1241,17 @@ All parameter, weight, gradient are variables in Paddle.
return self.GetMutable<framework::ReaderHolder>();
},
py::return_value_policy::reference)
.def("get_scope",
[](Variable &self) -> Scope * {
auto scope_vec =
self.GetMutable<std::vector<framework::Scope *>>();
PADDLE_ENFORCE_GT(
scope_vec->size(), 0,
platform::errors::InvalidArgument(
"The size of scope_vec should be greater than 0"));
return scope_vec->front();
},
py::return_value_policy::reference)
.def("set_scope", [](Variable &self, Scope &scope) {
auto scope_vec = self.GetMutable<std::vector<framework::Scope *>>();
scope_vec->emplace_back(&scope);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,10 +290,15 @@ def __call__(self, inputs):
self._valid_vars(self._params),
self._valid_vars(out_vars), self._tmp_scope_vec, self._double_grads,
*attrs)

self.drop_scope_if_no_grad()
restored_nest_out = self._restore_out(out_vars)
return self._remove_no_value(restored_nest_out)

def drop_scope_if_no_grad(self):
tracer = framework._dygraph_tracer()
if self.training and not tracer._has_grad:
self._tmp_scope_vec.value().get_scope().drop_kids()

@property
def program(self):
if self.training:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,21 @@ def test_switch_eval_and_train(self):
partial_layer._train_program)


class TestWithNoGrad(unittest.TestCase):
def test_with_no_grad(self):
with fluid.dygraph.guard():
linear_net = Linear()
x_data = np.random.random((5, 10)).astype('float32')
x = fluid.dygraph.to_variable(x_data)

with paddle.no_grad():
linear_net.train()
linear_net(x)
_, partial_layer = linear_net.forward.program_cache.last()[-1]
self.assertEqual(partial_layer.program,
partial_layer._train_program)


class GPT2LMHeadModel(fluid.dygraph.Layer):
def __init__(self):
super(GPT2LMHeadModel, self).__init__()
Expand Down