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 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -296,15 +296,17 @@ def __call__(self, inputs):

@property
def program(self):
if self.training:
tracer = framework._dygraph_tracer()
if self.training and tracer._has_grad:
return self._train_amp_program if _in_amp_guard(
) else self._train_program
else:
return self._infer_program

@property
def program_id(self):
if self.training:
tracer = framework._dygraph_tracer()
if self.training and tracer._has_grad:
return self._train_amp_program_id if _in_amp_guard(
) else self._train_program_id
else:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,26 @@ 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)

linear_net.train()
linear_net(x)

_, partial_layer = linear_net.forward.program_cache.last()[-1]
self.assertEqual(partial_layer.program,
partial_layer._train_program)

with paddle.no_grad():
linear_net(x)
self.assertEqual(partial_layer.program,
partial_layer._infer_program)


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