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

Fix inference mode grad context manager #15229

Closed
Closed
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
2 changes: 1 addition & 1 deletion src/pytorch_lightning/trainer/trainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2232,7 +2232,7 @@ def _evaluation_context(accelerator: Accelerator, inference_mode: bool = True) -
and not (dist.is_available() and dist.is_initialized() and dist.get_backend() == "gloo")
and not isinstance(accelerator, HPUAccelerator)
and not isinstance(accelerator, TPUAccelerator)
else torch.no_grad
else torch.enable_grad
)
with context_manager_class():
yield
10 changes: 9 additions & 1 deletion tests/tests_pytorch/trainer/flags/test_inference_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,16 @@
def test_eval_inference_mode():
"""Testing overwriting trainer arguments."""

class BoringModelGrad(BoringModel):
def on_test_epoch_start(self) -> None:
assert torch.is_grad_enabled()
assert not torch.is_inference_mode_enabled()
return super().on_test_epoch_start()

class BoringModelNoGrad(BoringModel):
def on_test_epoch_start(self) -> None:
assert not torch.is_grad_enabled()
assert not torch.is_inference_mode_enabled()
assert torch.is_inference_mode_enabled()
return super().on_test_epoch_start()

class BoringModelForInferenceMode(BoringModel):
Expand All @@ -34,6 +40,8 @@ def on_test_epoch_start(self) -> None:
return super().on_test_epoch_start()

trainer = Trainer(logger=False, inference_mode=False, fast_dev_run=True)
trainer.test(BoringModelGrad())
trainer = Trainer(logger=False, inference_mode=True, fast_dev_run=True)
trainer.test(BoringModelNoGrad())
trainer = Trainer(logger=False, inference_mode=True, fast_dev_run=True)
trainer.test(BoringModelForInferenceMode())