Skip to content

fix(predict): run inference under torch.no_grad (closes #111) - #113

Merged
meilame-tayebjee merged 1 commit into
mainfrom
fix/predict-no-grad
Nov 24, 2026
Merged

meilame-tayebjee merged 1 commit into
mainfrom
fix/predict-no-grad

Conversation

@meilame-tayebjee

Copy link
Copy Markdown
Member

Summary

  • predict() now runs its forward pass under torch.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.
  • Captum integrated gradients (explain_with_captum=True) are wrapped in torch.enable_grad(), so explanations still work, even when predict() is called from inside a user-level torch.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 no requires_grad during predict(), and that the global grad mode is restored afterwards. It fails on main and passes with this change.
  • test_predict_captum_works_under_user_no_grad: Captum attributions computed inside torch.no_grad() are non-zero, finite, and identical to those computed outside it.

test_predict_no_grad, test_torchTextClassifiers, test_components and test_sample_weights pass (35 tests).

🤖 Generated with Claude Code

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>
@meilame-tayebjee
meilame-tayebjee merged commit 8e20892 into main Nov 24, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Disable gradient calculation

1 participant