Attention Circuits

Dive into Deep Learning · §10.7

Attention Circuits: The Residual Stream, QK/OV Decomposition, and Induction Heads
residual stream · QK & OV circuits · skip-trigrams · two-layer induction heads · causal head ablation · in-context learning

Why Attention Heatmaps Alone Cannot Explain a Head

Motivation

  • A Positional Shortcut Can Mimic Retrieval: A 1-block model trained on 64-token sequences repeating a random 32-token pattern reaches 100\% accuracy on the second copy by looking 31 positions back.
  • Testing on Period 24 Exposes the Illusion: Evaluated on 24-token patterns, its accuracy collapses to 1.6\% (chance) because its heads still stare blindly at offset -31.

Decomposing Multi-Head Output into a Sum Over Heads

Additive Head Decomposition

  • Partitioning \mathbf{W}_o \in \mathbb{R}^{d \times H d_h} into H column slices \mathbf{W}_o^m \in \mathbb{R}^{d \times d_h} rewrites multi-head attention as a sum of H independent updates: \sum_{m=1}^H \mathbf{W}_o^m \mathbf{u}_m = \sum_{m=1}^H \sum_{j \le i} \alpha_{ij}^m\,\big(\mathbf{W}_o^m \mathbf{W}_v^m\big)\,\mathbf{h}_j
  • Only the Product \mathbf{W}_o^m \mathbf{W}_v^m Matters: Value projection \mathbf{W}_v^m and output slice \mathbf{W}_o^m act exclusively through their rank-d_h product.

Every Head Is Two Rank-d_h Matrices: QK and OV

QK and OV Circuits

  • Each attention head of width d_h is completely specified by two d \times d matrices of rank \le d_h (Elhage et al., 2021): \mathbf{W}_{\mathrm{QK}} = \mathbf{W}_q^\top \mathbf{W}_k, \qquad \mathbf{W}_{\mathrm{OV}} = \mathbf{W}_o \mathbf{W}_v
  • QK Circuit (\mathbf{W}_{\mathrm{QK}}): Bilinear form governing where the head attends (\alpha_{ij}).
  • OV Circuit (\mathbf{W}_{\mathrm{OV}}): Linear operator governing what vector \mathbf{W}_{\mathrm{OV}}\mathbf{h}_j is added to destination i.

The Residual Stream as a Shared Communication Bus

The Residual Stream

  • Starting from the token embedding \mathbf{h}_i^{(0)} = \mathbf{e}_{x_i}, each block \ell = 1, \ldots, N adds its heads’ outputs directly into a running vector at position i: \mathbf{h}_i^{(\ell)} = \mathbf{h}_i^{(\ell-1)} + \sum_{m=1}^H \sum_{j \le i} \alpha_{ij}^{\ell m}\,\mathbf{W}_{\mathrm{OV}}^{\ell m}\,\mathbf{h}_j^{(\ell-1)}
  • Shared Read/Write Channel: Every head reads subspaces of \mathbf{h}^{(\ell-1)} via its QK and OV circuits and adds its result back into \mathbf{h}^{(\ell)}, terminating at tied output logits \mathbf{z}_i = \mathbf{E}\,\mathbf{h}_i^{(N)}.

Each head reads earlier residual streams via its QK circuit and writes additively via its OV circuit.

What 0 and 1 Attention Layers Can Express

Expressivity by Depth

  • Expanding the residual stream for N = 1 reveals 0-layer bigram and 1-layer skip-trigram terms: \mathbf{z}_i = \mathbf{E}\,\mathbf{e}_{x_i} + \sum_{m=1}^H \sum_{j \le i} \alpha_{ij}^m\,\mathbf{E}\,\mathbf{W}_{\mathrm{OV}}^m\,\mathbf{e}_{x_j}
  • Zero Blocks (N = 0): Symmetric table \mathbf{E}\mathbf{E}^\top (cannot express asymmetric cycles).
  • One Block (N = 1): Skip-trigrams x_j \ldots x_i \to x_{\textrm{next}}, but cannot complete novel [\mathrm{A}][\mathrm{B}] \ldots [\mathrm{A}] \to [\mathrm{B}] because [\mathrm{B}]’s key knows nothing about its predecessor [\mathrm{A}].

Two Layers Form an Induction Head via K-Composition

