19.1 Mechanistic Interpretability
Give a model the tokens A B X A. Suppose its next prediction is B. Did it learn in training that B often follows A, or did it copy the pair it just saw? The prediction fits both stories. Change the prompt to A C X A and the stories start making different predictions. Mechanistic interpretability goes one step further. It asks which computation inside the model makes the answer change.
1. Motivation and History
Olah and colleagues traced how earlier features in a vision network contributed to a later curve detector [1]. A transformer poses a similar question with a useful extra clue. An attention head can read one token position and add information to the residual stream at another. We can record that path, change one part of it, and measure the effect on a particular output [2].
Consider an assistant that quotes an old delivery date even though the retrieved document gives a newer one. Changing the date in the document tests whether the answer uses that evidence. Restoring a head’s output from the original run into the changed run tests a narrower hypothesis about how the date gets carried forward. A diagnosis based on one such pair still needs to work on other dates and documents.
2. The Linear Representation Hypothesis
Individual coordinates are easy to record. The feature relevant to a prediction may span many coordinates. The linear representation hypothesis motivates looking for a direction along which a distinction, such as singular versus plural, can be read out. Park and colleagues formalize distinct meanings of linear representation for reading and intervening on concepts [4].
For a simple linear readout in a chosen coordinate system, let be the residual state at one token, and a unit direction in the same -dimensional space. The score measures the component of along . Whether that score tracks number is an empirical question. Fit the direction on one set of nouns, then test on unseen nouns in different sentences.
The Problem of Arbitrary Basis
A change of coordinates makes this concrete. In two dimensions, a direction can be written as in one orthonormal basis and have two nonzero entries in another. Transform both and into the new basis and the dot product stays the same. A coordinate index alone tells us little about the feature it might encode. A successful readout also leaves open whether the model itself uses the distinction. Section 19.3 tests these issues with a linear probe.
3. Circuits and Induction Heads
A circuit is a set of connected computations that performs a particular task. Elhage and colleagues studied small attention-only transformers where two heads in different layers cooperate to copy a continuation from the prompt [2]. Olsson and colleagues connect this behavior to in-context learning. The causal evidence is strongest in the small models they could intervene on directly [3].
The Algorithm of an Induction Head
Number the tokens in A B X A from 0 to 3. A previous-token head carries information about A at position 0 into the residual state at position 1. The token at position 1 is still B. Its state now also carries a clue about its predecessor.
| Position | Input token | Predecessor available to a later head |
|---|---|---|
| 0 | A | No preceding token in this example |
| 1 | B | A |
| 2 | X | B |
| 3 | A | X |
At position 3, a later induction head uses the current A as its query. The key at position 1 matches because the token there was preceded by A. Reading its value can favor B as the prediction for position 4. There are three different positions to keep track of here: where the first A occurred (0), where the head reads (1), and where the model makes the prediction (3). [3]
The QK and OV Circuits
With row-vector notation, governs how a query matches a key. The weight matrices and project residual states into queries and keys. In the basic attention-only setting, the resulting scores are scaled, masked and normalized across eligible positions. The product describes how a source state is transformed on its way back into the residual stream. Here is the value projection and is this head’s slice of the output projection. Later layers and the final vocabulary readout still affect the answer. A head can keep attending to position 1 even if we zero the vector it writes. [2]
4. Capture One Layer’s Attention in PyTorch
A forward hook sees the outputs its module returns. With PyTorch’s MultiheadAttention, ask for weights and keep the heads separate. Otherwise the weights can be absent or averaged across heads. [6]
Scope of the example. This CPU example checks the capture code on a randomly initialized layer, in evaluation mode, with one unpadded sequence and no KV cache. It uses eager attention with explicit weights. Saving a full matrix costs entries for batch size , head count and sequence length . A pretrained model with a fused kernel may expose a different interface.
import torch
from torch import nn
torch.manual_seed(7)
attention = nn.MultiheadAttention(8, 2, batch_first=True).eval()
x = torch.randn(1, 4, 8) # batch, tokens, hidden width
future = torch.ones(4, 4, dtype=torch.bool).triu(1)
captured = []
def capture(_module, _inputs, output):
captured.append(output[1].detach())
handle = attention.register_forward_hook(capture)
try:
with torch.no_grad():
attention(x, x, x, attn_mask=future,
need_weights=True, average_attn_weights=False)
finally:
handle.remove()
weights, = captured
assert weights.shape == (1, 2, 4, 4)
assert torch.count_nonzero(weights[..., future]) == 0
torch.testing.assert_close(weights.sum(-1), torch.ones(1, 2, 4))
print(tuple(weights.shape)) # (1, 2, 4, 4)
The axes are batch, head, query position and key position. For the four-token example, weights[0, head, 3, 1] is the entry to inspect. The assertions check that the hook captured a valid causal matrix. The random layer has had no opportunity to learn the copying task.
5. Change the Earlier Pair
The trace below implements one rule. Read every visible token immediately preceded by the final query token. Try changing the earlier B to C, then zero the head’s output. Which part of the trace survives? The trace lists exact matches and candidate continuations. It has no learned weights or probability scale.
- 0A
- 1Bread
- 2X
- 3Aquery
- Which positions match?
- 1 · B (preceded by A at 0)
- Which token does the copy path favor?
- B
With two continuations, both B and C satisfy the rule. A trained model can favor one, distribute attention across both, or predict something else through another path.
What changes when one head stops writing?
We ran the pretrained SmolLM2-135M on CPU with sequences of the form [BOS] A B x y C z w A. Each letter stands for a different vocabulary ID. The final A is the only repeat. If the model copies the earlier pair, it should favor B over C. Swap their earlier positions, leaving the final query and the set of tokens unchanged, and it should favor C. [7]
We chose a head on 16 development sequences. For each of the model’s 270 query heads, we measured attention from the final position to position 2, which holds the earlier successor. We replaced the final A with a fresh token D and measured again. Layer 18, head 6 (zero-based) had the largest mean difference. On 32 new sequences with disjoint token IDs, the same head put 78.17% of its attention on position 2 with the repeated cue, against 0.084% with the fresh cue.
Does that read change the prediction? At the final position we zeroed one head’s output just before the attention output projection. The table shows the mean logit of B minus that of C on the held-out sequences. Positive values favor B. Subtracting the swapped column from the original measures how far the model’s preference moved when the two tokens traded places.
| Final-position intervention | Original order | B and C swapped | Shift |
|---|---|---|---|
| All heads intact | 6.55 | −7.06 | 13.61 |
| Zero layer 18, head 6 | 4.86 | −5.35 | 10.21 |
| Zero the neighboring head 7 in layer 18 | 6.31 | −6.90 | 13.21 |
Removing head 6 weakened the response to the swap. Yet the shift still pointed in the expected direction on 30 of the 32 sequences, down from 32 with all heads intact. Other paths can sustain this behavior. These are relative scores for two token IDs on a synthetic copy task. Finding each token’s rank requires comparing the rest of the vocabulary. Tracing which earlier layers supply this head with information takes a separate experiment.
Run the CPU experiment (Python) · Inspect all 32 paired shifts (JSON)
6. From Features to Circuit Tracing
In their 2025 circuit-tracing study, Ameisen and colleagues trained a replacement for parts of a language model so they could trace contributions between interpretable features on a given prompt [5]. The graph suggests interventions. Its usefulness depends on how well the replacement reproduces the behavior under study and how much of the computation the displayed paths cover.
For the delivery-date example, record the difference between the new-date and old-date logits. On prompts that differ only in the date, patch a candidate activation and compare the change in this difference with a control intervention. Repeat on held-out dates and document layouts. Report the cases where the intervention has no effect, too.
7. Summary and Open Questions
There are three results worth writing down separately: the behavior changes when the prompt changes, an internal signal tracks that change, and an intervention on the signal changes the behavior. Each answers a different question. Section 19.2 compares attention maps with intermediate vocabulary readouts, and Section 19.4 examines features that share activation dimensions.
Quizzes
Quiz 1: In the prompt A C X A, which position should the induction head read, and for which position does the model predict a token?
With zero-based indices, the query is at 3. It reads position 1, where C follows the first A, and can favor C for position 4.
Quiz 2: What does a large attention weight at position 1 establish if zeroing the head’s output leaves the answer unchanged?
The head reads from that position. The intervention did not change the measured answer under these conditions. Its write may be small or other paths may support the same answer. Examine the logits as well as the top token.
Quiz 3: A probe detects plural nouns in its training sentences. How would you test what it learned?
Use unseen nouns and sentence templates, including matched singular and plural forms. This tests generalization of the readout. Testing whether the model uses the signal requires an intervention and a behavioral measurement.
Quiz 4: For the sequence A B X A C X A, does the exact-match rule pick B or C?
Both earlier A tokens have visible successors. Positions 1 and 4 hold B and C. Choosing a winner requires information the rule does not specify, such as the learned attention weights and each source’s contribution to the vocabulary logits.
References
- Olah, C., et al. (2020). Zoom In: An Introduction to Circuits.
- Elhage, N., et al. (2021). A Mathematical Framework for Transformer Circuits.
- Olsson, C., et al. (2022). In-context Learning and Induction Heads.
- Park, K., Choe, Y. J., & Veitch, V. (2024). The Linear Representation Hypothesis and the Geometry of Large Language Models.
- Ameisen, E., et al. (2025). Circuit Tracing: Revealing Computational Graphs in Language Models.
- PyTorch. MultiheadAttention.
- Hugging Face. SmolLM2-135M base checkpoint and model card.