Manuscript Offprint

arXiv:2611.05344

A Circuit for In-Context Learning

Andrew Gao, William Gao

Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.

ABSTRACT

In-context learning (ICL), a pretrained language model's ability to perform a task specified by demonstrations in its prompt, needs no training objective and no parameter updates. With arbitrary labels the model must acquire a mapping it cannot have memorized, so the learning happens within a single forward pass. Prior work found candidate parts but not how they compose. We give the composition for few-shot sentence classification with arbitrary labels in three 3–4B-parameter transformers. The model implements a key-value memory over label-token positions: each label token's residual stream encodes the label's identity, and middle-layer attention heads write into it the class of the preceding demonstration as its key. At the query, upper-layer heads match the query's class against the stored keys and copy out the matching labels. An early-layer signal encoding whether any label has repeated gates this readout; in its absence the readers attend to the beginning of the prompt and no label is favored, a default that softmax normalization makes unavoidable. A separate set of heads suppresses the most recently seen label, removing a recency bias. Each step is established causally by activation patching between minimal-pair prompts, head ablations against random-head baselines, and steering with the model's own signals. Cutting the connections shows that sixty percent of a class flip passes through the readers and that a few amplified readers cannot replace the rest. A softmax model of the readout with two identifiable constants per head, fit on one prompt distribution, predicts another. The computation is conserved across the three models; which heads fill each role varies. The named heads alone reproduce the behaviour, and a transformer trained from scratch grows the same parts, the gate only when retrieval is penalised. The circuit transfers to semantic concepts; with the concept's own words as labels, the same reader and brake types carry the part of the margin that follows the demonstrations, while the part that follows word meaning lies outside it. The same parts, with a causal gate, appear from 0.6B to 8B in one family; across that range the brakes' hold on word meaning rises with the flipped-label margin, the behaviour Wei et al. (2023) found only in large models, and the base model's heads still carry retrieval after instruction tuning. ICL in this setting is a gated associative lookup built from a few identifiable component types, traced causally from demonstrations to prediction.

*Equal contribution. Correspondence to gaodrew@stanford.edu. Code, batteries and an interactive walkthrough: https://github.com/andrewgcodes/in-context-learning-circuit.

1 INTRODUCTION

Show a base language model a dozen lines like these,

The soup was cold and the waiter rude -> bar A gorgeous evening with old friends -> foo ... I would not go back to that place ->

and it answers bar. Nothing in pretraining taught it that foo means a pleasant evening or that bar means a bad meal. The model worked that out from the prompt, in a single forward pass, without any change to its weights. This is few-shot in-context learning (Brown et al., 2020), one of the abilities that turned language models into general-purpose tools. Labelling sentences is its simplest form, and it is the form we study here; instructions, long-form tasks and binding among many classes are outside the scope of this paper.

Several pieces of the mechanism are already known. Induction heads copy the token that followed an earlier occurrence of the current token (Olsson et al., 2022). Work on task vectors and function vectors (Hendel et al., 2023; Todd et al., 2023) has shown that a handful of heads carry a compact description of the demonstrated task to the query. Label tokens are where task information accumulates (Cho et al., 2024; Zheng et al., 2024; Hu et al., 2025), and the recency bias of in-context learning has been traced to query-key similarity with label positions (Yu & Ananiadou, 2024). What has been missing is an account of how these pieces fit together into one working algorithm. It was not known exactly what gets written at the label tokens, or on which side of attention it is later read; which heads read it, and what switches that read on and off; how the result reaches the logits; or which of the parts are single heads one can name and which exist only as populations that act in sum.

This paper gives such an account for two-class label retrieval and function selection, on invented-word and natural labels, with up to twelve demonstrations, in three base models of three to four billion parameters: Qwen3-4B, SmolLM3-3B and Llama-3.2-3B. In the field's terms we describe a circuit and the algorithm it implements. Figure 2 draws the circuit, Figure 3 lays it out along the layers, and Figure 1 places it on a single prompt.