The Two-Layer Induction Circuit

  • Completing [\mathrm{A}][\mathrm{B}] \ldots [\mathrm{A}] \to [\mathrm{B}] requires two layers composing through the key pathway (K-composition):
  • Layer 1 (Previous-Token Head): Uses RoPE offset preference to attend 1 step back (j - 1) and writes \mathbf{W}_{\mathrm{OV}}^{1}\,\mathbf{e}_{[\mathrm{A}]} into the residual stream \mathbf{h}_j^{(1)} at [\mathrm{B}]’s position j.
  • Layer 2 (Induction Head): Its QK circuit matches the current query \mathbf{e}_{[\mathrm{A}]} against that written key feature in \mathbf{h}_j^{(1)} (\mathbf{e}_{[\mathrm{A}]}^\top \mathbf{W}_{\mathrm{QK}}^{2}\mathbf{W}_{\mathrm{OV}}^{1}\mathbf{e}_{[\mathrm{A}]}), and its OV circuit copies x_j = [\mathrm{B}] into the output logits.

A two-layer induction circuit composes a layer-1 previous-token head with a layer-2 match-and-copy head.

Synthetic Benchmark: Repeated Random Token Patterns

Isolating In-Context Retrieval

Does gradient descent find this circuit? Each sequence tiles a random pattern of length L \in [L_{\min}, L_{\max}] over 64 tokens:

def repeated_batch(batch_size, num_steps, vocab, Lmin, Lmax, device=None):
    """Random patterns of length Lmin..Lmax, tiled to num_steps tokens."""
    L = torch.randint(Lmin, Lmax + 1, (batch_size,), device=device)
    s = torch.randint(0, vocab, (batch_size, num_steps), device=device)
    pos = torch.arange(num_steps, device=device)
    return torch.gather(s, 1, pos[None, :] % L[:, None]), L

x, L = repeated_batch(batch_size=2, num_steps=16, vocab=10, Lmin=5, Lmax=8)
print(f'pattern lengths: {L.tolist()}')
print(x)
  • Unpredictable First Copy (t \le L): Each pattern is fresh, so the first period stays at chance (cross-entropy \log 64 \approx 4.16\text{ nats}, accuracy 1/64 \approx 1.6\%). So does the restart token at t = L: nothing has repeated yet.
  • Predictable Later Copies (t > L): Once the pattern repeats, each token can be predicted from the context by looking up the earlier occurrence.

Pitfall: The Fixed-Offset Positional Shortcut

Why Fixed Periods Mislead

What happens if we train a one-block model (num_blks=1, bias=True) on sequences with a fixed pattern period L = 32?

first copy 4.38 nats, second copy 0.14 nats, second-copy accuracy 1.00
patterns of length 24: second-copy accuracy 0.02
mass at offset 31, per head: 1.00 0.96 1.00 1.00
mass at offset 23, per head: 0.00 0.00 0.00 0.00

Mechanistic Pitfall: On L = 32, the 1-block model reaches 1.00 accuracy (about 0.1\text{ nats}) by using constant bias queries and keys under RoPE to attend purely to fixed offset j - i = -31. Tested on period L = 24 (target at offset -23), its heads still place more than 0.9 of their mass at offset -31 and accuracy collapses to 0.02, which is chance.

Variable Periods Force Content-Based Induction

1-Block vs. 2-Block Experiment

Sampling the period uniformly from L \in \{16, \ldots, 32\} on every sequence destroys any fixed-offset shortcut. We train three 2-block runs and a 1-block control (bias=False) for 5{,}000 Adam steps:

blocks  first copy  later copies  accuracy  below 1 nat at step
     2        4.44          0.30      0.94                 2150
     2        4.31          0.16      0.96                 1550
     2        4.31          0.19      0.95                 2650
     1        4.26          3.55      0.11                never
  • Two Blocks Solve Retrieval: All three 2-block seeds drop below 1\text{ nat} between steps 1{,}000 and 3{,}000, reaching roughly 0.2–0.4\text{ nats} and more than 90\% later-copy accuracy.
  • One Block Fails: The 1-block control stalls above 3.5\text{ nats} (about 10\% accuracy)—all it can do is boost the unigram set of tokens that appeared anywhere in the prefix.

Phase Transition During Induction Head Formation

Training Dynamics

  • Abrupt Loss Drop: For well over a thousand steps, the 2-block model sits on a plateau near 4\text{ nats}, barely below chance; once block 1’s OV output aligns with block 2’s QK circuit, later-copy loss plunges by more than 3\text{ nats}.
  • First-Copy Side Effect: First-copy loss rises slightly above \log 64 \approx 4.16 right at the phase transition: once induction activates, a token that repeats by chance inside the first period causes the model to predict its previous successor.

Evidence Level 1: Inspecting Attention Heatmaps

