CourseTransformers: From Attention to Trained, Served and Interpreted Models · Module 2: Self-Attention Mechanics · part 15 of 111
Part 15 · Module 2: Self-Attention Mechanics

Lesson 3: Multi-head attention, split, joined and switched off

21 min read·
Module 2 · Lesson 3 · About 50 minutes · Needs: Module 2, Lessons 1 and 2 (naive_attention with scale, 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".

HEADS SWITCHED OFF: WMT (6 X 16) AND BERT BASE one head off 8 of 96 encoder heads matter layer cut to 1 most layers fine; one loses 13.56 BLEU pruned together 20% WMT, 40% BERT then a sharp drop redundant alone is not removable together
Michel et al. (2019, cited): most single heads can go (green), most layers survive on one head but one loses 13.56 BLEU (amber), and joint pruning stops at 20% and 40% (red).

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.

python
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 5 on the author's Mac.
python
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 = 11 and set_seed().
python
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 out

Code walkthrough

  • Lesson 2's function, unchanged. It already accepts any leading axes, so a heads axis needs no new code.
MAYA'S QUERIES, MODEL WIDTH 8, TWO HEADS x @ Wq (1, 4, 8) view (1, 4, 2, 4) transpose(1, 2) (1, 2, 4, 4) batch, heads, tokens, head width
Splitting heads is reshaping only (blue, the lab's tensors): Maya's (1, 4, 8) queries become (1, 4, 2, 4), then (1, 2, 4, 4) with heads before tokens.

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.

python
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 randn draws 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_heads is view(B, T, 2, 4) then transpose(1, 2): (1, 4, 8) becomes (1, 2, 4, 4), batch, heads, tokens, head width.
  • naive_attention runs both heads at once, because the heads axis is just one more leading axis.
ROW 3, THE SECOND A: WHERE EACH HEAD READS head 0 M 0.46 a 0.21 y 0.12 a 0.21 head 1 M 0.30 a 0.19 y 0.32 a 0.19 head 0 is Lesson 1's head, to the digit
Head 0 reproduces Lesson 1's row (0.46 on M); head 1 puts most weight on y (0.32): two heads read the same token two ways (amber marks each head's largest weight).

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.

ONE TOKEN'S QUERY, 8 NUMBERS q0 q1 q2 q3 q4 q5 q6 q7 head 0: columns 0-3 head 1: columns 4-7 d_head = d_model / heads = 8 / 2 = 4
Each head owns a block of d_head columns: with width 8 and 2 heads, columns 0 to 3 are head 0 and 4 to 7 are head 1; in base, 128 / 4 = 32 (arithmetic).

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).

python
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_weights counts 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.
WIDTH 128: WEIGHTS AGAINST ATTENTION-MATRIX ENTRIES weights matrix entries, T = 128 1 x 128 65,536 16,384 2 x 64 65,536 32,768 4 x 32 65,536 65,536 8 x 16 65,536 131,072 16 x 8 65,536 262,144 heads x d_head
At width 128 the weights (blue) stay 65,536 from 1 head to 16, while the attention-matrix entries per sequence (amber) grow from 16,384 to 262,144 (arithmetic).

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.

128 / 4 = 32 4 heads of 32: valid 128 / 6 = 21.33 not whole: rejected the class asserts d_model % n_heads == 0
The width must split evenly: 128 into 4 heads of 32 works (green), 128 into 6 heads gives 21.33 and is rejected (red).

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.

SECOND A: EACH HEAD'S OUTPUT, THEN CONCATENATED 0.29 0.51 -0.48 0.00 -0.91 -0.13 0.88 0.17 head 0 head 1 0.29 -0.48 -0.91 0.88 0.51 0.00 -0.13 0.17 (1, 2, 4, 4) back to (1, 4, 8)
Concatenation lays the heads side by side: the second a's 4 numbers from head 0 (blue) and 4 from head 1 make one 8-number vector again.

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.

python
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_heads reverses split_heads: transpose(1, 2) then reshape to (1, 4, 8). The torch.equal checks confirm which columns hold which head.
  • W_o is a random output projection. per_head multiplies each head's output by its own 4 rows of W_o and adds the two.
head 0 out (4 numbers) head 1 out (4 numbers) W_o rows 0-3 W_o rows 4-7 sum = concat @ W_o checked: True each head writes its own term; remove one, lose one term
Projecting the concatenation equals each head writing through its own rows of W_o and summing (green: the check printed True), so switching a head off removes exactly one term.

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.

