Induction heads: train your own model and watch the phase change
Study the two-head induction mechanism, its prefix-matching, copying, composition and in-context learning diagnostics, and reported phase changes. Construct a head by hand, test ablations, and examine measurements from models trained locally.
After this lesson you can
- Explain induction as K-composition between a previous-token head and a copying head.
- Construct the weights of a two-layer transformer that implements exact induction by hand.
- Train one- and two-layer models and locate induction heads using prefix matching, copying and composition scores.
- Measure the in-context learning score throughout training and locate a phase change.
- Confirm the mechanism with previous-token and induction-head ablations.
Before you start
- 30Attention-only transformers and skip-trigramsResidual stream path decompositionDirect logit attributionHook points and activation caching
- 18Causal maskLearned positional embeddingRotary position embedding
- 20In-context learningData properties driving in-context learning
- 00Canonical training and evaluation loopPyTorch learning rate schedulersFull training checkpoint
Finding the continuation of a repetition
If a sequence contains “A B … A”, one strategy is to find a previous occurrence of A and copy the token that followed it. The result B depends on a relationship between two past positions. The figure implements an explicit two-head model with softmax attention and weights defined by identity and position matches. These are not measured activations from a trained model.
A previous-token head writes information about the preceding position’s token at each position. For example, if B follows A, the write at B indicates “A came before”. The induction head looks, for the current A, for a position whose key contains that previous A; from that position it reads value B. The circuit and interpretation come from Olsson and colleagues.
Head composition here is K-type: the earlier write enters the later head’s key. It is not a head simply attending to duplicate token A, because that pattern would read A; it seeks the following position, B. In a one-layer model without prior contextual states, a key receives only that position’s token and position. Thus “which token preceded this one” is not explicit in that key. The argument requires explicit architectural and positional-encoding assumptions and does not imply that one layer cannot solve restricted cases with bigram statistics.
Clean test and measurements
In natural text, “A B” may be predictable without using repetition. To isolate the operation, take a random sequence and repeat it: the second half contains continuations seen in the first. Evaluate on sequences distinct from training and compare with a head that simply attends to the duplicate. At the first position of the second half specify whether to count the continuation whose source is the last token of the first half; sequence boundaries affect the denominator.
The prefix-matching score is mean attention directed to positions following an earlier occurrence of the query token, under a specified distribution and index rule. A high score measures an attention pattern; it remains to check that the OV circuit copies the value and an intervention affects prediction.
The in-context learning score compares mean losses at early and late positions, for example token 50 loss minus token 500 loss. A positive difference indicates lower loss at the late position under the evaluated distribution, but does not itself identify a head or explain the cause of improvement.
An induction phase change is a rapid transition observed in training diagnostics, not a guaranteed jump for every architecture or seed. Olsson et al. assemble several lines of evidence, including ablations. Chan et al. study how distribution properties influence in-context learning; do not extrapolate a synthetic-distribution result to every language model.
The clean pattern does not exhaust induction: Olsson and colleagues also describe translation and approximate-matching examples where the key-query relationship may be semantic rather than literal token equality. Position matters too: an earlier head can learn an offset with absolute embeddings, while other encodings offer different ways to represent distances. Therefore check pattern and intervention in each architecture rather than assuming identical weights implement them.
In models analyzed by Olsson and colleagues, the reported window is between and tokens, approximately 1–2% of training for their large models. Temporal coincidence between head formation and score improvement is relevant evidence but does not itself prove those heads cause all improvement. The same work examines interventions and cautions about possible shared factors. Our laboratory has a different architecture, tokenization and budget; there is no reason to expect a figure from that study to transfer literally.
The following local run uses one seed, 2000 documents per split and 10000 steps for each depth, with batch 8 and context 512: 40960000 processed tokens per model. Diagnostics use eight fixed windows per checkpoint, so they are exploratory. For the repetition probe, 32 distinct bytes were chosen uniformly without replacement from the 71 appearing at least 20 times in training, then repeated. This avoids confusing a large number of never-seen bytes with the induction test, though the artificial sequence does not follow the natural-text distribution either.
Mean natural loss on the two-layer model’s validation batch falls approximately from 5.838 to 1.616 nats, evidence of learning on that batch. In contrast, its four final second-layer prefix scores are approximately 0.0158, 0.0038, 0.0008 and 0.0039, versus 0.0216 for uniform causal attention. In this run no step appears that justifies identifying an induction head. The natural 50-minus-500 score ends at approximately −0.515 nats for the same batch. A negative difference is possible and does not mean in-context learning is impossible under other conditions. The export identifies the reevaluated report by SHA-256 ea9dc389eb86377fdbdfa1b6496c3c641344d58ed837d4e725f81d4732d7ea44.
At the last checkpoint, mean loss in the second half of those eight sequences is approximately 9.800 nats. The eight individual ablations reduce that mean by between 0.057 and 1.637 nats. This does not confirm the sought mechanism: the test does not identify a pair whose removal destroys an induction capability. The result is limited to this model and small artificial probe. To investigate disagreement with the published study, expand budget and seeds, evaluate more sequences and separately verify prefix matching, copying and ablation effects; do not turn a manual simulation into evidence of a learned circuit.
Composition scores use products of feature matrices. For a first-layer sender with and receiver with and , numerators are , and . Each is divided by the product of its factors’ norms. These measure weight compatibility, not use on a particular input or causal proof; ablation and loss add another view.
Controlled construction
The following embeddings are one-hot; one channel stores the token and another stores position. The first score assigns strength to the previous position and the second compares the current token with the copied channel. NumPy’s printed indices start at zero. Softmax with finite weights does not give probability exactly one: in this example the argmax prediction is exact and remaining mass is small. BOS prevents the first token being confused with its own predecessor. Ablation zeros the channel written by the first head.
To construct weights, divide the residual into three blocks: token, position and previous token. In the first head the query reads position one-hot and the key applies offset ; their product is one exactly if . Its OV circuit copies the token block into the previous-token block. In the second, query reads the current-token block and key the previous-token block, while OV carries the attended position’s token block to logits. Causal masks exclude the future. The first position can attend only to itself; BOS distinct from A avoids a false match here. This construction is for finite lengths and vocabulary, not a universal accuracy claim for sequences with multiple matches or every strength.
import numpy as np
tokens = np.array([4, 0, 1, 2, 3, 0])
vocab, T = 5, len(tokens)
beta = 30.0
token_embed = np.eye(vocab)[tokens]
position = np.eye(T)
def causal_softmax(scores):
mask = np.tril(np.ones(scores.shape, dtype=bool))
scores = np.where(mask, scores, -np.inf)
exp = np.exp(scores - scores.max(axis=-1, keepdims=True))
return exp / exp.sum(axis=-1, keepdims=True)
# Q0 = position, K0 = position shifted by one; V0 copies the token channel.
shift = np.zeros((T, T))
for j in range(T - 1):
shift[j + 1, j] = 1
A0 = causal_softmax(beta * position @ shift @ position.T)
previous = A0 @ token_embed
# Q1 reads the current token and K1 reads the previous-token channel.
A1 = causal_softmax(beta * token_embed @ previous.T)
copied = A1 @ token_embed
print('Última consulta atiende a:', int(A1[-1].argmax()))
print('Predicción:', int(copied[-1].argmax()), 'esperada:', 1)
print('Masa de atención al sucesor previo:', float(A1[-1, 2]))
# Ablación: sin primera cabeza, la clave de la segunda es cero.
A1_ablated = causal_softmax(beta * token_embed @ np.zeros_like(previous).T)
copy_ablated = A1_ablated @ token_embed
print('Sin cabeza anterior, masa en sucesor:', float(A1_ablated[-1, 2]))
print('Sin cabeza anterior, predicción:', int(copy_ablated[-1].argmax()))
without_pos = causal_softmax(np.zeros((T, T))) @ token_embed
A1_no_pos = causal_softmax(beta * token_embed @ without_pos.T)
print('Sin posición, masa en sucesor:', float(A1_no_pos[-1, 2]))
print('Sin posición, predicción:', int((A1_no_pos @ token_embed)[-1].argmax()))
assert copied[-1].argmax() == 1 and A1[-1, 2] > 0.99The controlled experiment proves possibility for this sequence and rules, not that a trained model learned the circuit. An intervention altering the internal distribution can introduce out-of-distribution states; compare ablations, controls and multiple examples.
Local laboratory: saving and auditing checkpoints
This run trains one- and two-layer attention-only models with learned position embeddings on TinyStories bytes. It uses the pinned revision and official training and validation splits; it saves byte-stream hashes. Documents are concatenated with a newline, so a window can cross a boundary. By default it uses 2000 documents per split, context 512, four heads and 2000 updates per model. To reproduce figures use ORYON_STEPS=10000; ORYON_STEPS allows choosing budget from scratch. Option ORYON_QUICK=1 reduces size and steps to check the pipeline and uses positions 5 and 50, not 50 and 500. ORYON_M30_16_DIR chooses the checkpoint and metrics directory.
Each checkpoint records repetition loss, prefix-matching attention, the fraction of bytes for which OV ranks the same byte first, Q, K and V composition scores, and curves after ablating each head. Copying evaluates the full OV circuit without position embeddings; it is not a full contextual-copy measurement. Repeated sequences select distinct bytes with a fixed seed from those seen at least 20 times in training, and prefix score includes queries from the first position of the second copy through the penultimate. In the short test the threshold is one appearance and 16 distinct bytes are used. The first loss in the second half includes the jump between copies; not all its tokens have a useful earlier prefix. Uniform causal attention is also recorded as a baseline.
The context score uses a fixed validation batch and estimates loss at tokens 50 and 500 counted from 1. It is a noisy diagnostic: increase batch count and repeat with independent seeds before interpreting differences or locating a transition. Training and validation windows come from official splits; the code does not check near-duplicates between them.
import os, json, hashlib
from pathlib import Path
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from datasets import load_dataset
REV = 'f54c09fd23315a6f9c86f9dc80f725de7d8f9c64'
QUICK = os.environ.get('ORYON_QUICK') == '1'
ROOT = Path(os.environ.get('ORYON_M30_16_DIR', './oryon-m30-l16'))
ROOT.mkdir(parents=True, exist_ok=True)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
T, D, H, B = (64, 16, 2, 4) if QUICK else (512, 64, 4, 8)
docs = 16 if QUICK else 2000
steps = 4 if QUICK else int(os.environ.get('ORYON_STEPS', '2000'))
if steps < 1:
raise ValueError('ORYON_STEPS debe ser positivo')
schedule = [0, 2, 4] if QUICK else [0, 100, 200, 400, 800, 1200, 1600, 2000, 3000, 5000, 8000, 10000]
save_steps = sorted({s for s in schedule if s <= steps} | {steps})
def data(split):
rows = load_dataset('roneneldan/TinyStories', split=split, streaming=True, revision=REV)
text = [row['text'] for _, row in zip(range(docs), rows)]
stream = b'\n'.join(t.encode('utf-8') for t in text)
return torch.tensor(list(stream), dtype=torch.long), hashlib.sha256(stream).hexdigest()
train, train_hash = data('train')
validation, validation_hash = data('validation')
minimum_count = 1 if QUICK else 20
observed = torch.nonzero(torch.bincount(train, minlength=256) >= minimum_count).flatten()
assert len(observed) >= (16 if QUICK else 32)
class Head(nn.Module):
def __init__(self):
super().__init__()
self.q = nn.Linear(D, D // H, bias=False)
self.k = nn.Linear(D, D // H, bias=False)
self.v = nn.Linear(D, D // H, bias=False)
self.o = nn.Linear(D // H, D, bias=False)
def forward(self, r):
score = self.q(r) @ self.k(r).transpose(-1, -2) / (D // H) ** 0.5
causal = torch.ones(r.shape[1], r.shape[1], device=r.device, dtype=torch.bool).tril()
A = score.masked_fill(~causal, float('-inf')).softmax(-1)
return self.o(A @ self.v(r)), A
class Net(nn.Module):
def __init__(self, depth):
super().__init__()
self.embed = nn.Embedding(256, D)
self.pos = nn.Embedding(T, D)
self.blocks = nn.ModuleList([nn.ModuleList([Head() for _ in range(H)]) for _ in range(depth)])
self.unembed = nn.Linear(D, 256, bias=False)
def forward(self, x, ablate=None):
r = self.embed(x) + self.pos(torch.arange(x.shape[1], device=x.device))
patterns = []
for layer, heads in enumerate(self.blocks):
outputs, attention = [], []
for h, head in enumerate(heads):
out, A = head(r)
outputs.append(torch.zeros_like(out) if ablate == (layer, h) else out)
attention.append(A)
r = r + sum(outputs)
patterns.append(torch.stack(attention, dim=1))
return self.unembed(r), patterns
def batch(stream, gen):
start = torch.randint(len(stream)-T, (B,), generator=gen)
chunk = stream[start[:, None] + torch.arange(T+1)].to(device)
return chunk[:, :-1], chunk[:, 1:]
def diagnostic(model):
model.eval()
g = torch.Generator().manual_seed(300)
x, y = batch(validation, g)
# Las posiciones que siguen son de los tokens destino, contadas desde 1.
with torch.no_grad():
logits, _ = model(x)
losses = F.cross_entropy(logits.reshape(-1,256), y.reshape(-1), reduction='none').reshape(B,T)
early, late = ((5, 50) if QUICK else (50, 500))
icl = (losses[:,early-2] - losses[:,late-2]).mean().item()
repeat_gen = torch.Generator().manual_seed(301)
n = 16 if QUICK else 32
base = torch.stack([observed[torch.randperm(len(observed), generator=repeat_gen)[:n]] for _ in range(B)]).to(device)
seq = torch.cat([base, base], dim=1)
pred, pats = model(seq)
q = torch.arange(n, 2*n-1, device=device)
prefix = [p[:, :, q, q-n+1].mean(dim=(0, 2)).tolist() for p in pats]
uniform = (1.0 / (q + 1)).float().mean().item()
loss = F.cross_entropy(pred[:, :-1].reshape(-1,256), seq[:, 1:].reshape(-1), reduction='none').reshape(B,-1)
ablations = []
for layer in range(len(model.blocks)):
row = []
for h in range(H):
ablated, _ = model(seq, ablate=(layer, h))
l = F.cross_entropy(ablated[:, :-1].reshape(-1,256), seq[:, 1:].reshape(-1), reduction='none').reshape(B,-1)
row.append(l.mean(dim=0).tolist())
ablations.append(row)
copying = []
for heads in model.blocks:
row = []
for head in heads:
ov = model.unembed.weight @ head.o.weight @ head.v.weight @ model.embed.weight.T
row.append((ov.argmax(dim=0) == torch.arange(256, device=device)).float().mean().item())
copying.append(row)
composition = []
if len(model.blocks) == 2:
for early_head in model.blocks[0]:
ov0 = early_head.o.weight @ early_head.v.weight
row = []
for late_head in model.blocks[1]:
qk = late_head.q.weight.T @ late_head.k.weight
ov1 = late_head.o.weight @ late_head.v.weight
def ratio(a, b):
den = torch.linalg.norm(a) * torch.linalg.norm(b)
return (torch.linalg.norm(a @ b) / den).item()
row.append({'q':ratio(ov0.T, qk), 'k':ratio(qk, ov0), 'v':ratio(ov1, ov0)})
composition.append(row)
return {'early': early, 'late': late, 'icl': icl, 'validation_loss':losses.mean().item(), 'prefix': prefix, 'uniform_prefix':uniform,
'probe_support':len(observed), 'probe_minimum_count':minimum_count,
'first_loss': loss[:, :n-1].mean().item(), 'second_loss': loss[:, n-1:2*n-1].mean().item(),
'loss_position': loss.mean(dim=0).tolist(), 'ablations': ablations,
'copying': copying, 'composition': composition,
'patterns': [p[0].tolist() for p in pats]}
records = []
for depth in (1, 2):
torch.manual_seed(19)
model = Net(depth).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=0.001)
gen = torch.Generator().manual_seed(900 + depth)
for step in range(steps + 1):
if step in save_steps:
metrics = diagnostic(model)
records.append({'depth':depth, 'step':step, **metrics})
torch.save({'config':{'depth':depth,'width':D,'heads':H,'context':T,'step':step,
'revision':REV,'train_sha256':train_hash,'validation_sha256':validation_hash},
'state_dict':model.state_dict()}, ROOT / f'depth-{depth}-step-{step}.pt')
print(json.dumps({'depth':depth, 'step':step, 'icl':metrics['icl'], 'prefix':metrics['prefix']}, ensure_ascii=False), flush=True)
model.train()
if step == steps:
break
x, y = batch(train, gen)
logits, _ = model(x)
loss = F.cross_entropy(logits.reshape(-1,256), y.reshape(-1))
opt.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
ROOT.joinpath('metrics.json').write_text(json.dumps(records, ensure_ascii=False, indent=2), encoding='utf-8')npm run lab and open the connection link.To regenerate compact figure data, retain metrics and export the necessary attention-map positions. The full report is saved first and its SHA-256 identifies the source. The short version generates another file with fewer positions and steps; it does not replace the run shown on the page.
import json, hashlib, os
from pathlib import Path
raw = ROOT / os.environ.get('ORYON_PROBE_REPORT', 'metrics.json')
records = json.loads(raw.read_text(encoding='utf-8'))
small = []
for r in records:
if r['depth'] != 2:
continue
n = (len(r['loss_position']) + 1) // 2
compact = dict(r)
compact['patterns'] = [[], [
[[round(v, 6) for v in row[:n]] for row in head[n:2*n-1]]
for head in r['patterns'][1]
]]
for key in ('loss_position',):
compact[key] = [round(v, 6) for v in compact[key]]
compact['ablations'] = [[[round(v, 6) for v in head] for head in layer] for layer in compact['ablations']]
small.append(compact)
control = [{'step':r['step'], 'icl':r['icl'], 'validation_loss':r['validation_loss'], 'prefix':r['prefix'][0],
'first_loss':r['first_loss'], 'second_loss':r['second_loss']}
for r in records if r['depth'] == 1]
out = {'source_sha256': hashlib.sha256(raw.read_bytes()).hexdigest(),
'quick': QUICK, 'records': small, 'control':control}
dest = ROOT / 'measurement.json'
dest.write_text(json.dumps(out, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('Exportado', dest, 'SHA-256 del informe:', out['source_sha256'])npm run lab and open the connection link.Exercises
Step 1 of 2. What changes in the keys of B and C?
def prefix_score(attn, n):
passdef k_score(A, B):
pass