Module contents
Lesson 5 of 22Core 95 min

Multi-head attention

Implement multi-head attention with split and merged heads, derive the output as a sum of head contributions, and study QK and OV circuits, head redundancy, and ablations.

After this lesson you can

  • Implement multi-head attention with fused projections and reshape to (B, H, T, d_k) without loops.
  • Prove that concatenation followed by W_O sums the projected contributions of each head.
  • Form and interpret the low-rank QK and OV matrices of each head.
  • Count multi-head parameters and FLOPs and compare them with a single head.
  • Evaluate head redundancy experimentally by ablation.

Before you start

Several relationships at once

A position may need information from several positions for different reasons. One attention distribution produces one mixture per head; multiple heads can form different mixtures and write different contributions to the output representation. This does not guarantee that each head has a unique or interpretable function: heads interact with projections, residual streams, and subsequent layers.

InteractiveHead gallery
Rows: queries. Columns: keys. Selected cell: 1 → 1.
1: Hom2: arus3: ␠gam4: mar5: us6: ␠,7: ␠known8: ␠as9: ␠the10: ␠European11: ␠lobster12: ␠or13: ␠common14: ␠lobster15: ␠,16: ␠is
1
1
1
1
Cell weight1.0000
Next-token loss5.3947
Change from ablationno ablation
Choose a fragment, layer, and head of GPT-2 small. The matrix shows actual weights without ablation; enable ablation to see the measured change in next-token loss on that fragment.

The gallery contains outputs exported from pretrained GPT-2 small and two WikiText-2 validation fragments. Attention weights are rounded to five decimal places for display. A visible matrix does not by itself prove a copying circuit or syntactic relationship: these are hypotheses to test through interventions. The loss applies only to the tokens in the displayed fragment; an ablation with a small effect there may matter in other contexts. The results are from our own run, not figures from the paper.

Heads, concatenation, and cost

Multi-head attention projects each input into HH queries, keys, and values. For d=dmodeld=d_{\text{model}}, with dk=dv=d/Hd_k=d_v=d/H,

head⁡h=Attention⁡(XWQ(h),XWK(h),XWV(h)),Y=Concat⁡(head⁡1,…,head⁡H)WO.\operatorname{head}_h=\operatorname{Attention}(XW_Q^{(h)},XW_K^{(h)},XW_V^{(h)}),\qquad Y=\operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_H)W_O.

Each head’s scaled attention uses its own softmax and scale 1/dk1/\sqrt{d_k}. A complete layer may add biases, a mask, and dropout; here biases are omitted for clear counting and derivation. Q, K, and V projections have d2d^2 parameters each and the output another d2d^2, totaling 4d24d^2 independently of HH. Separate biases add 4d4d parameters.

Counting multiplication and addition as two FLOPs, the four projections cost approximately 8Td28Td^2, and scores and mixing 4T2d4T^2d, for one sequence without softmax, mask, or auxiliary operations. Dividing dd among heads preserves these terms compared with a single head of width dd; softmax work grows as HT2HT^2, and actual efficiency depends on hardware. Similar cost does not mean identical function: each head has a different distribution.

Splitting and merging

InteractiveFrom tensor to heads and back
1. Projection: (B,T,3d)
2. Split Q, K and V: (B,T,d)
3. Reshape: (B,T,H,dₖ)
4. Transpose: (B,H,T,dₖ)
5. Attention and merge: (B,T,d)
step 1 of 5
0
0
0
Original indices0, 1
Correct indices0, 1
Step through the shapes. Select an example, position, and head; enable direct reshape to see which values mix when the transpose is omitted.

Splitting and merging heads starts from XX with shape (B,T,d)(B,T,d). A fused projection produces (B,T,3d)(B,T,3d); it is reshaped to (B,T,3,H,dk)(B,T,3,H,d_k) and transposed to obtain Q, K, and V of shape (B,H,T,dk)(B,H,T,d_k). After attention, the inverse transpose gives (B,T,H,dk)(B,T,H,d_k) and reshape merges the last two dimensions into (B,T,d)(B,T,d). The example in the figure uses integers identifying memory positions, not trained activations.

