Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 123 additions & 0 deletions tests/unit/test_lit.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,129 @@ def test_unbatch_outputs(self):
assert result[0]["logits"].shape == (5, 10)
assert result[0]["tokens"] == ["a", "b"]

@pytest.fixture(params=["gpt2", "bloom"])
def gradient_model(self, request):
"""Tiny random bridges and an in-memory tokenizer keep salience tests offline."""
from tokenizers import Tokenizer
from tokenizers.models import WordLevel
from tokenizers.pre_tokenizers import Whitespace
from transformers import (
AutoModelForCausalLM,
BloomConfig,
GPT2Config,
PreTrainedTokenizerFast,
)

from transformer_lens.model_bridge.sources import build_bridge_from_module

torch.manual_seed(0)
vocab = {"UNK": 0, "BOS": 1, "EOS": 2, "a": 3, "b": 4, "c": 5}
raw_tokenizer = Tokenizer(WordLevel(vocab, unk_token="UNK"))
raw_tokenizer.pre_tokenizer = Whitespace()
tokenizer = PreTrainedTokenizerFast(
tokenizer_object=raw_tokenizer, bos_token="BOS", eos_token="EOS", unk_token="UNK"
)
# Untied weights keep the reference gradient free of the unembedding contribution.
config = (
GPT2Config(
vocab_size=len(vocab),
n_positions=8,
n_embd=16,
n_layer=1,
n_head=2,
tie_word_embeddings=False,
)
if request.param == "gpt2"
else BloomConfig(
vocab_size=len(vocab),
hidden_size=16,
n_layer=1,
n_head=2,
tie_word_embeddings=False,
)
)
config._attn_implementation = "eager"
hf_model = AutoModelForCausalLM.from_config(config).eval()
embedding_weight = hf_model.get_input_embeddings().weight
model = build_bridge_from_module(
hf_model,
type(hf_model).__name__,
hf_config=config,
tokenizer=tokenizer,
device="cpu",
).eval()
return model, embedding_weight

@pytest.mark.parametrize("target_idx", [None, 1, 2, -1, -2])
def test_compute_token_gradients_matches_forward(self, gradient_model, target_idx):
"""Salience includes learned positions and Bloom's embedding normalization."""
from transformer_lens.lit.utils import compute_token_gradients

model, embedding_weight = gradient_model
token_ids = model.to_tokens("a b c", prepend_bos=True)
assert token_ids.tolist() == [[1, 3, 4, 5]]
resolved_idx = {None: 3, 1: 1, 2: 2, -1: 3, -2: 2}[target_idx]

model.zero_grad(set_to_none=True)
model(token_ids)[0, resolved_idx - 1, token_ids[0, resolved_idx]].backward()
# Each id occurs once, so its weight-row gradient is its lookup-output gradient.
assert embedding_weight.grad is not None
expected = embedding_weight.grad[token_ids[0]].detach().clone()
inputs = embedding_weight.detach()[token_ids[0]]
model.zero_grad(set_to_none=True)

with torch.no_grad():
grad_l2, grad_dot_input, tokens = compute_token_gradients(
model, "a b c", target_idx=target_idx
)

assert tokens == ["BOS", "a", "b", "c"]
assert grad_l2 is not None and grad_dot_input is not None
np.testing.assert_allclose(grad_l2, expected.norm(dim=-1).numpy(), rtol=1e-5, atol=1e-7)
np.testing.assert_allclose(
grad_dot_input, (expected * inputs).sum(dim=-1).numpy(), rtol=1e-5, atol=1e-7
)
assert np.all(grad_l2[:resolved_idx] > 0)
assert np.all(grad_l2[resolved_idx:] == 0)
assert not model.hook_dict["embed.hook_out"].fwd_hooks

@pytest.mark.parametrize("target_idx", [0, 4, 5, -4, -5])
def test_compute_token_gradients_invalid_target(self, gradient_model, target_idx):
"""Targets must resolve to an existing token with a preceding position."""
from transformer_lens.lit.utils import compute_token_gradients

model, _ = gradient_model
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.

compute_token_gradients(model, "a b c", target_idx=target_idx)

def test_lit_model_compute_gradients_matches_forward(self, gradient_model):
"""The LIT wrapper's salience gradients also cover positions and embed_ln."""
from types import SimpleNamespace

from transformer_lens.lit.constants import OUTPUT_FIELDS
from transformer_lens.lit.model import (
TransformerLensLIT,
TransformerLensLITConfig,
)

model, embedding_weight = gradient_model
token_ids = model.to_tokens("a b c", prepend_bos=True)
model.zero_grad(set_to_none=True)
model(token_ids)[0, -2, token_ids[0, -1]].backward()
assert embedding_weight.grad is not None
expected = embedding_weight.grad[token_ids[0]].detach().clone()
model.zero_grad(set_to_none=True)

# Only model and config are read, so LIT itself is not needed here.
wrapper = SimpleNamespace(model=model, config=TransformerLensLITConfig(device="cpu"))
with torch.no_grad():
output = TransformerLensLIT._compute_gradients(wrapper, "a b c", {})

np.testing.assert_allclose(
output[OUTPUT_FIELDS.GRAD_L2], expected.numpy(), rtol=1e-5, atol=1e-7
)
assert not model.hook_dict["embed.hook_out"].fwd_hooks

