Module contents
Stage 2 of 8Advanced 100 min

Induction heads and phase changes

Train one- and two-layer attention-only transformers on text and investigate the emergence of induction heads, changes in loss, and in-context learning. Detect candidate heads with scores on random repeated sequences, analyze their composition with previous-token heads, and search for them in your own GPT.

After this lesson you can

  • Train one- and two-layer attention-only models while saving frequent checkpoints.
  • Calculate prefix-matching and copying scores on repeated sequences.
  • Relate the emergence of induction heads to changes in loss and in-context learning scores.
  • Measure K-composition between previous-token and induction heads and locate both in your own GPT.

Before you start

Look for a capability, not just a pattern

An induction head implements part of a contextual copying rule: if A,BA,B appeared earlier and AA appears again, the earlier context can help predict BB. An earlier head can write information about AA at the position of BB; another head queries that writing to locate the successor. The framework of Olsson and colleagues offers observable hypotheses, not an automatic label for every attention map.

Induction head detection uses a sequence of distinct tokens repeated twice. For queries in the second copy, the prefix score averages the attention paid to the successor of the earlier match. It is also necessary to check whether OV copies the token and whether an ablation harms prediction; high attention alone does not establish that the head is necessary or sufficient.

An experiment with a negative result

We reuse the models and measured report from m30-l16: one- and two-layer attention-only models, with four heads per layer and 64 dimensions, trained on 2000 TinyStories documents per split. Each processed 40 960 000 bytes in 10 000 steps; 12 checkpoints include natural-text loss, scores, copying and ablations. Eight sequences of 32 distinct bytes are sampled uniformly from the 71 bytes observed at least 20 times and then repeated. This is an artificial probe, not a representative sample of natural text.

InteractiveMeasured evolution, one and two layers
Attention from queries 33 to 63 over keys 1 to 32. Blue opacity is min(1, 8 × attention); values above 0.125 saturate.
0
Second-layer head
Prefix score0.022
In-context learning−0.327
Move through the checkpoints and change the head. Lines connect discrete measurements; the map shows attention from the second copy to the first.

Two-layer natural-text validation loss drops from 5.838 to 1.616 nats on a fixed batch. At the end, second-layer prefix scores are 0.0158, 0.0038, 0.0008 and 0.0039, compared with 0.0216 for uniform causal attention. The difference in natural-text loss at positions 50 and 500 is −0.515 nats. The eight individual ablations reduce the average loss on the second repeated half by between 0.057 and 1.637 nats. Thus, this run demonstrates neither an induction head nor the predicted jump. The complete report has SHA-256 ea9dc389eb86377fdbdfa1b6496c3c641344d58ed837d4e725f81d4732d7ea44.

Phase-change analysis requires checkpoints, multiple seeds, copying metrics and causal controls. A simultaneous jump in curves is a temporal correlation; an ablation can affect multiple pathways and requires comparison with alternatives. The negative result of this run does not by itself contradict the paper: the architecture, vocabulary, corpus, budget and protocol differ. No trained p06 checkpoint is available here, and no specific heads are attributed to it.

In a one-layer attention-only block, for a fixed query and two earlier positions containing the same token, their relative scores depend on their positional embeddings and not on the token preceding each position. This limits that prefix-matching mechanism in one head; it does not prove that every one-layer architecture is incapable of copying.

Lab: train and save checkpoints

The following cell reproduces the experiment from the related lesson from scratch. Install torch, numpy and datasets; it downloads the pinned TinyStories revision. By default it runs 2000 steps; use ORYON_STEPS=10000 for the budget behind the curves and ORYON_M30_16_DIR to choose the directory. ORYON_QUICK=1 checks the workflow with a reduced model and dataset and does not reproduce the figure’s numbers. Checkpoints can use disk space and runtime depends on the device.

[ ]Train and record diagnosticsLocal GPU
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')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Search your GPT and a public reference

The following probe accepts a snapshot of the p06 GPT through P11_CKPT, either a file or a folder of snapshots, and loads its configuration and weights. If it finds none, it uses GPT-2 small from the pinned public revision and clearly prints that identity; this is a different architecture and training run, not a substitute presented as your model. For either model it constructs eight sequences of 32 distinct repeated IDs, measures attention per head to the earlier successor and to the previous token, and ablates the three heads with the highest prefix score. The OV copying fraction compares only the 32 IDs from the first example and omits contextual and LayerNorm effects. Weight K-composition is a normalized affinity between the highest-scoring previous-token head and each later candidate; it does not prove that the pathway is used.

For the published GPT-2, seed 1102 and the eight examples, head 5.5 has prefix score 0.913 versus 0.0216 for uniform attention, and its ablation increases second-half loss by 0.244 nats. Head 5.1 scores 0.896 and +0.544, while 7.10 scores 0.892 and −0.037. The latter illustrates that a high pattern score does not suffice to demonstrate individual necessity. The highest-scoring previous-token head is 4.11 (0.988); its K-composition with 5.5 is 0.098. These numbers depend on the sample and differ from natural-text TinyStories training; layer and head indices start at zero. The test does not locate a phase change in GPT-2 because it uses only one checkpoint.

