Rewriting transformer layers as independent tensor products through a linear residual stream turns a two-layer attention-only model into a sum of end-to-end token paths, revealing a sharp algorithmic jump from static skip-trigram lookup tables in one layer to two-head induction circuits in two. Published in December 2021 by Nelson Elhage, Neel Nanda, Catherine Olsson, Chris Olah, and colleagues at Anthropic, A Mathematical Framework for Transformer Circuits gave mechanistic interpretability its working vocabulary: the residual stream as a communication bus, W_QK routing versus W_OV token writes, virtual weights, and Q-, K-, and V-composition.
The framework matters today because standard deep-learning equations optimize for fast batched matrix multiplies rather than human comprehension. By algebraically regrouping the exact same weights without changing a single floating-point output, the authors show why keys, queries, and values are merely intermediate by-products of two low-rank matrices, and why naive attention-pattern visualization systematically misreads multi-layer behavior.
- One shared linear bus, zero privileged basis: Every attention and MLP block reads a linear projection from the residual stream and writes by addition, allowing downstream components to read earlier outputs directly via “virtual weights” (
W_I^2 W_O^1) across layers. - Every head splits into routing (
W_QK) and content (W_OV): Freezing softmax attention patternsA^hmakes an attention-only transformer strictly linear in the input tokens, withW_QK = W_Q^T W_Kdeciding where to look andW_OV = W_O W_Vdeciding what to write. - 1-layer models are ensembles of bigrams and skip-trigrams: In a 12-head (
d_head = 64) one-layer model over ~50,000 vocabulary tokens, 10 of 12 heads exhibit strongly positiveW_OVcopying eigenvalues across expanded[source] ... [destination] → [out]tables of ~2.5 billion entries (rank 64). - 2-layer depth unlocks induction heads via K-composition: A Layer 0 previous-token head shifts keys forward by one position so a Layer 1 head implements
[a][b] ... [a] → [b]in-context copying, even on completely random repeated token sequences.
The residual stream is a linear communication channel
Most textbook descriptions concatenate all attention head result vectors r^{h_i} and multiply them by one giant output matrix W_O^H. Splitting W_O^H into per-head column blocks [W_O^{h_1}, W_O^{h_2}, ...] proves this is algebraically identical to running every head independently and adding its output into the residual stream: sum_i W_O^{h_i} r^{h_i}. Each layer reads a linear projection from that stream and writes a linear projection back, with no nonlinearity sitting on the residual path itself (unlike ResNets, which apply activations on or right before residual additions).
That linearity creates three architectural consequences. First, the residual stream has no privileged basis: you could apply any invertible rotation R to the stream and inverse-rotate every reading and writing weight matrix without changing a single logit, meaning individual coordinates of residual vectors are not meaningful “neurons.” Second, the stream acts like shared memory bandwidth: joint PCA on W_E and W_U shows embeddings and unembeddings occupy only a narrow slice of d_model, leaving most subspaces free for intermediate layers to pass signals without interfering (d_head is typically 64 or 128 inside a much wider stream). Some heads even show large negative W_OV eigenvalues on the current token, and some MLP neurons show strongly negative input-output cosine similarity, suggesting active “memory management” that deletes stale features from congested subspaces.
Third, the residual stream is a severe bottleneck activation. Standard MLP blocks hold 4x as many neurons as d_model, so by layer 25 of a 50-layer transformer, roughly 100x more neurons sit upstream and downstream than there are residual dimensions to carry their messages. That bandwidth crunch forces layers to pack signals in feature superposition, which is why later work turned to sparse dictionary learning rather than inspecting raw residual coordinates.
Path expansion: bigrams, skip-trigrams, and why simple rules break
To separate token-to-token routing from content transformation, the authors write a single head using Kronecker (tensor) products across the [n_context, d_model] activation matrix: h(x) = (A^h ⊗ W_OV^h) x, where W_OV^h = W_O^h W_V^h acts independently on each token vector and A^h = softmax*(t^T W_E^T W_QK^h W_E t) mixes across sequence positions via W_QK^h = W_Q^T W_K. Note what disappears: query, key, and value vectors are merely low-rank factorization intermediates of W_QK and W_OV, whose eigenvalues and SVDs can be computed in 64 x 64 space instead of 50,000 x 50,000 token space.
Expanding the product of a one-layer transformer turns a stack of layers into a sum of end-to-end paths: the direct bigram term Id ⊗ (W_U W_E) plus one term A^h ⊗ (W_U W_OV^h W_E) per head. Freeze the attention patterns A^h from a forward pass, and every path from one-hot input tokens to output logits becomes completely linear. Each head reduces to two [50,000, 50,000] matrices (~2.5 billion entries, rank 64 or 128) implementing skip-trigrams of the form [source] ... [destination] [out].
Inspecting those matrices in 12-head (d_head = 64) and 32-head (d_head = 128) models trained on 2,048-token contexts reveals rich lookup structure. Compared against random Ginibre matrices (whose eigenvalues split symmetrically around zero), 10 of 12 heads show heavily positive W_OV eigenvalues dedicated to copying attended tokens, including split-token repair where unspaced "R" attends back to spaced " Ralph" to predict "alph". Other heads encode Python indentation dedents (\n\t\t\t ... \n\t\t → else/elif/except), LaTeX pairing (left ... \ → right), URL schemes (github ... / → issues/blob/pull), and idiomatic phrases (back and → forth).
Notice the first trap right in the algebra: because W_QK only scores (source, destination) and W_OV only maps source → out, a single head factors a three-token rule as f_1(a, b) * f_2(a, c) rather than a true three-way interaction f(a, b, c). As a result, a head that learns both keep ... in mind and keep ... at bay structurally increases the logits for keep ... in bay and keep ... at mind too.
Three kinds of composition and the birth of induction heads
Adding a second attention layer lets heads compose through the residual stream whenever d_head / d_model (often 1/10 to 1/100) subspaces overlap instead of staying disjoint. Layer 1 can read a Layer 0 head’s W_OV subspace through W_Q (Q-composition), through W_K (K-composition), or through W_V (V-composition).
In the two-layer toy model (d_model = n_heads * d_head), most heads still just act as extra skip-trigrams. The dominant multi-layer discovery is K-composition between a Layer 0 previous-token head and Layer 1 induction heads. Because the previous-token head copies token [a] into the residual stream at the next token [b], the induction head’s W_K builds a shifted key at [b] representing [a]. When [a] appears again later in the prompt, the induction head’s query matches that shifted key at [b], attends directly to [b], and copies [b] into the output logits ([a][b] ... [a] → [b]).
Explore the four circuit patterns below to see how one-layer lookup, K-composition, Q-composition, and V-composition differ in structure, data-distribution robustness, and empirical impact.
Select a motif (or use Left and Right arrow keys) to inspect its algebraic form, mechanism, empirical test, and limitations.
One-layer copying and skip-trigram lookup
1-layer baselineA single head attends from current token [a] back to prior token [b] when bigram statistics make [b] a plausible next token: [b] ... [a] -> [b].
- Why it breaks
- Cannot tell how [a] or [b] appeared in context, fails on arbitrary random token sequences, and suffers from factored cross-talk like 'keep ... in bay'.
- Algebraic path
- Single-head term A^h tensor (W_U W_OV^h W_E), producing 50k x 50k low-rank lookup tables directly from the weights.
- Empirical evidence
- 10 of 12 heads in the 12-head model show positive OV copying eigenvalues compared against random Ginibre matrices.
- Where it shines
- Local syntax cues (Python dedents, LaTeX delimiters), fixed idioms, and repairing space-split rare tokens (' Ralph' -> 'R' predicts 'alph').
Induction heads via K-composition
Induction circuitLayer 0 attends to the previous token and copies it into the residual stream; Layer 1 reads that shifted subspace via W_K to complete [a][b] ... [a] -> [b].
- Why naive viewing fails
- Looking at Layer 1 attention patterns shows the head attending straight to [b], hiding the Layer 0 previous-token head that computed [b]'s shifted key.
- Algebraic path
- QK circuit expands into a (4,2)-tensor term Id tensor A^{h_-1} tensor W matching current query [a] against shifted key [a] sitting at position [b].
- Hardest test
- Works cleanly on uniformly sampled random token sequences repeated three times, proving zero reliance on memorized English bigram priors.
- 2023 erratum note
- Fixing a Frobenius-norm transposition bug (||AB||_F vs ||BA||_F) revealed induction heads also K-compose with a head attending over the last several tokens.
Pointer-arithmetic induction via Q-composition
Pointer arithmeticIn transformers that add positional embeddings to the residual stream (such as GPT-2), a head can copy a match's position vector and rotate it +1 via W_Q.
- Architectural constraint
- Unavailable in rotary or key/query-only positional schemes where position embeddings never enter the residual stream.
- Paper's mechanism
- Layer 0 attends to an earlier occurrence of [a] and copies its position embedding; Layer 1's W_Q rotates sinusoidal coordinates forward by one offset to query [b].
- Observed scope
- Documented by the authors in GPT-2 alongside sentence-boundary identifier hypotheses (copying the previous period's position).
- Takeaway
- Models with different positional encodings discover distinct circuits (K-composition vs Q-composition) to implement the same algorithm.
Virtual attention heads via V-composition
Virtual headsWhen Layer 1 reads a Layer 0 head's output through W_V, the pair acts like one unit with composite pattern (A^{h2} A^{h1}) and OV matrix (W_OV^{h2} W_OV^{h1}).
- Scaling hazard
- Two-head virtual heads grow quadratically in layer depth and three-head chains cubically, making brute-force path enumeration intractable in deep models.
- Term importance test
- Freezing ground-truth attention patterns and recursively replacing head outputs with zero or prior-pass activations isolates the marginal loss drop of nth-order OV paths.
- Empirical finding
- In the two-layer toy model, second-order virtual heads contributed little marginal loss reduction compared to direct and first-order Layer 1 head terms.
- Why they still matter
- In deep models, virtual heads let two small components compose patterns such as 'attend to the subject of the previous clause' without spending a whole head.
Source: Elhage et al. (2021), One-Layer and Two-Layer Attention-Only Transformers.
For readers scanning without clicking the tabs, here is how the four motifs compare across depth:
- One-layer skip-trigrams (
[b] ... [a] → [b]): Factored tables (A^h tensor W_U W_OV^h W_E) handle copying, syntax cues, and split tokens, yet fail on random tokens and show cross-pair bugs. - K-composition induction (
[a][b] ... [a] → [b]): Reading a Layer 0 previous-token head (and multi-token prior heads, per the 2023 Frobenius fix) viaW_Klets Layer 1 copy random repeated sequences. - Q-composition pointer arithmetic: When positional embeddings sit in the residual stream (GPT-2, not rotary models), a head copies a token’s position vector and rotates it
+1inW_Q. - V-composition virtual heads (
h_2 o h_1): ComposingA^{h_2} A^{h_1}andW_OV^{h_2} W_OV^{h_1}grows quadratically with depth; frozen-pattern ablation showed minor loss impact in the two-layer toy model.
To test V-composition without enumerating exponential paths, the authors’ Term Importance Analysis freezes attention patterns, zeros head outputs for the direct path, and iteratively substitutes saved Layer n-1 activations to measure the marginal loss drop of n-th order OV paths.
What toy attention-only models leave out
Three limits separate this framework from full reverse-engineering of production LLMs. First, the toy models omit MLP blocks, which hold roughly two-thirds of standard transformer parameters. GeLU or SwiGLU nonlinearities block linear path expansion across MLPs, and most MLP neurons remain polysemantic aside from phrase-cluster neurons near 5% depth. Because attention heads also interact with MLPs, pure attention analysis covers well under a third of a real model’s weights.
Second, normalization and a 2023 library bug complicate cross-layer weights. Folding LayerNorm affine terms leaves a per-token scalar variance factor, making cross-depth path norms incomparable. Separately, a 2023 erratum noted that a cyclic-trace transposition bug in Frobenius norms (||W_{QK}^{h_2} W_{OV}^{h_1}||_F) initially understated multi-token Layer 0 K-composition in the two-layer chart.
Third, weight-path expansion yields hypotheses, not causal proof. Showing what a head can move does not prove it drives an output; validating real circuits required counterfactual methods like path patching, automated circuit discovery (ACDC), and causal scrubbing.
For engineers debugging attention models today, the framework’s core habit remains immediately useful. Stop reading raw attention heatmaps or residual coordinates as privileged features; factor heads into W_QK routing and W_OV writes in low-rank d_head space, weight patterns by value norms (||v_{src}||) to ignore resting tokens, and check upstream K- and Q-composition before trusting single-layer stories.


