A Mathematical Framework & Induction Heads
QK and OV circuits, head composition, and the induction heads behind in-context learning.
- → Decompose an attention head into QK (where) and OV (what) circuits
- → Explain Q-, K-, and V-composition and virtual heads
- → Find and validate induction heads in a real 2-layer model
A transformer is a sum, not a stack
Elhage et al.'s Mathematical Framework is the paper that turned attention from “a mechanism” into “an object you can do algebra on”. Its first move costs nothing and changes everything: stop thinking of the residual stream as a value that gets transformed, and start thinking of it as a running sum that every component writes into.
For an attention-only transformer with layers and heads , the final residual stream at a position is exactly
and the logits are . Because the unembedding is linear and the sum is a sum, the logits decompose into one term per component. Ask “how much did head 4 in layer 2 contribute to the logit for this token?” and there is a literal answer: apply to that head's output. That is direct logit attribution, and it exists only because of additivity.
QK and OV: where to look, what to bring
A head has four weight matrices — — and the framework's second move is to notice they only ever appear in two pairs.
The attention scores use and only through the product
and the head's output uses and only through the product . So the individual matrices are not the meaningful objects; the products are. This is not a notational nicety — it means the head's learned content lives in two matrices that map residual stream to residual stream, and you can look at them directly.
Both circuits are severely low rank. In GPT-2 small, but , so and are 768×768 matrices of rank at most 64. A head cannot read or write arbitrary things; it gets a 64-dimensional slice of the stream. That constraint is what makes heads specialize, and it is a large part of why they are legible at all.
Composition, and heads that do not exist
One layer of attention can only do so much. Its QK circuit reads token embeddings, so it can only decide where to look based on what the tokens are. Its OV circuit writes token information straight to the logits. The result is a skip-trigram model: patterns of the form “… … → ”, with a characteristic failure mode the paper enjoys pointing out — the head cannot make depend on and jointly, so a head that learns “keep… in mind” also fires “keep… in mind” on the wrong . Elhage et al. call these skip-trigram bugs, and they are direct evidence about the algorithm rather than the behaviour.
Two layers change the picture, because layer 1 reads a residual stream that layer 0 has already written into. There are exactly three places that can happen, one per input of the head:
Expand the two-layer attention-only model and every term is one of these paths:
With heads per layer and 2 layers you get virtual heads on top of real ones. This is where the combinatorics get frightening: the count of paths grows exponentially in depth, so “enumerate all circuits” stops being a plan almost immediately. In practice most virtual heads carry negligible weight, and finding the few that matter is the job.
Induction heads: the circuit worth memorizing
Here is what two layers buy you, and it is the single most important concrete result in mechanistic interpretability so far.
An induction head implements: find an earlier occurrence of the current token, and predict whatever followed it. Given it predicts . It takes two heads working together:
- A previous-token head in layer 0 attends from each position to the one before it and copies that token's identity into the residual stream. Useless alone.
- An induction head in layer 1 whose keys are computed from that written subspace — K-composition. Its key at position now means “the token before me was ”; its query at the destination means “my current token is ”. The match lands attention on the position after the earlier occurrence, and a copying OV circuit writes that token to the output.
This is why a one-layer attention-only model cannot do induction and a two-layer one can — a clean, falsifiable capability boundary that falls straight out of the algebra.
Olsson et al. build a case, across six lines of evidence, that induction heads are the main source of in-context learning in transformers: the phase change in the loss curve coincides with induction-head formation; perturbing the architecture so induction heads form earlier or later moves the bump with them; ablating induction heads in small models removes most of the in-context learning; and per-head in-context-learning scores concentrate on induction heads. The authors are careful about the limits, and so should you be: the mechanistic story is demonstrated in small attention-only models and argued by correlation and analogy in large ones. Their own summary is that the evidence is strong but not conclusive at scale.
The heads found in large models are also not the crisp toy circuit. They do fuzzy matching: paraphrases, translations, and abstract pattern completion, not just literal token repeats. Whether that is “the same circuit, generalized” or a family of related mechanisms is unsettled.
Build the circuit
First, walk the induction circuit end to end and watch the two attention patterns do their separate jobs. Then take the diagram apart: decide which of H1's three reads see H0's output, and watch which terms of the path expansion blink into existence.
With no composition, this is effectively two independent one-layer models added together. Every term is a bigram or skip-trigram; nothing here can look up a pattern in the context.
Things to try: (1) Switch the induction visualizer to random tokens and step through again — the mechanism is identical, which is the proof that it is reading the context rather than recalling a bigram. (2) In the composition builder, hit Induction preset: K-composition only. Note that no virtual head appears, and yet this is the configuration that produces the field's canonical circuit — a useful antidote to the assumption that virtual heads are where the action is. (3) Turn on all three at once and count the terms; then imagine 12 heads per layer and 12 layers, and you will understand why circuit discovery needs automation.
Problem set
The pencil problems are the ones that make the paper readable; do them before you open it. The code problems are the field's standard first experiment — by the end you will have found induction heads in a real model and proved they matter by breaking them.
GPT-2 small: , , 12 heads per layer.
- Give the shapes and maximum ranks of and for one head.
- What are the shapes of and , and what does each entry mean in words?
- Why does it not matter that and individually are not identifiable?
In a 2-layer attention-only model with heads per layer, the logits expand into a sum of terms.
- How many terms are there in total, as a function of ? Break them down by type.
- Generalize to layers: give the number of paths and say in one sentence why enumeration is not a research strategy.
- A one-layer model has how many terms? What does that tell you about the class of functions it can express?
Suppose the residual stream has two orthogonal subspaces: holding the current token's embedding, and , empty at layer 0 and written by the previous-token head.
Specify, in words and in matrix terms, what and of the layer-1 induction head must do. Then say what breaks if the previous-token head writes into instead of a separate subspace.
Load gpt2-small (or the 2-layer attn-only-2l model from the TransformerLens demos) and build a repeated-random-token sequence: pick 50 random token ids, concatenate the sequence with itself, prepend BOS. Run run_with_cache.
For every head, compute the induction score: the mean attention weight on the diagonal offset by seq_len - 1 in the second half of the sequence. Plot a layer × head heatmap. Separately compute a previous-token score (mean weight on the offset-1 diagonal).
Success check: a small number of heads have induction scores far above the rest, and at least one earlier-layer head has a high previous-token score. In GPT-2 small, heads 5.5 and 6.9 are commonly reported as strong induction heads and 4.11 as a strong previous-token head — treat those as a sanity check on your indexing, not as the answer, and trust your own numbers if they disagree.
Take your best induction head and your best previous-token head . Two experiments:
(a) Measure the composition. Compute the K-composition score and compare it against the same score for 20 randomly chosen earlier-layer heads.
(b) Break it. Mean-ablate 's output (replace it with its mean over a batch of prompts) and re-measure 's induction score and the model's loss on the repeated sequence.
Success check: the composition score for the real pair is a clear outlier, and ablating collapses 's induction score while ablating a random earlier head does not.
Olsson et al. define an in-context learning score as the difference in loss between the 500th token of a context and the 50th, averaged over documents: how much better does the model predict once it has seen more of the document?
Compute it for gpt2-small on ~50 documents of ≥600 tokens. Then recompute it with your top induction head mean-ablated.
Success check: the base score is clearly negative (loss at token 500 is lower than at token 50), and ablating induction heads shrinks the magnitude measurably more than ablating a random head of the same layer.
Check yourself
[A][B] … [A] with tokens it has never seen adjacent in training. Can it predict [B]?Go deeper
The Mathematical Framework is dense and worth three sittings. Read it with the composition widget open. Nanda's walkthrough is the single best study aid for it — treat it as the lecture that accompanies the text.