Activation Patterns

  • Evaluating model_two on a test sequence of period L = 24 reveals two distinct geometric signatures across the two blocks:
  • Block 1 (Top Row): Several heads form a subdiagonal stripe at j = i - 1 (previous-token heads).
  • Block 2 (Bottom Row): Once the second copy starts at i \ge 24, all four heads form a parallel diagonal stripe at j = i + 1 - L = i - 23 (induction heads).

Quantifying Previous-Token and Induction Head Scores

Aggregated Attention Metrics

head_scores averages each head’s attention weight on the previous token (j = i - 1) and on the variable induction target (j = i + 1 - L for i \ge L) over 256 sequences with L \in \{16, \ldots, 32\}:

run 1, block 1, previous : 0.34 0.46 0.00 0.50
run 1, block 1, induction: 0.00 0.01 0.00 0.00
run 1, block 2, previous : 0.09 0.12 0.07 0.14
run 1, block 2, induction: 0.40 0.38 0.41 0.58
run 2, block 1, previous : 0.02 0.03 0.99 0.00
run 2, block 1, induction: 0.00 0.01 0.00 0.00
run 2, block 2, previous : 0.07 0.06 0.08 0.06
run 2, block 2, induction: 0.45 0.58 0.23 0.61
run 3, block 1, previous : 0.19 0.01 0.39 0.46
run 3, block 1, induction: 0.00 0.00 0.00 0.00
run 3, block 2, previous : 0.08 0.07 0.06 0.07
run 3, block 2, induction: 0.20 0.20 0.47 0.24
  • Clean Separation of Labor: In every run, Block 1 has 1–3 previous-token heads (scores from about 0.3 to 0.99) and at most 0.02 induction score, whereas Block 2 heads concentrate up to \approx 0.6 of their mass directly on the moving target i + 1 - L (vs. \approx 0.025 uniform chance).

Evidence Level 2: Reading the OV Copy Matrix

Weight-Space Circuit Analysis

  • Attending to position j predicts token x_j only if Block 2’s OV circuit boosts the logit of x_j: C_{ab} \stackrel{\textrm{def}}{=} \mathbf{e}_b^\top \mathbf{W}_{\mathrm{OV}}\,\bar{\mathbf{h}}_a
  • Signature of Copying: If the OV circuit copies token identity, the largest entry in row a lies on the diagonal (b = a) across nearly 100\% of the 64 tokens (versus 1/64 \approx 0.02 at random initialization).

OV Copy Matrix Results and Two Crucial Subtleties

Weight Inspection Results

  • Subtlety 1 (Stream vs. Embeddings): Block 2’s OV matrix copies almost perfectly (0.9–1.0 diagonal share) on the Block-1 stream \bar{\mathbf{h}}_a, but less reliably (anywhere from 0.3 to nearly 1.0) on raw embeddings \mathbf{e}_a—Block 2 also reads features transformed by Block 1’s OV circuits (V-composition).
  • Subtlety 2 (Copying \neq Retrieval): The 1-block model also has a near-perfect diagonal OV copy matrix (share \approx 1.00), yet gets only 10\% accuracy because its QK circuit cannot locate the target.
rows whose largest entry is the diagonal (chance 1/64)
                                   run 1   run 2   run 3
2 blocks, block 2, mean stream      1.00    1.00    0.91
2 blocks, block 2, embeddings       0.61    0.97    0.70
1 block, mean stream                1.00

Evidence Level 3: Causal Head Ablations

Component Interventions

Correlation in attention maps or weights is not causation. To test which heads are causally necessary, ablate zeroes out the output projection slice \mathbf{W}_o^m of selected heads:

def ablate(model, blk, heads):
    """Copy of model with the given heads of block blk removed."""
    model = copy.deepcopy(model)
    W_o = model.blks[blk]['proj'].weight   # (D, D): heads side by side
    with torch.no_grad():
        W_o.view(W_o.shape[0], model.num_heads, -1)[:, heads] = 0
    return model
  • Exact Additive Removal: Because block \ell adds \sum_{m=1}^H \mathbf{W}_o^m \mathbf{u}_m to the residual stream, zeroing \mathbf{W}_o^m deletes head m’s contribution while leaving all other heads intact.
  • Experimental Design: In Block 1, we compare removing the previous-token heads (score > 0.2) against removing all other Block-1 heads; in Block 2, we remove the top k \in \{1, 2, 3, 4\} induction heads cumulatively.

Ablation Results: Necessity, Redundancy, and Surprises

Interpreting Interventions