A direct reshape(B,H,T,d_k) on (B,T,d)(B,T,d) preserves the number of elements but interprets linear order differently and mixes tokens and heads. The error can pass a shape test. In PyTorch, a transpose can produce a noncontiguous tensor: view requires a compatible layout; contiguous().view(...) or reshape where appropriate avoids that storage error. Always check what each axis means, not just the number of elements.

If WOW_O is divided by rows into blocks WO(h)∈Rdk×dW_O^{(h)}\in\R^{d_k\times d}, the output projection as a sum of heads follows from block multiplication:

[H1  H2  ⋯  HH][WO(1)WO(2)⋮WO(H)]=∑h=1HHhWO(h).[H_1\;H_2\;\cdots\;H_H] \begin{bmatrix}W_O^{(1)}\\W_O^{(2)}\\\vdots\\W_O^{(H)}\end{bmatrix} =\sum_{h=1}^{H}H_hW_O^{(h)}.

Each product has shape (B,T,d)(B,T,d); their sum reconstructs the output before any bias. This identity is exact algebra and defines each head’s linear contribution before later layers process it.

QK and OV circuits

Without biases and for an input XX, scores for head hh are XWQ(h)WK(h)⊤X⊤/dkXW_Q^{(h)}W_K^{(h)\T}X\T/\sqrt{d_k}. Define WQK(h)=WQ(h)WK(h)⊤W_{QK}^{(h)}=W_Q^{(h)}W_K^{(h)\T}: it determines the bilinear form comparing positions. Also, WOV(h)=WV(h)WO(h)W_{OV}^{(h)}=W_V^{(h)}W_O^{(h)} determines what is written to the output stream for fixed weights. These are the QK and OV circuits in the interpretation of Elhage and colleagues. Each product has rank at most dkd_k, or less if its factors are deficient.

InteractiveA head is a low-rank bilinear form

Diagonal 4 × 4 matrix WQK

1.600001.200000.000000.0

Singular values of the bilinear form

00.511.5σ11.6σ21.2σ30σ40

Weights for the selected query

00.10.20.30.40.5token 10.468token 20.151token 30.049token 40.333
2
1
Rank of WQK2
Change d_k and the query. The diagonal matrix and its singular values are an explicit four-dimensional example; observe the weights induced over four tokens.

In the example, features are (x,y,1,xy)(x,y,1,xy) for four points and the diagonal matrix retains the first dkd_k values of (1.6,1.2,0.8,0.4)(1.6,1.2,0.8,0.4). The fourth direction disappears if dk<4d_k<4, so this family cannot express the full rank-four diagonal matrix. A trained head can choose other subspaces: the limitation is rank, not a requirement to always ignore the fourth coordinate. Softmax is nonlinear and can change the rank of the probability matrix; the preceding limit is on the bilinear form before softmax.

With fixed dd, increasing HH reduces dkd_k and the individual maximum rank while offering more independent distributions. Fewer heads have greater dimension per head but fewer separate mixtures. Rank and head count do not by themselves determine quality, since parameters, data, optimization, and architecture also matter.

Redundancy and ablations

Head redundancy is a claim about a task and intervention, not a guaranteed property. Individual ablation fixes all other parameters and zeros one head output. It measures the loss difference relative to the same input without ablation; that difference can be negative and does not imply that the head is generally useless or that multiple heads can be removed simultaneously without interaction.

Michel, Levy and Neubig observed that many heads of the models and tasks studied could be removed with little impact. Voita et al. reported that, in their English-Russian model, pruning 38 of 48 encoder heads reduced BLEU by 0.15. That published number belongs to their translation setup and pruning method, not this lesson’s GPT-2.

Lab: forward and backward in NumPy

Shapes follow the batch convention; the VJP uses the attention backward equations. The check uses a small case, without dropout, and with a causal mask.

