Skip to content

fix(lit): make compute_token_gradients target the last token - #2046

Merged
jlarson4 merged 3 commits into
TransformerLensOrg:devfrom
nurlanmnn-open-source:fix-lit-token-gradients
Nov 25, 2026
Merged

jlarson4 merged 3 commits into
TransformerLensOrg:devfrom
nurlanmnn-open-source:fix-lit-token-gradients

Conversation

@nurlanmnn

Copy link
Copy Markdown

Description

lit.utils.compute_token_gradients couldn't give a usable salience map. It crashed reading .grad from 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 way LitModel._compute_gradients already does.

Fixes #2045

Changes in transformer_lens/lit/utils.py:

  • The embeddings are detached and cloned into a leaf tensor, so backward() fills their .grad.
  • W_pos[:seq_len] is added before the forward pass when positional_embedding_type == "standard", since start_at_layer=0 skips the embedding step.
  • target_idx is the index of the target token, as the docstring says. Its logit is read at the position before it. None means the last token, negative values count from the end, and a target_idx that points at the first token (nothing predicts it) raises a ValueError.

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Checklist:

  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation (docstring)
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have not rewritten tests relating to key interfaces which would affect backward compatibility

New TestUtils.test_compute_token_gradients_targets_last_token in tests/unit/test_lit.py uses a tiny embedding + linear model and checks the gradients against a hand-computed last-token target. It fails on dev (the TypeError) 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

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>
Comment thread transformer_lens/lit/utils.py Outdated
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":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/unit/test_lit.py Outdated
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)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread tests/unit/test_lit.py
# The last position predicts no token, so it gets no gradient.
assert grad_l2[-1] == 0

with pytest.raises(ValueError, match="target_idx"):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jlarson4

Copy link
Copy Markdown
Collaborator

Thank you for putting this together @nurlanmnn! I added a couple notes above, let me know if you have any questions

nurlanmnn and others added 2 commits November 24, 2026 13:20
…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>
@jlarson4

Copy link
Copy Markdown
Collaborator

Looks good! merging now

@jlarson4
jlarson4 merged commit a16ee85 into TransformerLensOrg:dev Nov 25, 2026
31 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.

[Bug Report] lit.utils.compute_token_gradients targets the BOS token and crashes on a None grad

2 participants