Lesson 3: Multi-head attention, split, joined and switched off
Module 2 · Lesson 3 · About 50 minutes · Needs: Module 2, Lessons 1 and 2 (naive_attentionwithscale, the Maya trace, the GPT-2 head survey)
The situation
Sol 405 at Aurora Station. naive_attention now has a test and a scale switch. Kofi Mensah opens the base configuration: width 128, 4 heads of width 32. "Why four? One head of 128 has the same weights. And Lesson 1 found 144 heads in GPT-2. If one does nothing, show me."
This lesson adds MultiHeadAttention to tinyformer/attention.py, races one wide head against several at equal size, and switches GPT-2's heads off one at a time and together. If you met heads in the ai-engineering course (Module 6, Lesson 1), skim section 1.
A real case, first
In "Are Sixteen Heads Really Better than One?" (NeurIPS 2019, arXiv:1905.10650), Paul Michel, Omer Levy and Graham Neubig switched off heads in two trained models: a 6-layer, 16-head translation transformer (WMT English to French) and BERT base. They report that "a large percentage of attention heads can be removed at test time without significantly impacting performance".
In the translation encoder only 8 of 96 heads changed BLEU significantly when removed alone, half of them for the better. Most layers worked with one head, but cutting the last encoder-decoder layer to one head cost 13.56 BLEU. Pruning heads across the whole model, they removed 20% (translation) and 40% (BERT) "without incurring any noticeable negative impact"; beyond that, performance dropped sharply. Redundant one at a time does not mean removable all together. You will measure both halves of that sentence.
What you will be able to do
- Work out head width, weight count and attention-matrix size for any head count.
- Build multi-head attention by splitting, concatenating and projecting, and match PyTorch.
- Catch a wrong head split with a causal leak test.
- Compare one wide head with several at equal parameters, with seeds.
- Ablate GPT-2's heads singly and together, and read what redundancy means.
1. Multi-head dimension arithmetic (Essential)
One head returns one weighted average per position. If a token needs two things from two places, one average has to blend them. Multi-head attention runs several smaller heads side by side, each with its own average. Paste the torch setup cell, shared block 1 and Lesson 2's naive_attention.
import torch
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # every lesson runs on "cpu"; a GPU is optional
torch.manual_seed(11) # the course seed (see course-guide/06)
print("torch", torch.__version__, "| device", DEVICE, "| CPU threads", torch.get_num_threads())Code walkthrough
- The course's torch setup cell. It printed
torch 2.14.1 | device cpu | CPU threads 5on the author's Mac.
import random
import torch
COURSE_DATE = "2026-10-09" # versions, model names and prices checked on this day
SEED = 11 # every generator in the course starts from this seed
SNAPSHOT_SOL = 400 # the corpus is the station record up to sol 399
def set_seed(seed=SEED):
"""Seed Python and PyTorch so a cell gives the same numbers every run."""
random.seed(seed)
torch.manual_seed(seed)
set_seed()
print("torch", torch.__version__, "| threads", torch.get_num_threads())Code walkthrough
- Shared block 1, as written:
SEED = 11andset_seed().
import math
import torch.nn.functional as F
def naive_attention(q, k, v, mask=None, return_weights=False, scale=None):
"""Lesson 2's naive_attention: scale=None divides by sqrt(d_head); any number multiplies instead."""
scores = q @ k.transpose(-2, -1)
scores = scores * (1 / math.sqrt(q.shape[-1]) if scale is None else scale)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
weights = scores.softmax(dim=-1)
out = weights @ v
return (out, weights) if return_weights else outCode walkthrough
- Lesson 2's function, unchanged. It already accepts any leading axes, so a heads axis needs no new code.
Back to Maya at width 8. Lesson 1 used one head of width 4. Now keep that head as head 0 and add head 1 with three new matrices. Stacked side by side, the query matrix is 8 by 8. Splitting heads is pure reshaping: view cuts each token's 8 numbers into 2 groups of 4, and transpose moves the head axis forward.
ids = torch.tensor([[32, 45, 68, 45]]) # "Maya", as in Lessons 1 and 2
set_seed()
embed = torch.nn.Embedding(69, 8)
W_q, W_k, W_v = (torch.randn(8, 4) / 8 ** 0.5 for _ in range(3)) # head 0: Lesson 1's head, unchanged
W_q1, W_k1, W_v1 = (torch.randn(8, 4) / 8 ** 0.5 for _ in range(3)) # head 1: three new matrices
Wq, Wk, Wv = (torch.cat(pair, dim=1) for pair in [(W_q, W_q1), (W_k, W_k1), (W_v, W_v1)]) # (8, 8) each
n_heads, d_head = 2, 8 // 2
def split_heads(t): # (B, T, d_model) -> (B, heads, T, d_head)
B, T, _ = t.shape
return t.view(B, T, n_heads, d_head).transpose(1, 2)
with torch.no_grad():
x = embed(ids)
q, k, v = (split_heads(x @ W) for W in (Wq, Wk, Wv))
mask = torch.ones(4, 4, dtype=torch.bool).tril()
out, w = naive_attention(q, k, v, mask, return_weights=True)
print("x", tuple(x.shape), "| q after split", tuple(q.shape), "| weights", tuple(w.shape), "| out", tuple(out.shape))
for h in range(n_heads):
print(f"head {h}, row 3 (second a):", [round(a, 2) for a in w[0, h, 3].tolist()])Code walkthrough
- The first three
randndraws repeat Lesson 1 exactly, so head 0 is Lesson 1's head.torch.cat(..., dim=1)puts head 1's four columns after head 0's. split_headsisview(B, T, 2, 4)thentranspose(1, 2): (1, 4, 8) becomes (1, 2, 4, 4), batch, heads, tokens, head width.naive_attentionruns both heads at once, because the heads axis is just one more leading axis.
Head 0 gives the second a [0.46, 0.21, 0.12, 0.21], Lesson 1's row to the digit. Head 1 gives [0.30, 0.19, 0.32, 0.19]: it reads y most. Same token, two readings.
The general rule: with model width d_model and h heads, each head has head width d_head = d_model / h, and owns one block of d_head columns in each projection. The base model has 128 / 4 = 32 (arithmetic).
def attention_weights(d_model, n_heads):
"""Weights in one attention layer: W_q, W_k, W_v (d_model -> heads x d_head) and W_o back."""
d_head = d_model // n_heads
return 3 * d_model * n_heads * d_head + n_heads * d_head * d_model
for h in [1, 2, 4, 8, 16]:
print(f"d_model 128, {h:2d} heads: d_head {128 // h:3d} | weights {attention_weights(128, h):,} "
f"| attention-matrix entries per sequence of 128: {h * 128 * 128:,}")
print("6 heads at d_model 128: d_head", 128 / 6, "-> not a whole number, so the split fails")Code walkthrough
attention_weightscounts the three input projections and the output projection. Because heads x d_head is always d_model, the count is 4 x d_model squared.- The second column counts attention weights: one T by T matrix per head.
Weights stay at 65,536 from 1 head to 16. What grows is the attention matrix: 16,384 entries per sequence with one head, 262,144 with sixteen. Heads cost activation memory, not weights; Lesson 5 returns to that.
The last line printed 21.33: 6 heads cannot split 128. The width must divide evenly, so the lab's class asserts it.
2. Concatenation and the output projection (Essential)
The heads' outputs must return to one vector per token, the width the next layer expects. How they return decides what the heads can do together.
Concatenation undoes the split: transpose the heads axis back and lay each token's heads side by side. For the second a, columns 0 to 3 come from head 0 and 4 to 7 from head 1.
def merge_heads(t): # (B, heads, T, d_head) -> (B, T, d_model)
B, H, T, hd = t.shape
return t.transpose(1, 2).reshape(B, T, H * hd)
concat = merge_heads(out)
print("concatenated", tuple(concat.shape), "| columns 0-3 are head 0:", torch.equal(concat[0, :, :4], out[0, 0]),
"| columns 4-7 are head 1:", torch.equal(concat[0, :, 4:], out[0, 1]))
print("second a after concatenation:", [round(a, 2) for a in concat[0, 3].tolist()])
W_o = torch.randn(8, 8) / 8 ** 0.5 # the output projection
together = concat @ W_o
per_head = out[:, 0] @ W_o[:4] + out[:, 1] @ W_o[4:] # each head writes through its own 4 rows of W_o
print("concatenate then project == sum of per-head writes:", torch.allclose(together, per_head, atol=1e-6))Code walkthrough
merge_headsreversessplit_heads:transpose(1, 2)thenreshapeto (1, 4, 8). Thetorch.equalchecks confirm which columns hold which head.W_ois a random output projection.per_headmultiplies each head's output by its own 4 rows ofW_oand adds the two.
It printed True. Concatenating then projecting is the same as each head writing through its own slice of W_o, then summing. So W_o is where heads meet: each writes its own contribution, and switching a head off removes exactly one term.
The lab's class does all of this with one matrix for every head's queries, keys and values.
import torch.nn as nn
class MultiHeadAttention(nn.Module):
"""n_heads heads of width d_model // n_heads side by side, then one output projection."""
def __init__(self, d_model, n_heads):
super().__init__()
assert d_model % n_heads == 0, "d_model must split evenly into heads"
self.n_heads, self.d_head = n_heads, d_model // n_heads
self.qkv = nn.Linear(d_model, 3 * d_model, bias=False) # every head's W_q, W_k, W_v in one matrix
self.out = nn.Linear(d_model, d_model, bias=False) # W_o
def forward(self, x, mask=None):
B, T, D = x.shape
q, k, v = (t.view(B, T, self.n_heads, self.d_head).transpose(1, 2) # split
for t in self.qkv(x).chunk(3, dim=-1))
y, self.weights = naive_attention(q, k, v, mask, return_weights=True) # (B, heads, T, d_head)
return self.out(y.transpose(1, 2).reshape(B, T, D)) # concatenate, projectCode walkthrough
self.qkvmaps 128 to 384: queries, keys and values for all heads.chunk(3, dim=-1)cuts them apart;viewandtransposesplit each into heads.self.weightskeeps the (B, heads, T, T) weights for inspection. The last line concatenates and appliesself.out, W_o.
set_seed()
mha = MultiHeadAttention(128, 4) # the base model's sizes: width 128, 4 heads of 32
torch_mha = nn.MultiheadAttention(128, 4, bias=False, batch_first=True)
with torch.no_grad():
torch_mha.in_proj_weight.copy_(mha.qkv.weight) # PyTorch stacks W_q, W_k, W_v the same way
torch_mha.out_proj.weight.copy_(mha.out.weight)
x = torch.randn(32, 128, 128) # batch 32, 128 tokens, width 128
causal = torch.ones(128, 128, dtype=torch.bool).tril()
with torch.no_grad():
mine = mha(x, causal)
theirs, _ = torch_mha(x, x, x, attn_mask=~causal, need_weights=False) # PyTorch's mask: True = blocked
print("largest difference from nn.MultiheadAttention:", f"{(mine - theirs).abs().max().item():.1e}")
print("parameters:", sum(p.numel() for p in mha.parameters()), "| 4 x 128 x 128 =", 4 * 128 * 128)Code walkthrough
nn.MultiheadAttentionis PyTorch's layer.copy_gives it our weights, so any difference is in the computation.- PyTorch's mask marks blocked pairs with
True, the opposite of ours, hence~causal.
The largest difference is 1.8e-07, float32 rounding, and the layer has 65,536 weights, as the arithmetic said.
Break it: split heads with a bare reshape
reshape(B, heads, T, d_head) gives the right shape without the transpose. Nothing crashes.
class WrongSplit(MultiHeadAttention):
def forward(self, x, mask=None):
B, T, D = x.shape
q, k, v = (t.reshape(B, self.n_heads, T, self.d_head) # the bug: reshape straight to heads
for t in self.qkv(x).chunk(3, dim=-1))
return self.out(naive_attention(q, k, v, mask).transpose(1, 2).reshape(B, T, D))
def future_leak(layer, T=128):
"""Change only the last token. In a causal layer no earlier output may move."""
set_seed()
x = torch.randn(1, T, 128)
x2 = x.clone()
x2[0, -1] += 1.0
with torch.no_grad():
moved = layer(x, causal) - layer(x2, causal)
moved = moved[0, :-1].abs().amax(-1) # largest change at each earlier position
return moved.max().item(), int((moved > 1e-6).sum())
bad = WrongSplit(128, 4)
bad.load_state_dict(mha.state_dict()) # same weights, only the split differs
print("output shape:", tuple(bad(x, causal).shape))
for name, layer in [("correct split", mha), ("wrong split", bad)]:
size, count = future_leak(layer)
print(f"{name}: earlier outputs moved by up to {size:.1e}, at {count} of 127 earlier positions")Code walkthrough
WrongSplitcopies the class with one change:reshapestraight to (B, heads, T, d_head).future_leaknudges only the last token and counts earlier positions whose output moved. A causal layer must move none.
reshape fills the new shape in memory order, so each "head" receives a run of 32 whole tokens' features, read as if they were 128 short tokens. Rows of the causal mask no longer mean tokens.
The shape is still (32, 128, 128). The correct split moved 0 earlier positions; the wrong one moved 3, by up to 3.0e-02: the future leaks into the past. This causal leak test goes into tests/test_m02_attention.py.
3. Several heads against one wide head (Essential)
Equal weights do not mean equal ability. Measure it on a task where each answer needs two separate tokens.
The compare task, added in this lesson: 16 random tokens, a separator, then one answer per token, 1 if token i is greater than token i + 1, 2 if smaller, 3 if equal. The first row starts 7, 19, 19, 22, so its answers start 2, 3, 2. Answers 1 and 2 each make up 48% of targets (measured here).
Why should one head struggle? To answer, a position needs token i and token i + 1, and must know which is which. One head returns one average: half of 7 and half of 19 is the same blend for (7, 19) and (19, 7), whose answers differ. Two heads can each take one token and hand both over unmixed.
Paste shared block 9 (the TaskData bundle), then add the task.
from typing import NamedTuple
class TaskData(NamedTuple):
name: str
vocab_size: int
inputs: torch.Tensor # (n, T) token ids
targets: torch.Tensor # (n, T) the next token at every position
mask: torch.Tensor # (n, T) 1 where the answer is scored, 0 elsewhere
def _shift(name, vocab, seq, scored_from):
inputs, targets = seq[:, :-1], seq[:, 1:]
mask = torch.zeros_like(inputs)
mask[:, scored_from:] = 1
return TaskData(name, vocab, inputs, targets, mask)
def make_task(name, n=4096, length=16, vocab=32, seed=SEED):
"""copy, reverse or induction. Token 0 is the separator; content tokens are 1 to vocab - 1."""
g = torch.Generator().manual_seed(seed)
body = torch.randint(1, vocab, (n, length), generator=g)
sep = torch.zeros(n, 1, dtype=torch.long)
if name == "copy":
seq = torch.cat([body, sep, body], dim=1)
elif name == "reverse":
seq = torch.cat([body, sep, body.flip(1)], dim=1)
elif name == "induction": # random tokens, then the same random tokens again
seq = torch.cat([body, body], dim=1)
return _shift(name, vocab, seq, scored_from=length)
TASKS = {name: make_task(name) for name in ["copy", "reverse", "induction"]}
for t in TASKS.values():
print(t.name, tuple(t.inputs.shape), "scored positions per row:", int(t.mask[0].sum()))Code walkthrough
- Shared block 9, as written. The exercise uses
copy;_shiftmakes inputs, next-token targets and the scoring mask for the new task.
def make_compare(n=4096, length=16, vocab=32, seed=SEED):
"""Added in this lesson. 16 random tokens, separator 0, then one answer per token:
1 if token i is greater than token i + 1, 2 if smaller, 3 if equal (the last token wraps to the first)."""
g = torch.Generator().manual_seed(seed)
body = torch.randint(1, vocab, (n, length), generator=g)
after = body.roll(-1, dims=1) # token i + 1 for every i
answer = torch.where(body > after, 1, torch.where(body < after, 2, 3))
seq = torch.cat([body, torch.zeros(n, 1, dtype=torch.long), answer], dim=1)
return _shift("compare", vocab, seq, scored_from=length)
TASKS["compare"] = make_compare()
row = TASKS["compare"].inputs[0]
print("first row, tokens 0-3:", row[:4].tolist(), "| separator:", row[16].item(), "| answers 0-2:", row[17:20].tolist())
print("answer shares:", [round((TASKS["compare"].targets[:, 16:] == c).float().mean().item(), 3) for c in (1, 2, 3)])Code walkthrough
body.roll(-1, dims=1)shifts each row left by one, soafter[i]is token i + 1 (the last wraps round).torch.whereturns each pair into 1, 2 or 3. Scoring starts at position 16, as in copy.
The model is one pre-norm block of width 64. The head count is the only switch, and every version has 56,032 parameters (measured here).
class Block(nn.Module):
"""Pre-norm block: multi-head attention, then a feed-forward layer, each added back."""
def __init__(self, d, n_heads):
super().__init__()
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = MultiHeadAttention(d, n_heads)
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
def forward(self, x):
causal = torch.ones(x.shape[1], x.shape[1], dtype=torch.bool).tril()
x = x + self.attn(self.norm1(x), causal)
return x + self.ff(self.norm2(x))
class HeadLab(nn.Module):
"""One block, width 64; n_heads is the only switch."""
def __init__(self, n_heads, vocab=32, d=64, context=32):
super().__init__()
self.embed, self.pos = nn.Embedding(vocab, d), nn.Embedding(context, d)
self.block = Block(d, n_heads)
self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, vocab))
def forward(self, ids):
return self.head(self.block(self.embed(ids) + self.pos(torch.arange(ids.shape[1]))))
print({h: sum(p.numel() for p in HeadLab(h).parameters()) for h in [1, 2, 4, 8]})Code walkthrough
Blockis Lesson 2's block withMultiHeadAttentionin place of the single head. Module 3 builds the real block.HeadLabadds token and position embeddings and an output layer. The print confirms equal sizes.
import time
def train_heads(n_heads, seed, task, steps=400, n_valid=512):
set_seed(seed)
model, g = HeadLab(n_heads), torch.Generator().manual_seed(seed)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
for step in range(steps):
i = torch.randint(0, len(task.inputs) - n_valid, (64,), generator=g)
losses = F.cross_entropy(model(task.inputs[i]).flatten(0, 1), task.targets[i].flatten(), reduction="none")
loss = (losses * task.mask[i].flatten()).sum() / task.mask[i].sum()
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
xv, yv, mv = (t[-n_valid:] for t in (task.inputs, task.targets, task.mask))
with torch.no_grad():
right = (model(xv).argmax(-1) == yv).float()
return (right * mv).sum().item() / mv.sum().item(), model
t0, MODELS = time.perf_counter(), {}
for h in [1, 2, 4, 8]:
accs = []
for seed in (11, 12, 13):
acc, MODELS[h, seed] = train_heads(h, seed, TASKS["compare"])
accs.append(round(acc, 3))
print(f"{h} head(s), d_head {64 // h:2d}: held-out accuracy {accs} mean {sum(accs) / 3:.3f}")
print(f"12 runs in {time.perf_counter() - t0:.0f} s")Code walkthrough
train_headsis Lesson 2's loop: AdamW, 64 rows a step, loss on scored positions only, clipping at 1.0. It returns held-out accuracy on the last 512 rows, never trained on, and the model.- The loops make 12 runs: four head counts, three seeds. They took 16 to 19 s on the author's Mac; allow up to four times that on a free Colab CPU.
One head of width 64 reached 0.706 to 0.753. Two heads: 0.824 to 0.843. Four: 0.956 to 0.971; eight, 0.961 to 0.974. The worst four-head seed beats the best one-head seed by 0.20, far outside the seed spread. On this task, at equal parameters, splitting wins.
x_valid = TASKS["compare"].inputs[-512:] # the held-out rows
rows = torch.arange(16, 31) # positions whose answer compares token i with i + 1
for h in [1, 4]:
with torch.no_grad():
MODELS[h, 11](x_valid) # fills .weights: (512, heads, 32, 32)
top = MODELS[h, 11].block.attn.weights[:, :, rows].argmax(-1) - rows # where each row looks hardest
for head in range(h):
print(f"{h}-head model, head {head}: largest weight on token i {(top[:, head] == -16).float().mean():.2f}"
f" | on token i + 1 {(top[:, head] == -15).float().mean():.2f}")
ceiling = sum(max(a - 1, 31 - a) for a in range(1, 32)) / 31 / 31
print(f"best accuracy when only one of the two tokens is read: {ceiling:.3f}")Code walkthrough
- Position 16 + i answers about tokens i and i + 1, which sit 16 and 15 places back.
argmax(-1) - rowsis the offset of each row's largest weight. ceilingis arithmetic: knowing one token a, guess the likelier side; average the hit rate over a.
In the four-head model, head 1 looks hardest at token i in 100% of rows and head 0 at token i + 1 in 97%: a clean division of labour. The single head settles on neither (8% and 13%). Reading one token perfectly would score 0.734; the single head sits around that.
4. Head redundancy and ablation (Recommended)
Section 3 says several heads help. Michel and colleagues say many can be removed. Both hold; measure GPT-2 small to see how.
Ablation means switching a part off and measuring the damage. GPT-2 concatenates 12 heads of 64 into 768 columns before its output projection, c_proj. Zero one head's 64 columns there and, as section 2 showed, exactly that head's term disappears. This is how Michel and colleagues masked heads.
%pip install -q transformers==5.19.0from transformers import AutoModelForCausalLM, AutoTokenizer
REF = "openai-community/gpt2" # the course's reference model: GPT-2 small, MIT licence
tok = AutoTokenizer.from_pretrained(REF)
ref = AutoModelForCausalLM.from_pretrained(REF, attn_implementation="eager").eval()
g = torch.Generator().manual_seed(SEED)
R = 50 # Lesson 1's test: 50 random tokens, then the same 50
rnd = torch.randint(1000, 10000, (4, R), generator=g)
seq = torch.cat([torch.full((4, 1), tok.bos_token_id), rnd, rnd], dim=1) # (4, 101)
OFF = set() # (layer, head) pairs to switch off
def zero_heads(module, args, layer):
x = args[0].clone() # (4, 101, 768): the 12 heads concatenated
for l, h in OFF:
if l == layer:
x[..., h * 64:(h + 1) * 64] = 0 # remove head h's 64 columns before W_o
return (x,)
for l, block in enumerate(ref.transformer.h):
block.attn.c_proj.register_forward_pre_hook(lambda m, a, l=l: zero_heads(m, a, l))
def repeat_loss():
"""Mean loss on the repeated half, where only copying from the first half can help."""
with torch.no_grad():
logits = ref(seq).logits
return F.cross_entropy(logits[:, R + 1:-1].flatten(0, 1), seq[:, R + 2:].flatten()).item()
BASE = repeat_loss()
print(f"repeat-half loss, all 144 heads on: {BASE:.3f}")Code walkthrough
- The loading lines and
seqare Lesson 1's: four rows of 50 random tokens, written twice after<|endoftext|>. - A forward pre-hook runs just before a layer and may replace its input.
zero_headszeroes the columns of every head inOFFfor its layer;l=lfreezes each layer's number. repeat_lossscores only the second copy, where an induction circuit can predict every token.
The repeat-half loss is 0.299 nats with every head on (measured here).
t0 = time.perf_counter()
delta = torch.zeros(12, 12)
for l in range(12):
for h in range(12):
OFF = {(l, h)}
delta[l, h] = repeat_loss() - BASE # how much worse without this one head
OFF = set()
print(f"144 single-head ablations in {time.perf_counter() - t0:.0f} s")
print("heads costing under 0.05:", int((delta < 0.05).sum()), "| over 0.2:", int((delta > 0.2).sum()),
"| that lower the loss:", int((delta < 0).sum()))
for i in delta.flatten().argsort(descending=True)[:3].tolist():
print(f" head {i // 12}.{i % 12}: +{delta.flatten()[i]:.3f}")
print(f"head 5.5, Lesson 1's induction head: +{delta[5, 5]:.3f}")Code walkthrough
- Each pass switches off one head and stores the change in loss; 144 passes took 14 s on the author's Mac.
- The prints count heads by cost and name the three costliest.
Of 144 heads, 118 cost under 0.05 nats and 50 lower the loss slightly when removed. Ten cost over 0.2; head 1.10 is the costliest at +0.587. Head 5.5, Lesson 1's star induction head, costs only +0.124. That is head redundancy: other heads cover for one that is missing.
with torch.no_grad():
A = torch.stack(ref(seq, output_attentions=True).attentions) # (12, 4, 12, 101, 101)
pos = torch.arange(R + 1, 2 * R + 1)
induction = A[..., pos, pos - R + 1].mean((1, 3)) # Lesson 1's induction score
heads = [(l, h) for l in range(12) for h in range(12) if induction[l, h] > 0.4]
print(len(heads), "induction heads:", " ".join(f"{l}.{h}" for l, h in heads))
print(f"sum of their single-head costs: {sum(delta[l, h].item() for l, h in heads):+.2f}")
OFF = set(heads)
print(f"all {len(heads)} off together: {repeat_loss() - BASE:+.2f} (loss {repeat_loss():.2f})")
OFF = set()Code walkthrough
inductionis Lesson 1's score, with its 0.4 threshold. The last lines switch off every induction head at once.
Eleven heads pass: 5.0, 5.1, 5.5, 6.9, 7.2, 7.10, 9.6, 9.9, 10.1, 10.7 and 11.10. One at a time their costs sum to +0.38. All off together, the loss rises by +10.05, to 10.35: copying is gone. Single-head ablation measured what each head adds given all the others, not what it does.
5. Pruning several heads together (Optional)
Pruning removes heads for good, to save memory and time. Section 4 warns that costs do not add, so the order and number removed matter.
order = [divmod(i, 12) for i in delta.flatten().argsort().tolist()] # least costly first
random.seed(SEED)
shuffled = random.sample(order, len(order))
print(f"{'heads off':>9} {'least costly first':>19} {'random order':>13}")
for n in [0, 12, 24, 36, 48, 72, 144]:
losses = []
for plan in (order, shuffled):
OFF = set(plan[:n])
losses.append(repeat_loss())
print(f"{n:9d} {losses[0]:19.2f} {losses[1]:13.2f}")
OFF = set()Code walkthrough
orderranks heads by single-head cost, cheapest first;shuffledis a seeded random order. Each line switches off the first n heads of each plan together.
Removing the 12 cheapest heads lowered the loss to 0.19; 24 raised it to 1.10, and 72 to 4.72. Twelve random heads gave 4.03. Michel and colleagues pruned the same way, ranked by a gradient-based importance score instead of by single ablations, and saw the same shape at their scale: a flat start, then a sharp drop.
Pruning only pays if the matrices shrink. Masking, as here, saves nothing. Michel and colleagues removed half of BERT's heads for real and measured up to 17.5% more examples per second at batch 16 and 64, but 1.9% at batch 1.
In production
Head counts are chosen, not pruned. In "Attention Is All You Need" (Vaswani et al., 2017, Table 3), at fixed width one head scored 24.9 BLEU, eight heads 25.8 and thirty-two 25.4: "quality also drops off with too many heads". GPT-2 small uses 12 heads of 64. Production code calls a fused kernel with the same split and merge (Lesson 1). What teams change today is how many key and value heads to keep, because the cache stores them; Lesson 5 measures that.
What you added to tinyformer-lab
MultiHeadAttentionfortinyformer/attention.py: one qkv matrix, split,naive_attention, concatenate, project; checked againstnn.MultiheadAttention.- The causal leak test for
tests/test_m02_attention.py, which catches the wrong split. - The compare task and the one-head-against-many experiment. They stay in this lesson: the module lab keeps one seeded experiment,
experiments/m02_kv_heads.py(4, 2 and 1 key/value heads on the reverse task). - A head ablation hook for GPT-2, used again in Module 14.
Check yourself
- At width 128, how many weights does attention have with 1 head, and with 8?
- Why does concatenating then projecting equal a sum of per-head writes?
- The wrong split has the right shape. How does the leak test catch it?
- Why can one head not solve the compare task cleanly?
- Head 5.5 costs +0.124 alone. Why is it wrong to call it unimportant?
- 65,536 both times: heads x d_head is always 128, so the count is 4 x 128 x 128.
- Matrix multiplication by blocks: head t's columns of the concatenation meet only rows t of W_o.
- Changing the last token moved 3 earlier outputs; a causal layer moves none.
- Its one average blends the two tokens, and the blend of 7 and 19 is the same in either order.
- The other induction heads cover for it. All eleven off together cost +10.05.
Exercise
Multiple heads are not always needed. Predict whether one head of width 64 can learn the copy task, which needs one token per answer, then run the check.
def copy_check(steps=400):
acc_one, _ = train_heads(1, 11, TASKS["copy"], steps)
acc_four, _ = train_heads(4, 11, TASKS["copy"], steps)
assert acc_one > 0.95 and acc_four > 0.95, (acc_one, acc_four)
return round(acc_one, 3), round(acc_four, 3)
print("copy task, 1 head and 4 heads:", copy_check(), "check passed")Code walkthrough
copy_checktrains one head and four heads on copy with seed 11 and asserts both pass 95%. It printed(1.0, 1.0) check passed. Then changeTASKS["copy"]toTASKS["reverse"]and predict before rerunning.
Key terms
| Term | Meaning |
|---|---|
| Multi-head attention | Several attention heads side by side, each on its own slice of the width |
| Head width | d_head = d_model / h, the size of one head's queries, keys and values |
| Concatenation | Laying the heads' outputs side by side to rebuild width d_model |
| Output projection | W_o, which maps the concatenation back; each head writes through its own rows |
| Causal leak test | Change a later token and check that no earlier output moves |
| Ablation | Switching a part off and measuring the damage |
| Head redundancy | Other heads covering for one that is removed |
| Pruning | Removing heads for good to save memory and time |
Sources
- Paul Michel, Omer Levy, Graham Neubig, "Are Sixteen Heads Really Better than One?", NeurIPS 2019, sections 3.2 to 4.3, Tables 1, 2 and 4. https://arxiv.org/abs/1905.10650
- Ashish Vaswani et al., "Attention Is All You Need", 2017, Section 3.2.2 and Table 3. https://arxiv.org/abs/1706.03762
- PyTorch,
torch.nn.MultiheadAttention, documentation for version 2.14, checked October 2026. https://docs.pytorch.org/docs/2.14/generated/torch.nn.MultiheadAttention.html