[ ]Probe your own checkpoint or the published GPT-2Local GPU
import os, json, torch
from pathlib import Path
from transformers import AutoModelForCausalLM, GPT2Config, GPT2LMHeadModel
torch.set_num_threads(2)
device='cuda' if torch.cuda.is_available() else 'cpu'
path=Path(os.environ.get('P11_CKPT','p06_pretrain/runs/full/snapshots'))
files=[path] if path.is_file() else sorted(path.rglob('model-*.pt')) if path.is_dir() else []
rev='607a30d783dfa663caf39e06633721c8d4cfcd7e'
if files:
 ck=torch.load(files[-1],map_location='cpu',weights_only=True)
 sd={k.removeprefix('_orig_mod.'):v for k,v in ck.get('model',ck).items() if torch.is_tensor(v)}
 v,d=sd['transformer.wte.weight'].shape;t=sd['transformer.wpe.weight'].shape[0]
 layers=1+max(int(k.split('.')[2]) for k in sd if k.startswith('transformer.h.'))
 heads=int((ck.get('config') or {}).get('heads',12))
 cfg=GPT2Config(vocab_size=v,n_positions=t,n_embd=d,n_layer=layers,n_head=heads,attn_implementation='eager')
 model=GPT2LMHeadModel(cfg)
 trans=('attn.c_attn.weight','attn.c_proj.weight','mlp.c_fc.weight','mlp.c_proj.weight')
 sd={k:(v.T.contiguous() if k.endswith(trans) else v) for k,v in sd.items()}
 sd['lm_head.weight']=sd['transformer.wte.weight'];model.load_state_dict(sd,strict=True)
 identity=f'p06 {files[-1]} paso {ck.get("step")}'
else:
 model=AutoModelForCausalLM.from_pretrained('openai-community/gpt2',revision=rev,attn_implementation='eager')
 identity='GPT-2 small publicado '+rev
model.eval().to(device);cfg=model.config;v=cfg.vocab_size;heads=cfg.n_head;layers=cfg.n_layer;d=cfg.n_embd;dh=d//heads
gen=torch.Generator().manual_seed(1102);n=32;batch=2 if os.environ.get('ORYON_QUICK')=='1' else 8
base=torch.stack([torch.randperm(v-1,generator=gen)[:n] for _ in range(batch)]).to(device)
x=torch.cat([base,base],dim=1);inp=x[:,:-1];target=x[:,1:]
with torch.no_grad():
 out=model(inp,use_cache=False,output_attentions=True);pats=out.attentions
 q=torch.arange(n,2*n-1,device=device);pref=torch.stack([p[:,:,q,q-n+1].mean((0,2)) for p in pats])
 prev=torch.stack([p[:,:,1:,torch.arange(inp.shape[1]-1,device=device)].diagonal(dim1=-2,dim2=-1).mean((0,2)) for p in pats])
 base_loss=torch.nn.functional.cross_entropy(out.logits[:,n-1:].reshape(-1,v),target[:,n-1:].reshape(-1))
top=torch.topk(pref.flatten(),min(3,pref.numel())).indices.tolist();abl=[]
prev_index=int(prev.flatten().argmax());pl,ph=divmod(prev_index,heads)
def matrices(layer,head):
 block=model.transformer.h[layer].attn
 q,k,value=block.c_attn.weight.split(d,dim=1);s=slice(head*dh,(head+1)*dh)
 return q[:,s]@k[:,s].T,block.c_proj.weight[s,:].T@value[:,s].T
_,early_ov=matrices(pl,ph)
embedding=model.transformer.wte.weight.detach();subset=base[0]
for idx in top:
 l,h=divmod(idx,heads)
 with torch.no_grad():
  qk,ov=matrices(l,h);den=torch.linalg.norm(qk)*torch.linalg.norm(early_ov)
  kscore=float(torch.linalg.norm(qk@early_ov)/den) if pl<l else None
  copy=embedding[subset]@ov@embedding[subset].T
  copy_score=float((copy.argmax(0)==torch.arange(n,device=device)).float().mean())
 def hook(mod,args):
  z=args[0].clone();z[:,:,h*dh:(h+1)*dh]=0;return (z,)+args[1:]
 hand=model.transformer.h[l].attn.c_proj.register_forward_pre_hook(hook)
 try:
  with torch.no_grad():
   z=model(inp,use_cache=False).logits[:,n-1:]
   loss=torch.nn.functional.cross_entropy(z.reshape(-1,v),target[:,n-1:].reshape(-1))
   abl.append({'layer':l,'head':h,'prefix':float(pref[l,h]),'loss_change':float(loss-base_loss),'copy_subset':copy_score,'k_composition':kscore})
 finally:hand.remove()
print(json.dumps({'identity':identity,'prefix_max':abl,'previous_head':[pl,ph],'previous_max':float(prev.max()),'uniform':float((1/(q+1).float()).mean()),'repeat_loss':float(base_loss)},ensure_ascii=False))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The brief ORYON_QUICK=1 test uses two sequences and only validates the workflow. To measure your checkpoint, run the full size with its path and record the identifier it prints; the absence of a checkpoint in this test is not a result about that model.

Exercises

Numeric
The loss at token 50 is 3.8 and the loss at token 500 is 3.1. Calculate loss(50)−loss(500).
Quiz
A head has a high prefix score, but its ablation barely changes the loss. Which conclusion is prudent?
Quiz
What constrains the comparison of two identical occurrences of a token in a head of a one-layer attention-only model?
Code
Implement induction_score(model, seq_len, n): generate n sequences of seq_len distinct IDs between 0 and model.vocab−1 with default_rng(0), repeat each sequence, and call model(tokens). The result has shape batch × heads × 2seq_len × 2seq_len. Average A[q,q−seq_len+1] for q=seq_len,…,2seq_len−2 and across the batch; return one score per head.
def induction_score(model, seq_len, n):
  pass
Shift+Enter to run
Key idea
An induction head is established through patterns, copying and intervention effects; report the outcome of a training run even when the expected phenomenon does not appear.