All courses

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

▶ Watch this lesson Start the whole course

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.

One softmax row, two things to find

In single-head attention, each position gets one softmax row. Its weights sum to 1, so it produces one weighted average of value vectors. Suppose a word needs two things at once: the noun it refers to, and the word just before it. One row must split its weight between them, and the result blends both into a single vector. How can a position gather several different things at once, for about the same cost?

Several small attentions side by side

Run several narrow attentions in parallel. Each **head** has its own $W_Q, W_K, W_V$. That gives it its own idea of which positions match, and its own $T\times T$ pattern. Each head has a separate softmax, so heads don't compete for weight: one can lock onto the noun while another locks onto the previous word. Each head returns a $d_{head}$-vector. We place these side by side and let $W_O$ mix them back to width $d$.

The multi-head formula

For head $i=1..h$: $Q_i=XW_Q^{(i)}$, and likewise $K_i, V_i$ (each $T\times d_{head}$). $$O_i=\text{softmax}(Q_iK_i^\top/\sqrt{d_{head}}+M)\,V_i$$ Every head uses the same causal mask $M$. $\text{MHA}(X)=[O_1,\dots,O_h]\,W_O$. The concatenation is $T\times h\,d_{head}$, and $W_O\in\mathbb{R}^{(h\cdot d_{head})\times d}$. Cutting $W_O$ into row blocks $W_O^{(i)}$ gives $\sum_i O_iW_O^{(i)}$: each head adds its own contribution. With $d_{head}=d/h$, the weight count is $4d^2$ for any $h$.

Two heads, two different targets

Take $h=2$, $d_{head}=2$, $T=2$, and query position 2. **Head 1:** scaled scores $(\ln3,0)$ give weights $(0.75,0.25)$. Its value rows are $(4,0),(0,4)$, so $O_1=0.75(4,0)+0.25(0,4)=(3,1)$. **Head 2:** scores $(0,\ln3)$ give $(0.25,0.75)$. Its rows are $(0,8),(4,0)$, so $O_2=(3,2)$. Concatenate to $(3,1,3,2)$, then multiply by $W_O$ ($4\times4$) to get width $d=4$. A single row could not put 0.75 on both positions.

All heads in one matmul plus a reshape

In practice all heads share one matmul: $XW_Q$ with $W_Q\in\mathbb{R}^{d\times d}$, where column block $i$ is head $i$'s projection. Reshape $[B,T,d]\to[B,T,h,d_{head}]$, then transpose to $[B,h,T,d_{head}]$. Now $h$ behaves like a batch axis, and einsum computes every head's pattern at once. One $T\times T$ causal mask broadcasts over all $B$ and $h$.
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

Multi-head attention runs $h$ independent attentions of width $d_{head}=d/h$. Each has its own pattern and a separate softmax, so one position can pull different information from different places at once. Concatenate the $h$ outputs back to width $d$ and multiply by $W_O$ to mix them. The weight count is the same as one full-width head, and the compute is about the same.

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.