Repository navigation
Conversation
The helper read the logit for token_ids[0, target_idx + 1], which wraps to the BOS token for the default target_idx=-1. It also read .grad from a non-leaf embedding tensor (None) and skipped positional embeddings. Now it matches LitModel._compute_gradients. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| input_embeds.requires_grad_(True) | ||
|
|
||
| # start_at_layer=0 skips the embedding step, so add positional embeddings here | ||
| if model.cfg.positional_embedding_type == "standard": |
There was a problem hiding this comment.
Resuming at layer 0 requires this function to recreate everything the model does between the embedding lookup and the first block. Right now, it only recreates learned positions. Bloom also normalizes its embeddings there, meaning it gets a salience map that is not valid. Can we find a way to ensure all steps that occur before the first block are properly handled?
There was a problem hiding this comment.
Changed in 28317d9: compute_token_gradients no longer rebuilds the residual for start_at_layer=0. It runs the normal forward and captures a leaf tensor at embed.hook_out (the raw lookup, before positions and embed_ln), so every pre-block step is done by the model itself. The new tests check the result against the embedding-weight gradient from a plain model(tokens) backward on tiny GPT-2 and Bloom bridges, and the Bloom cases fail with the previous implementation.
There was a problem hiding this comment.
LitModel._compute_gradients in lit/model.py rebuilt the residual the same way, so I changed it too in 30fb225: it now captures embed.hook_out like compute_token_gradients. The new test_lit_model_compute_gradients_matches_forward compares it with the plain-backward reference on the tiny GPT-2 and Bloom bridges, and its Bloom case fails with the old code. pytest tests/unit/test_lit.py (38 passed, 21 skipped), black, isort and mypy . pass locally.
| def forward(residual, start_at_layer=0): | ||
| # Causal running mean so every logit depends on earlier tokens. | ||
| steps = torch.arange(1, residual.shape[1] + 1).view(1, -1, 1) | ||
| return unembed(residual.cumsum(dim=1) / steps) |
There was a problem hiding this comment.
This forward is linear in the residual, so the gradients come out the same whether or not W_pos is added, and the test still passes with that step removed. Can the mock be made to depend on the residual's value so the positional part of the fix is covered?
There was a problem hiding this comment.
Replaced the linear mock in 28317d9 with tiny random GPT-2 and Bloom bridges built offline, so the logits depend non-linearly on the residual. I checked that dropping the W_pos step from the previous implementation now fails the GPT-2 cases.
| # The last position predicts no token, so it gets no gradient. | ||
| assert grad_l2[-1] == 0 | ||
|
|
||
| with pytest.raises(ValueError, match="target_idx"): |
There was a problem hiding this comment.
Only the default target and the rejected target_idx=0 are checked. Negative-index handling and the upper bound can both be removed without causing a test failure. Can we add a positive and a negative explicit index test?
There was a problem hiding this comment.
Added in 28317d9: target_idx cases 1, 2, -1, -2 (plus the default) compared against the reference gradient, and 0, 4, 5, -4, -5 must raise ValueError. Removing the negative-index handling or the upper bound each fails 4 tests. pytest tests/unit/test_lit.py, make format and mypy . pass locally.
|
Thank you for putting this together @nurlanmnn! I added a couple notes above, let me know if you have any questions |
…ute_token_gradients Capture a leaf tensor at embed.hook_out during a normal forward instead of rebuilding the residual for start_at_layer=0, so positional embeddings, Bloom's embedding LayerNorm and any other pre-block step are included. Tests use tiny offline GPT-2 and Bloom bridges with an independent embedding-weight gradient reference, plus explicit positive, negative and out-of-range target_idx cases. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The LIT wrapper rebuilt the residual for start_at_layer=0 the same way compute_token_gradients used to, so it skipped pre-block steps such as Bloom's embedding LayerNorm. It now runs the normal forward and takes the gradient at embed.hook_out, like compute_token_gradients. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Looks good! merging now |
Description
lit.utils.compute_token_gradientscouldn't give a usable salience map. It crashed reading.gradfrom a non-leaf embedding tensor, it left out positional embeddings, and its default target wrapped around to the BOS token instead of the last token. This makes it work the same wayLitModel._compute_gradientsalready does.Fixes #2045
Changes in
transformer_lens/lit/utils.py:backward()fills their.grad.W_pos[:seq_len]is added before the forward pass whenpositional_embedding_type == "standard", sincestart_at_layer=0skips the embedding step.target_idxis the index of the target token, as the docstring says. Its logit is read at the position before it.Nonemeans the last token, negative values count from the end, and atarget_idxthat points at the first token (nothing predicts it) raises aValueError.Type of change
Checklist:
New
TestUtils.test_compute_token_gradients_targets_last_tokenintests/unit/test_lit.pyuses a tiny embedding + linear model and checks the gradients against a hand-computed last-token target. It fails ondev(theTypeError) and passes with the fix.pytest tests/unit/test_lit.py: 17 passed, 21 skipped (LIT not installed). black, isort and mypy are clean.🤖 Generated with Claude Code