Fix backward hooks Runtime Error#1175
Open
evcyen wants to merge 1 commit intoTransformerLensOrg:mainfrom
Open
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.
Description
Fixes backward hooks that return the gradient raising
RuntimeError: hook 'hook' has changed the size of value(issue #1160).Root cause: PyTorch's
register_full_backward_hookexpects the hook to return eitherNoneor a tuple of tensors that replacesgrad_input. TransformerLens was passing the user's return value through unchanged. When the user returned a single tensor, PyTorch received a tensor instead of a tuple and raised "hook has changed the size of value."Fix: In
hook_points.py, the wrapper for backward hooks now normalizes the return value before returning to PyTorch. if the user returns a single tensor, we wrap it as(result,). if they already return a one-element tuple, we pass it through.Tests: Existing test
test_backward_hook_runs_successfullystill passes. A minimal repro script that returns a bare tensor now runs without error.Minimal Repro Script:
Fixes #1160
Type of change
Checklist: