Skip to content

A Mathematical Framework for Transformer Circuits

main track #2corefundamentalblogrubric 11/122021 · ~60 min

Nelson Elhage, Neel Nanda, Catherine Olsson, …, Chris Olah

Status

TL;DR. This Anthropic report starts with the simplest transformers: attention-only, no MLPs, zero to two layers. It shows you can understand them from the weights. The residual stream is a sum of what every component writes. Each attention head splits into a QK circuit, which decides where to look, and an OV circuit, which decides what to write. One-layer models are mostly bigrams plus “skip-trigrams”. Two-layer models compose heads, and the key example is the induction head, which does in-context copying.

Why it matters now. Almost every later mechanistic result uses this vocabulary: residual stream, QK/OV circuits, composition, virtual heads, path expansion. That includes induction heads, the IOI circuit and attribution graphs. If you want to ask how a reranker matches query and document tokens, or how an LLM copies spans from a retrieved passage, the QK/OV split is the first tool to reach for.

The model is linear in the residual stream except for the attention softmax. Each head reads with WVW_V and writes with WOW_O, so only WOV=WOWVW_{OV} = W_O W_V matters for content. Likewise only WQK=WQ⊤WKW_{QK} = W_Q^{\top} W_K matters for attention scores. For a one-layer attention-only model with tokens tt:

T=Id⊗WUWE  +  ∑hAh⊗(WUWOVhWE),Ah=softmax(t⊤WE⊤WQKhWE t).T = \mathrm{Id}\otimes W_U W_E \;+\; \sum_h A^h \otimes \big(W_U W_{OV}^h W_E\big),\qquad A^h = \mathrm{softmax}\big(t^{\top} W_E^{\top} W_{QK}^h W_E\, t\big).

With two layers, heads can read what earlier heads wrote. In Q-composition and K-composition the query or key reads an earlier head’s output, which changes the attention pattern. In V-composition the value reads it, which creates “virtual heads” (Ah2Ah1)⊗(WOVh2WOVh1)(A^{h_2}A^{h_1})\otimes(W_{OV}^{h_2}W_{OV}^{h_1}).

A Mathematical Framework for Transformer Circuits: the residual stream and the QK and OV circuits of an attention head Top: the residual stream runs from the token embedding to the unembedding; each attention head reads from it and adds its output back, so the stream is a sum of contributions. Bottom left: each head factors into a QK circuit, which decides where to attend, and an OV circuit, which decides what to write once it attends. Bottom right: for a one-layer attention-only model, the logits are a direct bigram path plus one skip-trigram term per head. Residual stream: every component reads and adds tokens → W_E W_U → logits head 1.1 head 1.2 head 2.1 linear channel: x_final = x_0 + Σ_h h(x) layer-2 heads can read layer-1 outputs (Q-, K- or V-composition) One head = two separate circuits QK circuit: where to look W_Eᵀ W_QK W_E vocab × vocab score: query token vs key token OV circuit: what to write W_U W_OV W_E vocab × vocab: attended token → logit change W_QK = W_Qᵀ W_K and W_OV = W_O W_V are low-rank (d_head) 1-layer attention-only model logits = W_U W_E t direct path: bigram statistics + Σ_h A^h ⊗ (W_U W_OV^h W_E) t one skip-trigram term per head: "A … B → C"; many heads copy attention pattern is fixed by the QK circuit
Original sketch. Every head reads from and adds to the residual stream. Each head is two separate vocabulary-by-vocabulary circuits. Later heads can compose with earlier ones.

This is a theory-and-case-study report, so results are qualitative.

  • Zero layers: the model is WUWEW_U W_E, an approximation of bigram statistics.
  • One layer: expanded QK and OV tables show skip-trigrams for common phrases. Examples include “keep … [in → mind / at → bay / under → wraps]”, copying heads, and heads for words split into two tokens. 10 of 12 heads have strongly positive OV eigenvalues.
  • Two layers: composition scores, measured as Frobenius norms of WQKh2W_{QK}^{h_2} or WOVh2W_{OV}^{h_2} times WOVh1W_{OV}^{h_1} normalised by their norms, show K-composition between a previous-token head and induction heads. Interactive patterns on the opening of Harry Potter show the off-diagonal “induction stripes”.
  • Correction: a later note reports a bug in the composition diagram. The corrected plot confirms the previous-token K-composition and adds composition with a head that attends over several recent tokens.
  • Attention-only toy models. No MLPs, no layer norm, no biases. Real models put much of their computation in MLPs, which this framework does not cover.
  • Weight-based statistics can mislead. Eigenvalue summaries are heuristic, and the composition bug shows how a plausible statistic can be wrong.
  • Scaling. Expanding vocab × vocab circuits is feasible for small models. Larger models need tools for superposition and features.
  • Virtual heads and longer paths were not important here, and it is open how much they matter in deep models.