run 1: block 1 previous-token heads [0, 1, 3], others [2]
run 2: block 1 previous-token heads [2], others [0, 1, 3]
run 3: block 1 previous-token heads [2, 3], others [0, 1]
heads removed                  later-copy loss / accuracy: run 1, 2, 3
none                              0.31 / 0.94   0.15 / 0.96   0.17 / 0.96
block 1, previous-token heads     4.64 / 0.07   3.71 / 0.09   3.80 / 0.17
block 1, all other heads          5.66 / 0.02   3.96 / 0.10   3.85 / 0.13
block 2, top 1 induction          0.63 / 0.92   0.56 / 0.91   1.65 / 0.70
block 2, top 2 induction          1.66 / 0.68   4.49 / 0.28   3.14 / 0.45
block 2, top 3 induction          3.38 / 0.24   5.68 / 0.06   3.88 / 0.23
block 2, top 4 induction          4.25 / 0.02   4.19 / 0.01   4.18 / 0.02
one-block model                   3.56 / 0.11
  • 1. Block-1 Previous-Token Heads Are Necessary: Removing them drops accuracy from above 0.9 to below 0.2.
  • 2. Surprise—Block 1’s “Inert” Heads Are Also Necessary: Removing them drops accuracy below 0.15: Block 2’s OV copy circuit relies on their stream transformation (zero-ablation also shifts stream norms off-distribution).
  • 3. Block-2 Redundancy: Removing the single strongest induction head leaves accuracy at 0.7–0.9; all four Block-2 heads share the induction workload and must be removed together to drop to chance.

In-Context Learning: Generalizing to Unseen Patterns

One-Shot Pattern Completion

  • With 64^{24} \approx 2.2 \times 10^{43} possible patterns of length 24, the model has never seen any test pattern during training, and all token transitions are equally likely a priori.
  • First Copy (t < 24): Accuracy sits at the chance baseline 1/64 \approx 0.016.
  • Second Copy (t \ge 25): Jumps immediately above 0.90 from a single in-context exposure. (At the exact restart t = 24, content matching has not yet seen a repeated token.)

Dissecting the Remaining Error: Repeated Tokens

Beyond Single-Token Matching

Why does accuracy after the restart plateau a few points short of 100\%? When a token occurs K > 1 times inside the L-token pattern with different successors, matching on the current token alone is ambiguous:

\mathbb{E}\!\left[\frac{1}{K}\right] = \frac{1 - (1 - p)^L}{L p} \approx 0.84 \quad\textrm{overall}\quad (\approx 0.47 \textrm{ on repeated tokens } K > 1), \qquad p = \frac{1}{64},\; L = 24

current token        unique repeated      all
share of targets       0.69     0.31     1.00
single-token match     1.00     0.47     0.84
run 1 accuracy         0.99     0.80     0.93
run 2 accuracy         1.00     0.87     0.96
run 3 accuracy         1.00     0.85     0.95

On unique pattern tokens (K = 1, 70\% of positions), model_two achieves 0.97–1.00 accuracy; on repeated tokens (K > 1, 30\% of positions), it reaches roughly 0.7–0.9, beating the 0.47 uniform single-token match by combining multi-token prefix context and RoPE distance preferences.

In-Context Gradient Descent via Linear Attention

Beyond Copying

  • A single linear-attention head can also execute one step of gradient descent on an in-context regression task \mathcal{D} = \{(\mathbf{x}_i, y_i)\}_{i=1}^n (Oswald et al., 2023): \mathbf{w}_1 = \eta \sum_{i=1}^n y_i\,\mathbf{x}_i \;\Longrightarrow\; \hat{y}_q = \sum_{i=1}^n (\mathbf{x}_q^\top \mathbf{x}_i)\,(\eta y_i)
  • Packing examples as \mathbf{z}_i = [\mathbf{x}_i; y_i] and query as \mathbf{z}_q = [\mathbf{x}_q; 0] computes \hat{y}_q in a single forward pass without updating model weights.

Hierarchy of Mechanistic Evidence

Interpretability Methodology

Our investigation of induction heads illustrates why establishing what a circuit computes requires a multi-level hierarchy of evidence:

Diagnostic Probe Evidence Level What It Establishes What It Leaves Open / Limitation
1. Later-Copy Loss Behavioral Two blocks solve variable-period repetition; one cannot Identifies no internal component or algorithm
2. Period Shift (32 \to 24) Input intervention Exposes the 1-block model’s fixed-offset -31 shortcut Alters the input distribution alongside the probe
3. Attention Head Scores Activation probe Block 1 attends to i-1; Block 2 attends to i+1-L Shows where heads look, not what their values transmit
4. OV Copy Matrix (\mathbf{C}) Weights + stream Block 2’s OV circuit boosts the attended token’s logit Also diagonal (\approx 1.00) in the failing 1-block control
5. Zero / Mean Ablation Causal intervention Both Block-1 groups and Block-2 heads are causally required Zero-ablation shifts stream norms (use mean ablation to verify)