MULTIHEADATTENTION(128, 4), BATCH 32, 128 TOKENS qkv (32,128,384) split (32,4,128,32) attention per head concat (32,128,128) W_o (32,128,128) one matrix makes every head's q, k and v
The lab's MultiHeadAttention at base sizes: one qkv matrix, a split into 4 heads of 32, naive_attention per head (amber), concatenation and W_o (blue).

The lab's class does all of this with one matrix for every head's queries, keys and values.

python
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, project

Code walkthrough

  • self.qkv maps 128 to 384: queries, keys and values for all heads. chunk(3, dim=-1) cuts them apart; view and transpose split each into heads.
  • self.weights keeps the (B, heads, T, T) weights for inspection. The last line concatenates and applies self.out, W_o.
python
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.MultiheadAttention is 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.
our class 65,536 weights nn.MultiheadAttention same weights copied 1.8e-07 largest difference: float32 rounding
With the same weights, the lab's class and PyTorch's nn.MultiheadAttention differ by at most 1.8e-07 (green), float32 rounding.

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.

python
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

  • WrongSplit copies the class with one change: reshape straight to (B, heads, T, d_head).
  • future_leak nudges only the last token and counts earlier positions whose output moved. A causal layer must move none.
WHERE TOKEN 0'S 128 FEATURES GO view + transpose token 0 gives 32 to each of the 4 heads bare reshape head 0 gets tokens 0-31 cut into 128 rows of 32 same shape, different meaning of a row
view then transpose gives every head a slice of every token (green); a bare reshape hands head 0 tokens 0 to 31 chopped into 128 fake rows (red).

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.

CHANGE ONLY THE LAST TOKEN; COUNT EARLIER OUTPUTS THAT MOVE correct split 0 of 127 wrong split 3 of 127, up to 3.0e-02 the future leaks into the past
The causal leak test: the correct split moves no earlier output (green); the wrong split moves 3 of 127, so a later token changed the past (red).

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.

COMPARE TASK, FIRST ROW (ADDED IN THIS LESSON) 7 19 19 22 ... 0 2 3 2 ... 16 random tokens sep answers 7 < 19 gives 2; 19 = 19 gives 3; 19 < 22 gives 2 1 greater, 2 smaller, 3 equal
The compare task: each answer (green) says whether token i is greater than (1), smaller than (2) or equal to (3) token i + 1; the first row gives 2, 3, 2.

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).

one head 0.5 x 7 + 0.5 x 19 same blend for (19, 7) two heads head A: 7, head B: 19 order kept one average cannot say which token came first
One head returns one average, and the blend of 7 and 19 is the same whichever came first (red); two heads can each fetch one token and keep the order (green).

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.

python
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; _shift makes inputs, next-token targets and the scoring mask for the new task.
python
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, so after[i] is token i + 1 (the last wraps round).
  • torch.where turns each pair into 1, 2 or 3. Scoring starts at position 16, as in copy.
HEADLAB: ONE BLOCK, WIDTH 64 heads d_head parameters 1 64 56,032 2 32 56,032 4 16 56,032 8 8 56,032
The fair test: four HeadLab models with 1, 2, 4 and 8 heads all have 56,032 parameters (blue); only the split of the 64 columns changes.

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).

python
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

  • Block is Lesson 2's block with MultiHeadAttention in place of the single head. Module 3 builds the real block.
  • HeadLab adds token and position embeddings and an output layer. The print confirms equal sizes.
python
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_heads is 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.
HELD-OUT ACCURACY, 400 STEPS, SEEDS 11 TO 13 1 head 0.725 2 heads 0.831 4 heads 0.962 8 heads 0.968 0.734: one token read perfectly
At equal parameters, mean held-out accuracy rises from 0.725 with one head (red) to 0.962 with four (green); dots are seeds, and the dashed line is the one-token ceiling (arithmetic).

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.

python
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) - rows is the offset of each row's largest weight.
  • ceiling is arithmetic: knowing one token a, guess the likelier side; average the hit rate over a.
SHARE OF ROWS LOOKING HARDEST AT EACH TOKEN 1 head: head 0 token i 0.08 token i + 1 0.13 4 heads: head 0 token i 0.03 token i + 1 0.97 4 heads: head 1 token i 1.00 token i + 1 0.00
In the four-head model head 1 looks hardest at token i (amber) in every row and head 0 at token i + 1 (blue) in 97%; the single head settles on neither.

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.

