Multi-head attention (MHA) extends attention by learning several contexts in parallel. Each head can focus on a different pattern, then the model mixes their answers into one output. section 12.5.1
Represent the mechanism as queries over paired keys and values:
- Use key and value tensors K and V with shape (T, D), where each key has a corresponding value. section 12.5.1
- Use a query tensor Q with its own length T′; each query receives one D-dimensional response. section 12.5.1
- Apply softmax and learned nn.Linear layers so each head selectively focuses on parts of the input. section 12.5.1
- Concatenate the head outputs and project them through a final linear layer; increasing the head count does not increase output width. section 12.5.1
A PyTorch implementation pattern
Create one query, key, and value projection per head, compute Attention(wq(Q), wk(K), wv(V)) for every head, concatenate the results, and apply wo to return D features. A useful intuition is the contrast with a Python dictionary: MHA lets every key contribute according to similarity instead of requiring an exact match. section 12.5.1
Figure 12.5 Outline of the multiheaded attention block. There are three sequences as inputs: the queries Q and the keys and values K, V, which are paired together. The MHA returns a D-dimensional vector that answers each query qi ∈ Q.
Shows Q, K, and V as three input sequences and the D-dimensional response returned for each query. section 12.5.1