[ ]Fused multi-head attentionBrowser
import numpy as np
def multi_forward(x,w,wo,h):
    b,t,d=x.shape; dh=d//h
    qkv=(x@w).reshape(b,t,3,h,dh).transpose(2,0,3,1,4)
    q,k,v=qkv
    s=q@np.swapaxes(k,-1,-2)/np.sqrt(dh)
    s=np.where(np.tril(np.ones((t,t),bool)),s,-np.inf)
    e=np.exp(s-s.max(axis=-1,keepdims=True)); p=e/e.sum(axis=-1,keepdims=True)
    head=p@v; merged=head.transpose(0,2,1,3).reshape(b,t,d)
    return merged@wo,(x,w,wo,q,k,v,p,merged,h)
def multi_backward(g,cache):
    x,w,wo,q,k,v,p,merged,h=cache; b,t,d=x.shape; dh=d//h
    dwo=merged.reshape(-1,d).T@g.reshape(-1,d)
    dhout=(g@wo.T).reshape(b,t,h,dh).transpose(0,2,1,3)
    dp=dhout@np.swapaxes(v,-1,-2); dv=np.swapaxes(p,-1,-2)@dhout
    ds=p*(dp-(dp*p).sum(axis=-1,keepdims=True))
    dq=ds@k/np.sqrt(dh); dk=np.swapaxes(ds,-1,-2)@q/np.sqrt(dh)
    dz=np.stack([a.transpose(0,2,1,3) for a in (dq,dk,dv)],axis=2).reshape(b,t,3*d)
    return dz@w.T, x.reshape(-1,d).T@dz.reshape(-1,3*d), dwo
[ ]Head sum and gradient checkBrowser
rng=np.random.default_rng(5)
x=rng.normal(size=(1,3,4)); w=rng.normal(size=(4,12)); wo=rng.normal(size=(4,4)); g=rng.normal(size=(1,3,4))
y,cache=multi_forward(x,w,wo,2); grads=multi_backward(g,cache)
head=(cache[6]@cache[5]).transpose(0,2,1,3)
parts=sum(head[:,:,j,:]@wo[j*2:(j+1)*2,:] for j in range(2))
print('error suma:',np.max(np.abs(y-parts)))
for name,a,grad in zip(('X','Wqkv','Wo'),(x,w,wo),grads):
    fd=np.zeros_like(a); eps=1e-5
    for idx in np.ndindex(a.shape):
        old=a[idx];a[idx]=old+eps;plus=np.sum(multi_forward(x,w,wo,2)[0]*g)
        a[idx]=old-eps;minus=np.sum(multi_forward(x,w,wo,2)[0]*g);a[idx]=old
        fd[idx]=(plus-minus)/(2*eps)
    err=np.max(np.abs(fd-grad));print(name,'error máximo:',err);assert err<1e-7

The block sum is checked numerically and central differences check every input and parameter coordinate in this case. Block multiplication explains the identity for all compatible dimensions. The lab uses float64; with very small steps or float32, finite differences can be dominated by rounding.

PyTorch and real ablation

nn.MultiheadAttention accepts batch_first=True for (B,T,d)(B,T,d); its default configuration uses (T,B,d)(T,B,d). In this API a Boolean attn_mask marks forbidden positions with True, whereas in scaled_dot_product_attention, True means allowed. Check the documentation and version, and disable dropout for comparison. In the local lab the fused projection is copied transposed to in_proj_weight, and WOW_O transposed to out_proj.weight, to verify correspondence.

