Repository navigation
fix(predict): run inference under torch.no_grad (closes #111) - #113
Merged
Merged
Conversation
predict() no longer builds an autograd graph for its forward pass, which saves memory and time at inference. Captum integrated gradients are wrapped in torch.enable_grad() so explanations keep working even when predict() is itself called from a user-level torch.no_grad() context. Closes #111 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
predict()now runs its forward pass undertorch.no_grad(): no autograd graph is built at inference, which lowers memory usage and speeds up prediction. Users no longer need a custom wrapper for this.explain_with_captum=True) are wrapped intorch.enable_grad(), so explanations still work, even whenpredict()is called from inside a user-leveltorch.no_grad()block.Closes #111
Tests
New file
tests/test_predict_no_grad.py:test_predict_does_not_track_gradients: a forward hook checks that grad mode is off and the output has norequires_gradduringpredict(), and that the global grad mode is restored afterwards. It fails onmainand passes with this change.test_predict_captum_works_under_user_no_grad: Captum attributions computed insidetorch.no_grad()are non-zero, finite, and identical to those computed outside it.test_predict_no_grad,test_torchTextClassifiers,test_componentsandtest_sample_weightspass (35 tests).🤖 Generated with Claude Code