Skip to content

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

Done

Description

@nurlanmnn

Describe the bug

transformer_lens.lit.utils.compute_token_gradients doesn't work as a salience helper:

  1. 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.
  2. 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.
  3. 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

import torch
from unittest.mock import MagicMock
from transformer_lens.lit.utils import compute_token_gradients

model = MagicMock(side_effect=lambda r, 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions