Induction Heads: Mathematical Foundations, Two-Layer Circuit Composition, and the Emergence of In-Context Learning in Transformers
One of the defining capabilities of modern autoregressive large language models is in-context learning: the ability to infer rules, adapt to task formats, and execute complex few-shot instructions purely from prompt context without updating neural network weights. For years, in-context learning was treated as an enigmatic, emergent property of large-scale autoregressive pre-training.
However, mechanistic interpretability research spearheaded by Anthropic (most notably in the landmark papers by Elhage et al. (2021) and Olsson et al. (2022)) demonstrated that in-context learning is driven by concrete, identifiable algorithmic sub-circuits known as induction heads.
Induction heads operate across transformer attention layers via inter-head composition. By combining a "previous-token head" in an early layer with an "induction head" in a downstream layer, the transformer implements a general pattern-matching and copying algorithm: if pattern appeared previously in the context, and the current token is , the circuit attends back to and boosts its probability as the next token.
Moreover, induction heads do not form gradually throughout pre-training. They crystallize during a sharp, macroscopic phase transition early in training, directly coinciding with a steep reduction in in-context loss across model scales.
Understanding the mathematical mechanics, matrix factorization, and circuit dynamics of induction heads provides fundamental insight into how transformer architectures transition from simple n-gram memorization to general algorithmic reasoning.
1. The Transformer Circuit Decomposition Framework
To analyze induction heads rigorously, we adopt the mathematical framework of transformer circuits formulated by Elhage et al. (2021).
The Residual Stream as a Linear Communication Bus
In a standard decoder-only transformer with layers, hidden dimension , and attention heads per layer, the central backbone is the residual stream. For a sequence of input tokens , the initial representations are formed by token and positional embeddings:
Each attention layer and feed-forward network (MLP) reads from the residual stream and adds its output back into the stream via residual connections:
Finally, the output logits for predicting token are computed by applying the unembedding matrix :
Because residual connections are additive, the residual stream acts as a linear communication channel where individual attention heads write vectors into specific subspaces without overwriting existing representations.
Factorizing Attention: QK and OV Circuits
For an individual attention head in layer , parameterized by query matrix , key matrix , value matrix , and output projection , the head's computation factorizes into two distinct bilinear operations:
- The Query-Key (QK) Circuit: Determines the attention pattern , defining where information is routed:
where is the causal attention mask ( for , and for ). The product is the QK matrix, representing an unnormalized bilinear form over the residual stream.
- The Output-Value (OV) Circuit: Determines what vector is written into the residual stream:
The separation into and is fundamental: computes routing attention probabilities, while applies a linear transformation to the attended source token representations before writing the result to the destination token's residual stream.
2. Multi-Head Layer Composition
A single attention layer can only perform operations where keys, queries, and values depend directly on the raw input embeddings . In a multi-layer transformer, the inputs to layer include the additive outputs of earlier heads in layers .
Let be an attention head in Layer 1 with output matrix , and let be an attention head in Layer 2. When processes the residual stream, its input at position is:
This enables three structural types of inter-head composition:
- -Composition: Head computes keys by multiplying against the output of :
The effective interaction between queries at position and keys produced via at position is governed by the composite matrix:
- -Composition: Head computes queries from the output of via .
- -Composition: Head computes values from the output of via .
Induction heads rely primarily on -composition and direct -copying.