Questions to think through

These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.

  1. Derive / compute

    For a one-layer attention-only transformer with no biases, write the logits as a sum of end-to-end paths. Identify the bigram term, the per-head terms, and the two vocab × vocab matrices that describe each head. State which part decides where a head attends and which decides what it writes.

    What a strong answer covers
    • T = Id ⊗ W_U W_E + Σ_h A^h ⊗ (W_U W_OV^h W_E), where W_OV^h = W_O^h W_V^h and A^h is the attention pattern.
    • The first term is the direct path: embedding then unembedding, which can only learn bigram statistics (next token given current token).
    • A^h = softmax(tᵀ W_Eᵀ W_QK^h W_E t) with W_QK^h = W_Q^hᵀ W_K^h. The QK circuit W_Eᵀ W_QK^h W_E scores each (query token, key token) pair: where to look.
    • The OV circuit W_U W_OV^h W_E maps an attended token to its effect on the output logits: what to write.
    • Each head is therefore a set of skip-trigrams "A … B → C": B is the current token, A an earlier token the head attends to, and C the token whose logit rises.
  2. Mechanism

    The framework says a one-layer head that raises both "keep … in mind" and "keep … at bay" must also raise "keep … in bay" and "keep … at mind". Explain this "skip-trigram bug" from the factored QK/OV form, and why a second layer can fix it.

    What a strong answer covers
    • A head's contribution factors into f₁(query token, key token) for attention and f₂(key token, output token) for the OV effect, like f(a, b, c) = f₁(a, b) f₂(a, c).
    • If "keep" is the attended token for current tokens "in" and "at", the OV circuit maps "keep" to raised logits for both "mind" and "bay", regardless of which current token triggered the attention.
    • The head cannot express the three-way interaction (current token × attended token × output), so it raises all four combinations.
    • With two layers, Q- or K-composition lets attention depend on information moved by earlier heads, and different heads can specialise on different contexts, so the model can represent conditional patterns.
  3. Derive / compute

    Show how K-composition with a previous-token head produces the induction QK term Id ⊗ A^{h−1} ⊗ W. Then explain how the authors check from the weights alone that a head is an induction head.

    What a strong answer covers
    • A layer-1 previous-token head (pattern A^{h−1}) writes, at position j, information about the token at j − 1 into the residual stream through its OV circuit.
    • A layer-2 head's key at j reads that output, so its QK circuit gains a term comparing the destination token with the token before each source position: Id ⊗ A^{h−1} ⊗ W.
    • If W is a "same token" matching matrix, attention goes to positions whose previous token equals the current token: prefix matching.
    • Check: the head's OV circuit should be copying (large positive eigenvalues) and the K-composition QK term should be a matching matrix (also positive eigenvalues). The induction heads sit in the positive corner on both statistics.
  4. Critique

    The authors later found that their composition-strength diagram had a bug: a transposition identity was wrongly used to speed up the Frobenius norm. What did the buggy measure compute, why did it still highlight induction heads, and what does this teach about validating weight-based interpretability claims?

    What a strong answer covers
    • Intended: ‖W_QK^{h₂} W_OV^{h₁}‖_F normalised by the individual norms (for K-composition). Computed: a cyclically permuted product, which measures whether the induction head's query reads the subspace the previous-token head wrote into.
    • That is exactly what an induction head's previous-token K-composition needs, so the plot strongly showed it and filtered out other composition.
    • The corrected plot shows more composition: two induction heads also use a head that attends over the last several tokens.
    • Lesson: weight-based summary statistics need independent checks (ablations, activation patching, random baselines). Agreement with a prior hypothesis is not evidence the measure is correct.
  5. Research idea

    A ColBERT-style late-interaction retriever uses a transformer encoder followed by token-level MaxSim. Propose how to use the framework's QK/OV decomposition to find heads that implement exact-match behaviour (a query token attending to identical tokens) in a small encoder, and how you would test that they matter for retrieval.

    What a strong answer covers
    • Compute each head's QK circuit restricted to the vocabulary (W_Eᵀ W_QK W_E, ignoring position) and look for strong diagonals, the "same-token" matching signature; summarise with positive eigenvalues as in the paper.
    • Compute OV circuits into the final embedding space (replace W_U with the projection used by MaxSim) to see whether heads copy token identity forward.
    • Caveat: real encoders have MLPs, layer norm and biases, so the clean decomposition is approximate; verify with activations.
    • Test causally: ablate candidate heads (mean or resample ablation) and measure retrieval quality on queries where exact match matters, against random-head ablations of the same size.

Done with this page?

Status