Issue 45 · Pick 09 AI / ML ✓ read
A Circuit for In-Context Learning
TL;DR
Gao & Gao open up three small-ish base LLMs (Qwen3-4B, SmolLM3-3B, Llama-3.2-3B) and trace, intervention by intervention, the complete causal path by which few-shot in-context learning with arbitrary labels actually happens: the prompt is turned into a key–value memory stored at the label tokens, a class-keyed lookup reads it out, and a learned "is there anything worth reading?" signal gates the whole thing by controlling attention to the sink. Every step is pinned down with activation patching, ablations against matched random controls, and steering with the model's own directions; a two-constant-per-head softmax law fit on one prompt distribution predicts another; and a from-scratch toy transformer grows the same parts — growing the gate only when training penalizes blind retrieval. If you've wanted one worked example of a nontrivial LLM capability explained end-to-end, mechanistically and causally, this is the strongest one I've seen.
The problem: learning that can't be memorization
Show a base model twelve lines like The soup was cold -> bar / A gorgeous evening -> foo and then a new sentence, and it outputs the right invented word. Since foo and bar carry no pretrained meaning, the sentence→label mapping must be acquired inside a single forward pass, with frozen weights. This is the cleanest form of in-context learning, and it's been a genuine mystery as a composed algorithm.
Pieces were known. Induction heads copy tokens that followed earlier occurrences of the current token (Olsson et al. 2022). Task/function vectors show a few heads carry a compact task description to the query. Several papers located label tokens as where task information accumulates. But nobody had shown: what exactly is written at the label tokens, on which side of attention it's read, which heads read it, what turns the read on and off, and how the result reaches the logits. This paper answers all of those, with a control for each answer.
The key idea: the prompt becomes a key–value memory
Here's the picture to hold in your head. Each label token's residual stream becomes a memory slot with two fields, read through two different attention matrices:
- The value is the label's identity (
foovsbar) — present from the token embedding, read through the readers' W_V. - The key is the class of the sentence that preceded it — not there originally. About twenty middle-layer "writer" heads attend from the label token back to its own sentence and deposit the class direction into the label's residual stream. This key is read through the readers' W_K.
At the query arrow, two things happen: a "query code" representing the new sentence's class gets written into the arrow position, and ~90 upper-layer reader heads run a plain softmax over positions, matching the query code against the slot keys and copying out values from matching slots. The readers are, in effect, induction heads keyed on a semantic class rather than a literal token.
The dissociation of key from value is the paper's cleanest experiment (Section 3). Swap foo↔bar everywhere (changing values, not keys): the effect flows through the label tokens' values in the reader layers — the eight sharpest readers' values carry -2.16 nats of the flip while their keys carry +0.56 (wrong direction). Swap one sentence for one of the opposite class (changing a key, not a value): now the effect flows through the label tokens' keys, and only in the middle layers. A same-class sentence swap of matched length — the control — moves the answer by +0.08 nats and every handoff stays within \pm 0.06. Only the class reaches the answer, and key and value live on opposite sides of attention.
The gate, and why the sink exists
A memory that is always read would be a liability — most text contains no demonstrations. The models have a solution with a satisfying architectural logic. Early duplicate-token heads (the first half of the classic induction circuit, repurposed) detect whether any label has appeared twice. Flat pooling heads in layers 20–23 aggregate this into a single direction g in the residual stream at the query arrow (prompts with repeated labels project at \sim +18, unique-label twins at \sim -21, held-out sign agreement 1.00).
What g does is the "aha" of the paper. Attention is a softmax: the mass has to go somewhere. For these reader heads, position zero — the attention sink — is where unspent attention goes. When no label repeats, the sink wins the softmax and the readers return nothing in particular (the "null action"). The gate opens the read by lowering the readers' logit on the sink: adding g at the model's own dose drops the sink-minus-match logit by 1.75–3.65 nats at the sharpest readers, while a random direction of the same norm moves it by at most 0.2. The effect on the match-vs-nonmatch gap is seven times smaller. And the paper notes a small corollary that explains where the gate must act: a signal present only at the query position can only influence L_{\text{sink}} - L_{\text{match}} through the readers' queries — which is exactly where g projects in the weights, with the releasing sign.
This gives the attention sink — a ubiquitous, mostly-mysterious feature of trained transformers — an actual job: it is the "null" slot of a lookup, and a one-dimensional context signal toggles between read and don't-read by adjusting its logit. Zeroing position zero's value across all layers costs 0.4–0.8 nats precisely on the prompts where not reading is correct.
The quantitative law, and why populations
Because the read is an ordinary softmax, the attention mass m on matching slots should obey
where n_m is the number of slots matching the query's class, N the total slots, L the match logit, and n_{\text{rest}} + e^{L_{\text{sink}}} a lumped "everything else" term (only the sum is identifiable — so two constants per head). As algebra this is trivial; the content is that fixed constants per head describe the head across prompt distributions. Fit on 12-demonstration prompts with 2–6 classes, the law reproduces measured mass within 0.1 for 127/140 Qwen heads and 124/125 Llama heads, and then predicts the never-fitted one-slot-per-class regime with median error 0.07 (Qwen) and 0.04 (Llama).
It fails upward: on 18-demonstration prompts, 92–94% of heads are over-predicted. The diagnosis is itself informative — each head's sink attention (e.g., 0.34–0.36 for the sharpest Qwen readers) and its total matching mass are roughly fixed properties of the head, so extra matching slots divide a fixed budget. The authors report this failure plainly, which is a pattern throughout the paper: pre-registered predictions in an appendix, misses counted as findings.
The second structural insight: why ~90 readers instead of a few? Not for lack of signal — a single reader already separates the classes in its attention pattern. The constraint is output gain: no head writes more than 0.2 nats directly to the answer logit, so a 1.3-nat margin arithmetically requires at least seven heads (Proposition 2). They test the alternative directly: amplifying three strong readers 4× cannot replace seventeen knocked-out ones (-0.46 vs. an intact-ish baseline; 8× breaks the model). This reframes the sparse-vs-distributed circuits debate: the model concentrates where little gain is needed (two query-code heads, sixteen duplicate detectors, three value-carrying KV groups) and sums over populations where gain exceeds any single head's W_{OV}. Sparsity isn't a property of circuits; it's set per-step by the required gain.
There's also a third population: ~24 brake heads (negative heads in the copy-suppression sense) that write against the most recently seen label. Knocking them out nearly triples the margin (+1.39 nats vs. +0.22 for random sets) but leaves the model recency-biased — the readers favor late slots by 0.5–0.85 nats, and the brakes cancel this to keep the model order-neutral.
How strong is the evidence?
Unusually strong, by mech-interp standards. Three features stand out.
Exact accounting. The final residual decomposes exactly into per-component contributions to the margin, and they verify the decomposition closes to within 0.05 nats on every prompt. This reveals the division of labor: the readers collect labels into the arrow but write little directly; a band of copier heads in the last six layers writes most of the logit (+0.66 of a +0.68 margin); the late MLPs act as a prior toward the most frequent label and oppose flips.
Connection cuts, not just part lists. Patching only the 20 readers' outputs from a class-flipped twin carries 60% of the full behavioral flip; holding late attention and MLP inputs fixed then dissects the routes out of the readers (roughly a quarter-to-third via copiers, ~40% via late MLPs, a third direct to logits in Qwen; Llama's readers go direct). The gate's path through the readers' queries is isolated the same way: removing g from just those queries takes back a quarter to a third of the gate's effect, while a random direction removes nothing.
Sufficiency and synthesis. Keeping only the named heads (ultimately 189 in Qwen) and mean/resample-ablating everything else at the query reproduces or exceeds the intact margin. A hand-wired three-layer attention-only transformer implementing exactly Figure 2's circuit reproduces the softmax law to machine precision and the gate's behavioral signatures. And the from-scratch experiment delivers the most elegant result in the paper: a 3.4M-parameter transformer trained on a synthetic version grows writers and readers under any training distribution, but grows a gate only when unique-label prompts carry unpredictable query labels — i.e., only when blind retrieval is penalized. That's causal evidence for why pretrained models have a gate at all: in natural text, labels that never repeat don't certify a consistent mapping.
The cross-model story is honest about what's conserved (the algorithm: slot key/value dissociation, the softmax law, the null action, reader and brake populations) and what varies (which heads, how many, gate strength — Llama emits a label on 67% of unique-label prompts vs. Qwen's 10%, and Llama's induction-scored heads hold the read closed rather than open it). One link — duplicate heads → behavior — only closes cleanly in Qwen.
The scaling result: emergence without new parts
Section 11 is the part most worth your time if you only read one section beyond the mechanism. Wei et al. (2023) found that only large models follow flipped labels (where animal labels food sentences): small models answer by word meaning, large ones by the demonstrations. The census across Qwen3 0.6B→8B shows this famous "emergent" behavior involves no new component. Readers, brakes, and a working gate all exist at 0.6B. What changes is balance: splitting the word-label margin into a demonstrations-following part R and a meaning-following part P, the ratio P/R falls from 1.03 to 0.73 across scale, and the summed strength of brakes-on-word-meaning rises in lockstep with the flipped-label margin (+1.7 nats at 0.6B to +4.0 at 8B). Instruction tuning, similarly, doesn't rewire anything — the base model's 189 heads carry retrieval unchanged in the instruct model; post-training multiplies both R and P by ~2.5 and adds braking around the circuit.
If this generalizes, it suggests a different research posture toward emergence: instead of hunting for the component that switches on at scale, measure how the strengths of already-present parts shift. Striking detail: within a layout, the parts sit at the same addresses — the two 36-layer models (4B, 8B) share their five strongest readers and five strongest brakes by layer:head index. The authors can't say whether this is initialization, data order, or task structure; it's a loose thread worth someone pulling.
What to be skeptical about
The selection prompt's caveat is the right one: this is two-class sentence classification with single-token labels, ≤12 demonstrations, ≤8B parameters. The authors are admirably explicit about this boundary. Real ICL involves instructions, many classes, long-form outputs, and binding structure — none covered. The softmax law already breaks on 18-demonstration prompts, and the fix (per-head fixed attention budgets) is described but unexplained. Several of their own pre-registered predictions failed: many-shot LoRA fine-tuning was supposed to strengthen the brakes and instead tripled the readers; the top-7-copier knockout had the right sign but an interval through zero. The "encoder bound" (features not linearly readable at the arrow never bind, no matter how many demos) is correlational, though the hand-written key raising parity accuracy from 50% to 71% is suggestive. And the circuit-only faithfulness tests are sensitive to reference choice — the authors document a mistake they made here (Appendix on the mean-reference pair-matching bug), which increases rather than decreases my trust.
The bigger conceptual claim — "ICL in this setting is retrieval, with no step resembling a gradient update" — is well-supported in this setting, but the gradient-descent-in-context results (von Oswald et al., Akyürek et al.) live in continuous regression tasks where there may genuinely be different mechanisms. Both can be true.
Why it matters
Three takeaways travel beyond the setting. First, a worked existence proof that a real capability in a real pretrained model can be traced end-to-end — parts, connections, gating, quantitative law, synthesis — with every link carrying a matched control. Second, the gain-bound resolution of sparse-vs-distributed circuits: populations aren't a failure of interpretability but a predictable consequence of per-head output limits, characterizable by their shared read/write directions. Third, the gate: models carry a low-dimensional, steerable signal encoding "does my context contain a mapping worth trusting?" — directly relevant to RAG, to context-vs-parametric-knowledge conflicts, and perhaps adjustable on purpose. The closing line of the discussion (a Watson-and-Crick homage: "it has not escaped our notice...") points exactly there.
Read Section 3 for the key/value dissociation, Section 5 for the gate, and Section 11–12 for the scaling census and the from-scratch gate result. The appendix of pre-registered predictions — including the misses — is a model of how this kind of work should be reported.