ONE GPT-2 LAYER, JUST BEFORE C_PROJ (W_O) 0 1 2 3 4 5 6 7 8 9 10 11 head 5's 64 columns set to 0 12 heads x 64 = 768 columns
Ablating head 5 zeroes its 64 of the 768 concatenated columns (red) before GPT-2's output projection, removing exactly its term.

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.

python
%pip install -q transformers==5.19.0
python
from 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 seq are 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_heads zeroes the columns of every head in OFF for its layer; l=l freezes each layer's number.
  • repeat_loss scores 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).

python
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.
LOSS INCREASE WHEN ONE HEAD IS OFF (ROWS: LAYER) 0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10 11 118 heads under 0.05 (grey) 10 heads over 0.2 1.10: +0.587 5.5: +0.124
Switching off GPT-2's heads one at a time on the repeat task: 118 of 144 cost under 0.05 nats (grey), ten cost over 0.2 (deep red), and Lesson 1's head 5.5 (amber outline) only +0.124.

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.

python
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

  • induction is Lesson 1's score, with its 0.4 threshold. The last lines switch off every induction head at once.
THE 11 INDUCTION HEADS, REPEAT-HALF LOSS INCREASE one at a time, summed +0.38 all off together +10.05 loss 0.30 becomes 10.35: copying is gone
The 11 induction heads cost +0.38 when removed one at a time and summed (amber), but +10.05 when removed together (red): each covers for the others.

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.

python
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

  • order ranks heads by single-head cost, cheapest first; shuffled is a seeded random order. Each line switches off the first n heads of each plan together.
REPEAT-HALF LOSS AS HEADS ARE SWITCHED OFF TOGETHER 0 7 14 0 24 72 144 12 off: 0.19 | 24 off: 1.10 random order least costly first heads off
Removing heads least costly first (blue) keeps the loss at 0.19 for 12 heads, then it climbs to 1.10 at 24 and 4.72 at 72; a random order (grey) is worse from the start.

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.

BERT, HALF THE HEADS REMOVED: THROUGHPUT GAIN batch 1 +1.9% batch 4 +2.7% batch 16 +17.5% batch 64 +17.5%
Michel et al. (2019, cited): really removing half of BERT's heads gave up to 17.5% more throughput at batch 16 and 64 (green), but only 1.9% at batch 1.

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

TRANSFORMER BASE, FIXED WIDTH 512, DEV BLEU 1 head 24.9 4 heads 25.5 8 heads 25.8 16 heads 25.8 32 heads 25.4 axis starts at 24.0 BLEU
Vaswani et al. (2017, Table 3, cited): at fixed width, one head scored 24.9 BLEU (red), eight and sixteen 25.8 (green), thirty-two 25.4; the axis starts at 24.

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

  • MultiHeadAttention for tinyformer/attention.py: one qkv matrix, split, naive_attention, concatenate, project; checked against nn.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

  1. At width 128, how many weights does attention have with 1 head, and with 8?
  2. Why does concatenating then projecting equal a sum of per-head writes?
  3. The wrong split has the right shape. How does the leak test catch it?
  4. Why can one head not solve the compare task cleanly?
  5. Head 5.5 costs +0.124 alone. Why is it wrong to call it unimportant?
  1. 65,536 both times: heads x d_head is always 128, so the count is 4 x 128 x 128.
  2. Matrix multiplication by blocks: head t's columns of the concatenation meet only rows t of W_o.
  3. Changing the last token moved 3 earlier outputs; a causal layer moves none.
  4. Its one average blends the two tokens, and the blend of 7 and 19 is the same in either order.
  5. 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.

python
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_check trains one head and four heads on copy with seed 11 and asserts both pass 95%. It printed (1.0, 1.0) check passed. Then change TASKS["copy"] to TASKS["reverse"] and predict before rerunning.

Key terms

TermMeaning
Multi-head attentionSeveral attention heads side by side, each on its own slice of the width
Head widthd_head = d_model / h, the size of one head's queries, keys and values
ConcatenationLaying the heads' outputs side by side to rebuild width d_model
Output projectionW_o, which maps the concatenation back; each head writes through its own rows
Causal leak testChange a later token and check that no earlier output moves
AblationSwitching a part off and measuring the damage
Head redundancyOther heads covering for one that is removed
PruningRemoving 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