feat(backward_lens): add vocabulary readout of GPT-2 MLP gradient factors - #1723
Open
janmenjayap wants to merge 10 commits into
Open
feat(backward_lens): add vocabulary readout of GPT-2 MLP gradient factors#1723janmenjayap wants to merge 10 commits into
janmenjayap wants to merge 10 commits into
Conversation
- Reconstruct linear weight gradients from forward inputs and output VJPs. - Support GPT-2 Conv1D and torch.nn.Linear weight layouts. - Add detached CPU contracts, validation, error metrics, and signed vocabulary rankings. - Cover numerical, validation, overflow, ownership, and ranking edge cases.
- Validate raw GPT-2 Bridge models, prompts, targets, layers, and original Conv1D weights. - Capture both MLP projections with one forward pass and one autograd call. - Reconstruct exact weight gradients and return detached CPU-owned factors. - Preserve model state, RNG, gradients, and existing hooks with comprehensive integration coverage.
…ry space - Add public BackwardLens.analyze(prompt, target_token, layers, normalized=False) returning detached, CPU-owned result dataclasses. - Project residual-width factors through fresh ln_final and unembed, with an optional Normalized Logit Lens for low-norm factors. - Expose factor norms, zero-norm masks, signed top/bottom vocabulary rankings, token decoding, and raw-gradient target ranks. - Export the public result contracts and cover the API with model-free unit tests and GPT-2 integration tests.
- Derive the FF1 and FF2 gradient factorizations, vocabulary projections, and tensor-shape contracts. - Document the public API, raw Bridge and single-token restrictions, state-safety guarantees, and error behavior. - Explain raw versus normalized projections, zero-factor handling, gradient-versus-SGD signs, interpretation limits, and troubleshooting. - Add the guide to the documentation index and cite Katz et al. without copying external code or assets.
- Add an executed GPT-2-small walkthrough of MLP gradient factorization and vocabulary projection. - Visualize reconstruction error, numerical rank, layer-position token directions, VJP norms, and target ranks. - Compare raw and normalized projections, expose gradient-update sign semantics, mark near-zero signals, and sort cumulative reconstruction by contribution. - Save reproducible outputs and register all ten notebook cells in CI and the Makefile notebook test target.
- Suppress the narrow Typeguard instrumentation warning emitted during fresh TransformerLens imports. - Display target ranks as stable vocabulary percentiles while retaining exact ranks in the analysis data. - Regenerate all notebook outputs and verify all ten nbval cells pass.
6 tasks
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
This PR implements Backward Lens as a self-contained analysis tool for raw GPT-2 models loaded
through
TransformerBridge.Backward Lens interprets the low-rank factors of MLP weight gradients by projecting residual-width
factors into vocabulary space. It preserves the two interpretations from Katz et al. (2024):
x_i, describinginformation written into the first MLP matrix.
delta_i, describingvocabulary directions toward or away from which the second MLP matrix is updated.
For every selected layer, the implementation reconstructs the independently obtained weight
gradients using:
grad_W_in = sum_i outer(x_i, grad_pre_i)grad_W_out = sum_i outer(hidden_i, grad_out_i)Reconstruction errors and numerical ranks provide independently testable correctness invariants.
Motivation and context
TransformerLens already supports forward vocabulary readouts and the Jacobian Lens, but it did not
provide a maintained tool for interpreting parameter gradients in vocabulary space.
This feature adds that missing analysis surface without training an auxiliary model, loading a
learned artifact, applying optimizer steps, or depending on the authors' research repository.
Implementation details
BackwardLensundertransformer_lens/tools/analysis/.torch.autograd.gradcall..backward(), mutate parameter.grad, or freeze selected parameters.gradient descent.
requires_grad, existing hooks, training mode, and RNG state.Supported scope
This initial implementation supports:
TransformerBridgemodels.The following are intentionally deferred to separate follow-up issues:
Documentation and demonstration
This PR adds:
restrictions, state safety, and troubleshooting.
The notebook figures and tables were manually inspected for correctness and legibility.
Dependencies
No new dependencies are required.
Validation
Observed local validation:
uv lock --check: passedgit diff --check upstream/dev...HEAD: passedupstream/devFocused validation passed in the established
transformer-lensConda environment.Exact locked-
.venvpytest execution was blocked by a local PyTorch/CUDA runtime symbol mismatch.The documentation builder parsed the new Backward Lens page, but a complete local docs build was not
obtained because the environment lacked Pandoc and the build encountered model-registry/docstring
errors. Repository-wide checks remain subject to PR CI.
Fixes #1686
Type of change
Screenshots
Vocabulary-facing gradient factors
Reconstruction and rank diagnostics
Target-token ranks: raw versus Normalized Logit Lens
Checklist