Concept Check: Circuits, Composition, and Sinks

Check Your Understanding

Test your understanding of QK/OV circuits and mechanistic interventions:

  1. Q-, K-, and V-Composition: When a Block-2 head scores \mathbf{h}_i^{(1)\top}\mathbf{W}_{\mathrm{QK}}^{2}\mathbf{h}_j^{(1)}, why does the induction circuit rely on K-composition (\mathbf{e}_{x_i}^\top \mathbf{W}_{\mathrm{QK}}^{2} \mathbf{W}_{\mathrm{OV}}^{1} \mathbf{e}_{x_{j-1}}) rather than Q-composition?
  2. Attention Sinks: In pretrained LLMs, many heads place > 80\% of their attention weight on the very first token (<bos>) across almost all queries. What two quantities should you measure before claiming that <bos> carries critical semantic information?
  3. Zero-Block Bigram Cycles: Why can a 0-block model with tied embedding/unembedding logits \mathbf{z}_i = \mathbf{E}\,\mathbf{e}_{x_i} never make t \to h \to e \to ␣ \to t each token’s top predicted successor?

Answers:

  1. Because the query at destination i is the current token x_i = [\mathrm{A}] itself (\mathbf{e}_{x_i}), whereas the key at source position j (x_j = [\mathrm{B}]) must contain the Block-1 OV output encoding that its predecessor was x_{j-1} = [\mathrm{A}].
    1. The norm of the OV output vector \|\mathbf{W}_{\mathrm{OV}}\mathbf{h}_{\langle\mathrm{bos}\rangle}\| (which is near zero for an attention sink absorbing unused softmax mass), and (2) the change in loss under head ablation.
  2. For b \neq a to beat a’s self-logit \mathbf{e}_a^\top\mathbf{e}_a, Cauchy–Schwarz requires \|\mathbf{e}_b\| > \|\mathbf{e}_a\|, which cannot hold around a closed cycle \|\mathbf{e}_{\texttt{t}}\| < \|\mathbf{e}_{\texttt{h}}\| < \|\mathbf{e}_{\texttt{e}}\| < \|\mathbf{e}_{\texttt{␣}}\| < \|\mathbf{e}_{\texttt{t}}\|.

Summary: Attention Circuits and Induction Heads

Key Takeaways

Concept / Circuit Mathematical Expression Rank / Depth Requirement Mechanistic Role in Sequence Models
QK Circuit \mathbf{W}_{\mathrm{QK}} = \mathbf{W}_q^\top \mathbf{W}_k (or \mathbf{W}_q^\top \mathbf{R}_{j-i}\mathbf{W}_k) Rank \le d_h (d \times d) Determines where a head attends (\alpha_{ij})
OV Circuit \mathbf{W}_{\mathrm{OV}} = \mathbf{W}_o \mathbf{W}_v Rank \le d_h (d \times d) Determines what vector \mathbf{W}_{\mathrm{OV}}\mathbf{h}_j is written to destination i
Residual Stream \mathbf{h}_i^{(\ell)} = \mathbf{h}_i^{(\ell-1)} + \sum_{m, j \le i} \alpha_{ij}^{\ell m}\mathbf{W}_{\mathrm{OV}}^{\ell m}\mathbf{h}_j^{(\ell-1)} Shared width-d vector bus Allows later layers to read and compose earlier heads’ outputs
Skip-Trigram \mathbf{E}\,\mathbf{W}_{\mathrm{OV}}^m\,\mathbf{e}_{x_j} weighted by \alpha_{ij}^m N = 1 attention layer Implements x_j \ldots x_i \to x_{\textrm{next}} and single-token copying
Induction Circuit K-composition \mathbf{e}_{x_i}^\top \mathbf{W}_{\mathrm{QK}}^{2m'} \mathbf{W}_{\mathrm{OV}}^{1m} \mathbf{e}_{x_{j-1}} N \ge 2 attention layers Completes novel in-context patterns [\mathrm{A}][\mathrm{B}] \ldots [\mathrm{A}] \to [\mathrm{B}]
Copy Matrix & Ablation C_{ab} = \mathbf{e}_b^\top \mathbf{W}_{\mathrm{OV}}\bar{\mathbf{h}}_a; zero/mean \mathbf{W}_o^m Weights + intervention Separates true causal circuits from attention sinks and shortcuts