def test_get_model_info(self, mock_hooked_transformer):
"""Test model info extraction."""
from transformer_lens.lit.utils import get_model_info
Expand Down
38 changes: 15 additions & 23 deletions transformer_lens/lit/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,24 +551,19 @@ def _compute_gradients(
# Get target mask if provided
target_mask = example.get(INPUT_FIELDS.TARGET_MASK)

# Get embeddings with gradient tracking
input_embeds: Optional[torch.Tensor] = None

def capture_embeddings(out: torch.Tensor, hook: Any) -> torch.Tensor:
nonlocal input_embeds
input_embeds = out.detach().clone().requires_grad_(True)
return input_embeds

with torch.enable_grad():
# Get input embeddings and make them a leaf tensor for gradients
embed = self.model.embed(input_tokens).detach().clone()
embed.requires_grad_(True)

# Add positional embeddings if applicable
if self.model.cfg.positional_embedding_type == "standard":
# W_pos indexed by POSITION. Calling pos_embed(input_tokens) on
# a bridge routes to HF's wpe, which embeds whatever ids it is
# given — token ids, here — silently producing wrong positions.
pos_embed = self.model.W_pos[: input_tokens.shape[1]].unsqueeze(0)
residual = embed + pos_embed
else:
residual = embed

# Forward through the rest of the model
logits = self.model(residual, start_at_layer=0)
# Make the raw token lookup a leaf tensor. The model's own forward then
# applies positions and any embedding normalization (e.g. Bloom's embed_ln).
logits = self.model.run_with_hooks(
input_tokens, fwd_hooks=[("embed.hook_out", capture_embeddings)]
)

# Compute loss or target logit
if target_mask is not None:
Expand All @@ -583,12 +578,9 @@ def _compute_gradients(
# Backward pass
target_logit.backward()

# Get gradients - now embed is a leaf tensor so grad should be populated
if embed.grad is None:
# Fallback: return zeros if gradients couldn't be computed
gradients = torch.zeros_like(embed[0])
else:
gradients = embed.grad[0] # [seq_len, d_model]
if input_embeds is None or input_embeds.grad is None:
raise RuntimeError("embed.hook_out did not run, so no embedding gradient was captured")
gradients = input_embeds.grad[0] # [seq_len, d_model]

# Return the full gradient tensor - LIT computes norms internally
# TokenGradients expects shape [num_tokens, emb_dim]
Expand Down
54 changes: 37 additions & 17 deletions transformer_lens/lit/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,40 +234,60 @@ def compute_token_gradients(
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List[str]]:
"""Compute token-level gradients for salience.

Uses gradient of the loss with respect to token embeddings to compute
importance scores for each token.
Uses the gradient of the target logit with respect to raw token embeddings
to compute importance scores. The model's forward applies all subsequent
embedding processing, including positions, normalization, and scaling.

Args:
model: TransformerLens model.
text: Input text.
target_idx: Target token index for gradient computation.
If None, uses the last token.
target_idx: Index of the target token. Its logit at the previous
position is the salience target. Negative values count
from the end. If None, uses the last token.
prepend_bos: Whether to prepend BOS token.

Returns:
Tuple of (grad_l2, grad_dot_input, tokens) where:
- grad_l2: L2 norm of gradients per token [seq_len]
- grad_dot_input: Gradient dot input embedding per token [seq_len]
- tokens: List of token strings

Raises:
ValueError: If target_idx does not point to a token after the first one.
"""
# Tokenize
tokens, token_ids = get_tokens_from_model(model, text, prepend_bos=prepend_bos)
token_ids = token_ids.unsqueeze(0).to(model.cfg.device)
seq_len = token_ids.shape[1]

input_embeds = model.embed(token_ids)
input_embeds.requires_grad_(True)

# Forward pass
logits = model(input_embeds, start_at_layer=0)

# Determine target
# Determine target: the token at target_idx, predicted from the position before it
if target_idx is None:
target_idx = -1 # Last token

# Get target logit and compute gradient
target_logit = logits[0, target_idx, token_ids[0, target_idx + 1]]
target_logit.backward()

target_idx = seq_len - 1 # Last token
elif target_idx < 0:
target_idx += seq_len
if not 1 <= target_idx < seq_len:
raise ValueError(
f"target_idx must point to a token after the first one, got {target_idx} "
f"for {seq_len} tokens"
)

input_embeds: Optional[torch.Tensor] = None

def capture_embeddings(out: torch.Tensor, hook: Any) -> torch.Tensor:
nonlocal input_embeds
input_embeds = out.detach().clone().requires_grad_(True)
return input_embeds

with torch.enable_grad():
# hook_embed can alias post-normalization embeddings (e.g. Bloom).
logits = model.run_with_hooks(token_ids, fwd_hooks=[("embed.hook_out", capture_embeddings)])

# Get target logit and compute gradient
target_logit = logits[0, target_idx - 1, token_ids[0, target_idx]]
target_logit.backward()

if input_embeds is None or input_embeds.grad is None:
raise RuntimeError("embed.hook_out did not run, so no embedding gradient was captured")
gradients = input_embeds.grad[0] # [seq_len, d_model]

# Compute gradient L2 norm per token
Expand Down
Loading