[ ]Equivalence with nn.MultiheadAttentionLocal GPU
import numpy as np, torch
rng=np.random.default_rng(5)
x=rng.normal(size=(1,3,4)); w=rng.normal(size=(4,12)); wo=rng.normal(size=(4,4))
qkv=(x@w).reshape(1,3,3,2,2).transpose(2,0,3,1,4); q,k,v=qkv
scores=q@np.swapaxes(k,-1,-2)/np.sqrt(2)
scores=np.where(np.tril(np.ones((3,3),bool)),scores,-np.inf)
e=np.exp(scores-scores.max(axis=-1,keepdims=True));p=e/e.sum(axis=-1,keepdims=True)
own=(p@v).transpose(0,2,1,3).reshape(1,3,4)@wo
m=torch.nn.MultiheadAttention(4,2,bias=False,batch_first=True,dropout=0).double()
with torch.no_grad():
    m.in_proj_weight.copy_(torch.from_numpy(w.T));m.out_proj.weight.copy_(torch.from_numpy(wo.T))
    xx=torch.from_numpy(x); blocked=torch.ones(3,3,dtype=torch.bool).triu(1)
    result,_=m(xx,xx,xx,attn_mask=blocked,need_weights=False)
    error=np.max(np.abs(result.numpy()-own)); print('error máximo:',error); assert error<1e-10
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell loads GPT-2 small and uses two 16-token fragments from the WikiText-2 validation split, rows 3 and 7 of wikitext-2-raw-v1. IDs are fixed to reproduce the experiment without depending on a local data path. Mean loss is calculated over each fragment’s 15 shifted predictions. The hook zeros 64 channels of c_proj’s input, namely one head’s output before the shared projection, and is removed after each intervention. Repeat all 144 ablations for each fragment. This implementation checks that at least one changes the loss: some versions accept head_mask without applying it in GPT-2.

[ ]Ablation of all 144 GPT-2 headsLocal GPU
import torch
from transformers import AutoModelForCausalLM
assert torch.cuda.is_available(), 'El experimento de referencia usa CUDA'
revision='607a30d783dfa663caf39e06633721c8d4cfcd7e'
model=AutoModelForCausalLM.from_pretrained('openai-community/gpt2',revision=revision,attn_implementation='eager').to('cuda').eval()
examples=[
 [28718,20272,9106,3876,385,837,1900,355,262,3427,43657,393,2219,43657,837,318],
 [28718,20272,9106,3876,385,318,257,1588,20048,558,272,837,351,257,1767,4129],
]
with torch.inference_mode():
    for ids in examples:
        x=torch.tensor([ids],device='cuda')
        base=model(x,labels=x,output_attentions=True,use_cache=False)
        loss=base.loss.item(); print('pérdida base:',loss,'forma de atención:',tuple(base.attentions[0].shape))
        differences=[]
        for layer in range(12):
            for head in range(12):
                def zero_head(module,args):
                    z=args[0].clone();z[...,head*64:(head+1)*64]=0
                    return (z,*args[1:])
                hook=model.transformer.h[layer].attn.c_proj.register_forward_pre_hook(zero_head)
                try: changed=model(x,labels=x,use_cache=False).loss.item()
                finally: hook.remove()
                differences.append((changed-loss,layer+1,head+1))
        assert max(abs(v[0]) for v in differences)>1e-5, 'La intervención no ha tenido efecto'
        print('mayores incrementos:',sorted(differences,reverse=True)[:5])
        print('menor variación:',min(differences))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

This is an individual ablation without parameter readjustment. The figures and patterns exported to the gallery come from the same configuration, with a fixed checkpoint and dropout disabled. They do not prove that a head is dispensable across the entire corpus. To make a pruning decision, extend the evaluation to many documents and seeds and measure joint ablations too.

Exercises

Proof
Prove: Concatenating heads and multiplying by W_O equals summing their projected contributions.
0
Partition W_O into row blocks with each head's width.

Step 1 of 2. How does block multiplication act?

Numeric
For d=768 and H=12, calculate the number of Q, K, V, and W_O parameters without biases.
Numeric
With d=768 and T=1024, calculate FLOPs per token for the four projections and for QK transpose and PV, counting multiplication and addition as two operations and excluding softmax.
Quiz
When doubling H while keeping d fixed and d_k=d/H, what changes?
Code
Implement split_heads(x,h) from (B,T,d) to (B,H,T,d/H), and merge_heads(x) as its inverse. Assume d is divisible by h.
import numpy as np
def split_heads(x,h):
  pass
def merge_heads(x):
  pass
Shift+Enter to run
Key idea
Heads compute different distributions in reduced subspaces; the output projection sums their contributions. Axis partitioning, the rank of QK and OV forms, and causal evaluation of ablations explain both their capabilities and limits.