[Layer 1: Previous-Token Head]
Source: Token A (pos j-1) ---> Writes "Saw A" vector to Residual Stream at Token B (pos j)
|
v
[Layer 2: Induction Head]
Query: Reads Token A (pos n) <---> Key: Matches "Saw A" at pos j ($K$-Composition)
|
Attends to pos j
|
Value: Copies Token B (pos j)
|
v
Destination: Residual Stream at pos n ---> Unembedding ---> Predicts Token B (pos n+1)3. The Mathematical Mechanics of the Two-Layer Induction Circuit
Consider an arbitrary token sequence containing a repeated subsequence:
The objective of an induction circuit is to predict that the token following is .
A 1-layer transformer cannot solve this problem for arbitrary, novel tokens and . At position , the model sees token . To know that should follow, it must search the historical context for prior occurrences of , determine what token immediately followed that prior occurrence (), and copy . Because attention is a linear combination of existing representations, a single layer cannot simultaneously identify where occurred and look one step ahead to .
The induction circuit solves this in two layers using two collaborating heads.
Step 1: The Previous-Token Head (Layer 1)
In Layer 1, a dedicated attention head develops an attention pattern that shifts representations forward by one token index:
The output written by into the residual stream at token position (where the token is ) is:
When evaluated at position , the residual stream now contains:
The representation at position now explicitly carries a subspace encoding the identity of the previous token .
Step 2: The Induction Head (Layer 2)
In Layer 2, an induction head operates on the transformed residual stream.
The Query-Key Matching Mechanism (-Composition)
At the current sequence position , where the input token is , the induction head computes its query directly from the current token embedding:
At any candidate prior position , the induction head computes its key using the residual stream :
The resulting unnormalized attention logit between query position and key position is the dot product:
Expanding this product yields two terms:
During training, the composite matrix:
is optimized such that when projected through embedding space , it approximates a positive scaled identity matrix:
Under this alignment:
- If , the dot product is approximately zero (orthogonal random embeddings in high-dimensional space).
- If , the term evaluates to .
Consequently, the softmax attention weights at position heavily concentrate on index :
The Output-Value Copying Mechanism
Once the induction head attends to position , it extracts the value vector at position :
The head projects this value back into the residual stream at current position :
When the final residual stream reaches the unembedding layer , the contribution to the logit vector over the vocabulary is:
where is the one-hot indicator for token .
The model optimizes with positive scalar . This ensures that whenever the head attends to token , it directly increases the logit corresponding to token in the next-token distribution, successfully completing the sequence:
4. The Induction Head Phase Change
One of the most striking empirical findings documented by Olsson et al. (2022) is that induction heads do not form continuously or linearly during training. Instead, models exhibit a distinct, macro-level phase transition.
Measuring the In-Context Learning (ICL) Slope
To quantify in-context learning independently of general pre-training loss improvements, researchers compute the loss as a function of sequence position .
Early in pre-training, a model's cross-entropy loss at token index is barely lower than its loss at token index . The model relies almost exclusively on static unigram frequencies and local bigram associations.
As training proceeds, training runs across 2-layer toy transformers, 6-layer models, and frontier multi-billion parameter architectures encounter a sharp transition window:
- The In-Context Learning Jump: Over a narrow range of optimizer steps (often spanning less than 2% to 5% of total training duration), the difference in loss between late sequence tokens and early sequence tokens drops dramatically.
- The Training Loss Bump / Plateau: In many architectures, this phase transition is marked by a visible inflection or brief plateau in the aggregate training loss curve, reflecting structural reorganization of attention weights across layers.
- Simultaneous Metric Synchronization: The phase change coincides precisely with a steep rise in two quantitative circuit metrics:
- Prefix Matching Score: The degree to which Layer 2 heads attend back to position when .
- Copying Score: The eigenvalue spectrum alignment of along the positive real axis.
Training Steps --->
|
| Loss at Token 50 --------------------------------
|
| Loss at Token 500 ----------------\
| \ <-- Induction Head Phase Change
| \ (Rapid ICL Capacity Formation)
| \-------------------------
vWhy One-Layer Models Cannot Form Induction Circuits
In a strict 1-layer transformer (without recurrent memory or positional bigram embeddings), the attention logits at position are limited to:
Because the key depends only on and position , contains no information about .
A 1-layer head can implement:
- Previous-token attention: Attending to via positional terms .
- Direct token matching: Attending to previous instances of .
- Positional copying: Copying fixed offsets.
However, a 1-layer head cannot condition attention to on the identity of while simultaneously matching across arbitrary, variable distances. Thus, a minimum depth of two attention layers (or an attention layer composed with an active non-linear MLP layer) is mathematically required to support induction circuits.
5. Functional Generalization: Beyond Exact Token Matching
While the canonical induction head matches identical token strings (), empirical analysis reveals that induction circuits rapidly generalize into flexible, semantic pattern engines.
The induction circuit family spans several specialized variations:
- Exact Token Induction: Routing triggers on exact token ID equality () and transfers the exact token representation () for repeated sequence reproduction and verbatim recall.
- Fuzzy / Semantic Induction: Routing triggers when semantic cosine similarity exceeds a threshold () and transfers semantic neighbors for synonym handling, paraphrased recall, and analogical completion.
- Cross-Lingual Induction: Routing matches translated counterparts () to enable in-context few-shot machine translation.
- Structural / Role Induction: Routing matches syntactic roles or delimiters (such as key-value separators) to extract associated value tokens for JSON parsing and structured reasoning.
Fuzzy Induction Heads
In real-world text, concepts recur with variations in inflection, punctuation, or synonymy. In fuzzy induction heads, the composite matrix:
does not behave as a strict diagonal delta function , but rather as a dense semantic kernel matrix. If and , the inner product produces a high attention score, enabling the model to retrieve contextually associated tokens even when surface forms diverge.
Translation and In-Context Mapping
In few-shot prompting setups such as:
induction circuits compose with feed-forward representation layers to match relational patterns rather than surface identities. The Layer 1 head encodes the structural delimiter (e.g., the arrow ), while the Layer 2 induction head binds the query concept to the prior relational exemplars, copying the translated category vector into the output distribution.
The Indirect Object Identification (IOI) Circuit
In their detailed circuit dissection of GPT-2 Small, Wang et al. (2022) demonstrated that complex linguistic tasks like Indirect Object Identification (for example: rely on an elaborate 26-head circuit where specialized duplicate token heads, name mover heads, and negative induction heads interact. Duplicate token heads signal repeated instances of "John", inhibiting the model from outputting "John" and allowing name mover heads (an induction variant) to copy the non-duplicated name "Mary".
6. Verification and Causal Interventions
Mechanistic interpretability relies on causal intervention techniques to prove that induction heads are necessary and sufficient drivers of in-context learning.
[Prompt Sequence] ---> [Forward Pass] ---> [Measure Logit Attribution]
|
[Intervention Stage]
+--------------+--------------+
| |
[Activation Patching] [Ablation / Zeroing]
(Isolate Circuit Path) (Measure Causal Degradation)
| |
+--------------+--------------+
v
[Validated Circuit Function]1. Activation Patching (Path Patching)
To establish causality without permanently damaging model representations, researchers perform activation patching:
- Run a clean forward pass on sequence .
- Run a corrupted forward pass on sequence where the pattern is disrupted.
- Replace the activation output of candidate head during the corrupted run with its activation from the clean run.
- If restoring the output of alone recovers the model's ability to predict , the head is causally sufficient for that computational step.
2. Direct Logit Attribution (DLA)
Because the residual stream is linear, any head contributes an additive term to the pre-unembedding state. The direct contribution of that head to the logit difference between target token and distractor token is computed analytically:
Across diverse models, induction heads consistently show the largest positive DLA values for repeated tokens and in-context classification labels.
3. Head Ablation / Knockout Experiments
When identified induction heads are systematically ablated (their attention outputs set to zero or replaced with mean activations over a dataset), models experience:
- A severe drop in few-shot prompt accuracy across standard benchmarks (MMLU, GSM8K, Big-Bench).
- Complete loss of synthetic associative recall ability (e.g. repeated random sequence memorization).
- Degradation of in-context loss reduction slopes over extended prompt contexts.
7. Architectural Implications and Modern Scaling
The discovery of induction heads has shaped both tokenizer design and the evolution of non-transformer sequence models.
Positional Encodings: RoPE and Relative Biases
Induction heads require Layer 1 previous-token heads to reliably shift token representations by an offset of , and Layer 2 induction heads to match keys across arbitrary distances .
- Rotary Position Embeddings (RoPE): Encode relative position as complex rotations in 2D subspaces. Because RoPE preserves the dot product as a function of relative distance , it allows induction heads to maintain stable QK matching across sequence lengths scaling from 4k to 1M+ tokens.
- Attention with Linear Biases (ALiBi): Applies linear penalties proportional to . While ALiBi excels at local extrapolation, strong negative slope penalties can attenuate the long-range key-query matching required for induction heads over extreme context windows.
Transformers vs. Recurrent Models and State Space Models (SSMs)
A central challenge for pure Recurrent Neural Networks (RNNs) and early State Space Models (e.g., S4, linear attention) is the Associative Recall (AR) task: retrieving a value associated with an arbitrary key seen hundreds of steps earlier in a single forward pass.
While transformers solve associative recall naturally through induction circuits via explicit pairwise attention over all historical keys, fixed-size recurrent state vectors must compress historical key-value pairs into finite memory bounds. Modern SSMs like Mamba (Gu & Dao, 2023) introduce input-dependent continuous state transitions () specifically to emulate induction-like selective associative retrieval without storing the full quadratic KV cache.
Summary and Key Takeaways
- In-Context Learning Engine: Induction heads are the fundamental mechanistic circuits responsible for copying, pattern replication, and few-shot in-context learning in autoregressive language models.
- Two-Layer Composition: The minimal induction circuit requires two attention layers: a Layer 1 previous-token head that shifts token representations by one position, and a Layer 2 induction head that uses -composition to match the current token against shifted historical keys and -projection to copy the target token.
- Macroscopic Phase Change: Induction heads form abruptly during training in a distinct phase transition that coincides with a rapid steepening of the model's in-context learning loss slope.
- Generalization: Beyond exact token copying, induction heads generalize to fuzzy semantic matching, cross-lingual translation, and complex grammatical routing circuits like Indirect Object Identification.
- Architectural Significance: The ability to form induction circuits is a primary benchmark for sequence model architectures, explaining the historical dominance of transformers on in-context reasoning tasks and motivating selective state dynamics in modern SSMs.
Sources
- In-context Learning and Induction Heads (Olsson et al., 2022)
- A Mathematical Framework for Transformer Circuits (Elhage et al., 2021)
- Interpretability in the Wild: a Circuit for Indirect Object Identification in GPT-2 small (Wang et al., 2022)
- Mamba: Linear-Time Sequence Modeling with Selective State Spaces (Gu & Dao, 2023)
- Transformer circuits thread: In-context Learning and Induction Heads (Anthropic Research)