In brief, the model turns its demonstrations into a key-value memory inside the prompt. Each label token becomes a slot whose value is the identity of the label and whose key is the class of the sentence it followed. The key is deposited by about twenty attention heads in the middle layers, which read the sentence and write its class into the label token's residual stream (K-composition in the sense of Elhage et al. 2021). When the model reaches the query it computes the class of the new sentence, and about ninety heads in the upper layers compare that class with the slot keys through an ordinary softmax over positions and copy out the labels whose keys match. These readers are, in effect, induction heads keyed on a class.

The read is gated. Early in the network, duplicate-token heads register whether any label has appeared twice, and that information is pooled into a single direction in the residual stream at the query. The direction lowers the logit that the readers assign to the attention sink at position zero. When no label repeats, the sink wins the softmax and the readers return nothing in particular. We call this outcome the null action. It follows from the softmax itself, since attention has to go somewhere, and the sink is where these heads put the attention they do not spend on the slots. Finally, a population of about two dozen heads writes against whichever label the model saw most recently. These are negative heads in the sense of Wang et al. (2022) and McDougall et al. (2023). We call them brakes, because removing them nearly triples the margin and leaves the model biased toward the most recent label.

Every step of this account rests on an intervention with a matched control. We build pairs of prompts that are identical token for token except in one span, where we change one sentence, one label or the query, and we move activations from one member of the pair into the other, head by head, group by group or position by position. We knock out heads and compare against random heads from the same layers. We steer the residual stream along directions at the strength the model itself uses and compare against random directions of the same norm. Every head set chosen on one draw of prompts is confirmed on a fresh draw. Where the model concentrates a function in a few heads we name them. Where it spreads a function over many, we describe the population by the direction it reads or writes, and show that this direction matters more than a random subspace of the same dimension. We also

Figure

Figure 1: One twelve-demonstration prompt, stage by stage. Columns are tokens (sentences sis_i, arrows, labels and the query qq) and rows are layers of Qwen3-4B. Each coloured block marks the tokens and layers where a stage acts: the duplicate detectors and the encoder early on, the writers into the label tokens in the middle layers, and then, at the query arrow, the query code, the gate, the readers, the brakes and the readout band. Later sections give the intervention behind each block.

account for the answer exactly. On each prompt, the contributions of all heads and MLPs to the answer logit add up to the model's own logit to within 0.05 nats.

Two results surprised us. The first is that the read follows a simple law. The attention each reader pays to the matching slots is described by a softmax expression in the number of matching slots, the total number of slots and the null logit. It has three constants per head, of which two are identifiable, because two of them enter only through their sum. Constants fitted on twelve-demonstration prompts predict a regime with one slot per class that was never used in fitting, in both Qwen and Llama. The same constants fail on longer prompts. When we looked at why, we found that each head's attention to the sink, and its total attention to the matching slots, are roughly fixed properties of the head, so adding matching slots divides a fixed budget among them.

The second surprise concerns why so many of the components are populations. A single reader already separates the two classes in its attention pattern, so the model is not spreading the work because individual heads lack the signal. What individual heads lack is output gain. No head contributes more than 0.2 nats of logit directly, so a 1.3-nat answer is a sum over at least seven heads. (A 1.3-nat change between two prompts needs at least four, since a head's contribution can change sign.)

Sections 3 to 8 follow the computation from the slot, through the read (Section 4), the gate (Section 5) and the query code (Section 6), to the readers and brakes (Section 7) and the final logits. Section 9 asks which parts of the account any transformer would need and which are left to training, and tests the account in two further models and across training checkpoints. Sections 10 and 11 carry the circuit to natural concepts and word labels, to four model sizes and to an instruction-tuned model, and Section 12 builds it twice, once by hand and once by training a small transformer from scratch. After related work (Section 13), Section 14 sets out what the account does not cover, including the predictions that did not hold, and what we think it implies more broadly.

References (41)