Multi-head attention
Split attention into h heads of size d_head by reshaping [B, T, d] → [B, h, T, d_head], each head with its own attention pattern. Concatenate the head outputs and project with W_O, and explain why several heads can attend to different things at once.
Builds on: Scaled dot-product attention, Batched tensors, broadcasting and einsum
What the animation says
One row, two targets
In single-head attention, each position gets one softmax row of weights. They sum to one, so the row makes one weighted average of value vectors. Take the word 'it'. It needs two things: the noun it refers to, 'cat', and the word just before it, 'because'. Ideally, it would put three quarters of its weight on each. What does one softmax row actually give you?
Several heads, side by side
Right: one row has one unit of weight to share, so both targets blur into one vector. The fix: run several narrow attentions side by side. Each one is a head. Each head has its own query, key and value matrices, so its own idea of what matches. And each head has its own softmax, so heads don't compete for weight. One head locks onto the noun, another onto the previous word. Their small outputs go side by side, and an output matrix mixes them back to full width.
Two heads, real numbers
Let's put numbers on it: two heads, each two wide, two tokens, looking from position two. Head one's scores favour token one. After softmax: three quarters and one quarter. Its value rows are four-zero and zero-four, so it outputs three, one. Head two favours token two: one quarter and three quarters. Its value rows are zero-eight and four-zero. What does head two output?
Concatenate, then mix
Head two outputs three, two. Each head put three quarters on a different token. One softmax row could never do that. Concatenate: three, one, three, two. Four numbers, full width again. An output matrix, four by four, mixes the heads together. Cut it into row blocks, and each head just adds its own contribution. With head width d over h, the weights stay four d squared, for any number of heads.
All heads in one matmul
In practice, all heads share one matmul. Each block of columns belongs to one head. These next two lines split the width into h heads of size d head, and reorder the axes. Now heads sit right beside the batch, so they behave like extra sequences. The einsum scores every head at once. The patterns have shape batch, heads, T, T. One T by T causal mask broadcasts over every sequence and every head. Which line puts the heads beside the batch axis? Tap it.
Several small attentions side by side
The multi-head formula
Two heads, two different targets
All heads in one matmul plus a reshape
import numpy as np
B,T,d,h=2,5,8,2; dh=d//h
X=np.random.randn(B,T,d)
WQ,WK,WV,WO=(np.random.randn(d,d)/np.sqrt(d) for _ in range(4))
split=lambda Y: Y.reshape(B,T,h,dh).transpose(0,2,1,3) # [B,h,T,dh]
Q,K,V=split(X@WQ),split(X@WK),split(X@WV)
S=np.einsum('bhqd,bhkd->bhqk',Q,K)/np.sqrt(dh) # [B,h,T,T]
S=S+np.triu(np.full((T,T),-np.inf),1) # causal mask M
A=np.exp(S-S.max(-1,keepdims=True)); A/=A.sum(-1,keepdims=True)
O=np.einsum('bhqk,bhkd->bhqd',A,V) # [B,h,T,dh]
out=O.transpose(0,2,1,3).reshape(B,T,d)@WO # [B,T,d]
print(A.shape,out.shape)
What to remember
On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.
Bytewise
All courses