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.
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 queries, keys, and values. For , with ,
Each head’s scaled attention uses its own softmax and scale . 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 parameters each and the output another , totaling independently of . Separate biases add parameters.
Counting multiplication and addition as two FLOPs, the four projections cost approximately , and scores and mixing , for one sequence without softmax, mask, or auxiliary operations. Dividing among heads preserves these terms compared with a single head of width ; softmax work grows as , and actual efficiency depends on hardware. Similar cost does not mean identical function: each head has a different distribution.
Splitting and merging
Splitting and merging heads starts from with shape . A fused projection produces ; it is reshaped to and transposed to obtain Q, K, and V of shape . After attention, the inverse transpose gives and reshape merges the last two dimensions into . The example in the figure uses integers identifying memory positions, not trained activations.
A direct reshape(B,H,T,d_k) on 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 is divided by rows into blocks , the output projection as a sum of heads follows from block multiplication:
Each product has shape ; 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 , scores for head are . Define : it determines the bilinear form comparing positions. Also, 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 , or less if its factors are deficient.
In the example, features are for four points and the diagonal matrix retains the first values of . The fourth direction disappears if , 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 , increasing reduces 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.
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
[email protected](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)[email protected](-1,d)
dhout=([email protected]).reshape(b,t,h,dh).transpose(0,2,1,3)
[email protected](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 [email protected], x.reshape(-1,d)[email protected](-1,3*d), dworng=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-7The 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 ; its default configuration uses . 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 transposed to out_proj.weight, to verify correspondence.
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
[email protected](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-10npm 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.
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))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
Step 1 of 2. How does block multiplication act?
import numpy as np
def split_heads(x,h):
pass
def merge_heads(x):
pass