You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Bug Report] lit.utils.compute_token_gradients targets the BOS token and crashes on a None grad #2045
transformer_lens.lit.utils.compute_token_gradients doesn't work as a salience helper:
With the default target_idx=None it sets target_idx = -1 and reads logits[0, -1, token_ids[0, target_idx + 1]], so the target is token_ids[0, 0], the BOS token, not the last token the docstring promises.
model.embed(token_ids) is not a leaf tensor (it comes from the embedding weights), so input_embeds.grad stays None after backward() and input_embeds.grad[0] raises TypeError: 'NoneType' object is not subscriptable.
It calls model(input_embeds, start_at_layer=0) without adding positional embeddings, so for models with positional_embedding_type == "standard" the forward pass sees no positions.
LitModel._compute_gradients in lit/model.py already handles all three (detached leaf embeddings, W_pos added, last token predicted from the second-to-last position), so the helper is just out of sync with it.
Code example
importtorchfromunittest.mockimportMagicMockfromtransformer_lens.lit.utilsimportcompute_token_gradientsmodel=MagicMock(side_effect=lambdar, start_at_layer=0: torch.nn.functional.linear(r, torch.randn(6, 8)))
model.cfg.device="cpu"model.cfg.positional_embedding_type="standard"model.embed=torch.nn.Embedding(6, 8)
model.W_pos=torch.randn(4, 8)
model.to_tokens.return_value=torch.tensor([[0, 3, 1, 4]])
model.tokenizer.convert_ids_to_tokens.return_value= ["<s>", "a", "b", "c"]
compute_token_gradients(model, "a b c")
# TypeError: 'NoneType' object is not subscriptable
System Info
Installed from source on dev
macOS
Python 3.12
Additional context
I have a small fix ready that makes the helper match LitModel._compute_gradients: target_idx is the index of the target token (default: the last one, negative values count from the end) and its logit is read at the position before it.
Checklist
I have checked that there is no similar issue in the repo (required)
Activity