Separate attention-map capture from gradient hooks - #1232
Draft
LIU-kaiyu wants to merge 1 commit into
Draft
Conversation
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.
Fixes #1166.
AttentionRollout previously enabled backward hooks despite using only attention maps, causing it to fail inside torch.no_grad(). This change separates map capture from gradient capture in Transformer and StageAttentionNet.
Introduces AttentionInterpretable and its subclass GradientInterpretable, retaining CheferInterpretable as an alias. Rollout explicitly requests forward-only capture and runs without autograd; Chefer explicitly requests gradients. Attribution calculations remain unchanged.
Existing positional register_hook arguments and concrete models’ one-argument hook behavior are preserved. Disabling capture stops both modes while retaining the latest results; the next attention forward clears stale gradients and replaces or clears the map. Chefer now raises clear errors for empty layers, missing tensors, and mismatched map/gradient shapes.
Compatibility: custom models must explicitly inherit the appropriate interface and accept the capture_gradients keyword. The alias does not adapt obsolete method signatures. Overlapping captured forwards/backwards on one model remain unsupported and are documented.
Validation: 36 focused tests passed in Pixi, including 11 new tests covering no-grad execution, unchanged parameter gradients, interpreter switching, cache lifecycle, positional compatibility, migration errors, and failure cleanup. All changed executable statements were covered. The synthetic example, new docstring examples, and #1166-specific contribution checks passed.