TExcelTAD
Home › Math for Deep Learning & LLMs › Multi-Head Attention

Multi-Head Attention

A single attention operation produces one weighted average per position, so it can follow only one "kind" of relation at a time. Multi-head attention runs hh smaller attentions in parallel, each with its own projections, and concatenates the results. One head may track the previous token, another the subject of the sentence, another matching brackets. The total cost is about the same as one full-width head.

The computation

With model width dd and hh heads of size dh=d/hd_h = d/h:

headi=Attention⁡(XWQ(i),XWK(i),XWV(i)),WQ(i),WK(i),WV(i)∈Rd×dhMHA⁡(X)=[head1,…,headh] WO,WO∈Rd×d\begin{aligned} \text{head}_i &= \operatorname{Attention}(XW_Q^{(i)}, XW_K^{(i)}, XW_V^{(i)}), \qquad W_Q^{(i)}, W_K^{(i)}, W_V^{(i)} \in \mathbb{R}^{d \times d_h} \\ \operatorname{MHA}(X) &= [\text{head}_1, \ldots, \text{head}_h]\,W_O, \qquad W_O \in \mathbb{R}^{d \times d} \end{aligned}

In practice the hh query projections are one d×dd \times d matrix whose output is reshaped into hh chunks of size dhd_h, and likewise for keys and values. Parameters: 4d24d^2 (plus biases) for WQ,WK,WV,WOW_Q, W_K, W_V, W_O, independent of hh.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
B, n, d, h = 2, 5, 16, 4
dh = d // h
X = rng.normal(size=(B, n, d))
WQ, WK, WV, WO = (rng.normal(0, d**-0.5, (d, d)) for _ in range(4))
def split(T):                                       # (B, n, d) -> (B, h, n, dh)
    return T.reshape(B, n, h, dh).transpose(0, 2, 1, 3)
Q, K, V = split(X @ WQ), split(X @ WK), split(X @ WV)
S = np.einsum("bhqd,bhkd->bhqk", Q, K) / np.sqrt(dh)
A = np.exp(S - S.max(-1, keepdims=True)); A /= A.sum(-1, keepdims=True)
heads = A @ V                                       # (B, h, n, dh)
out = heads.transpose(0, 2, 1, 3).reshape(B, n, d) @ WO
print("Q per head:", Q.shape, " attention weights:", A.shape, " output:", out.shape)
print("parameters:", 4 * d * d, "= 4 d^2, for any number of heads")
Q per head: (2, 4, 5, 4)  attention weights: (2, 4, 5, 5)  output: (2, 5, 16)
parameters: 1024 = 4 d^2, for any number of heads

Heads are low-rank

Each head's score matrix QKT=XWQ(i)WK(i)TXTQK^T = XW_Q^{(i)}W_K^{(i)T}X^T uses the d×dd \times d bilinear form WQ(i)WK(i)TW_Q^{(i)}W_K^{(i)T} of rank at most dhd_h. So multi-head attention replaces one full-rank similarity by hh different low-rank ones, each free to focus on a different subspace of the representation. Likewise, each head's contribution to the output is headiWO(i)\text{head}_i W_O^{(i)}, a rank-dhd_h map: the output projection is a sum over heads.

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
d, h = 16, 4; dh = d // h
WQ, WK = rng.normal(size=(d, d)), rng.normal(size=(d, d))
for i in range(2):
    Wq_i, Wk_i = WQ[:, i * dh:(i + 1) * dh], WK[:, i * dh:(i + 1) * dh]
    print(f"head {i}: rank of W_Q W_K^T = {np.linalg.matrix_rank(Wq_i @ Wk_i.T)} (d_h = {dh})")
print("single full head: rank", np.linalg.matrix_rank(WQ @ WK.T))
head 0: rank of W_Q W_K^T = 4 (d_h = 4)
head 1: rank of W_Q W_K^T = 4 (d_h = 4)
single full head: rank 16

Grouped-query and multi-query attention

During generation, keys and values of past tokens are cached, and with many heads that cache dominates memory (The KV Cache). Multi-query attention (MQA) shares one key/value head among all query heads; grouped-query attention (GQA) shares each key/value head among a group of query heads (e.g. 32 query heads, 8 KV heads). The cache shrinks by the group factor with little quality loss; most recent open LLMs use GQA.

Variant Query heads KV heads KV cache relative size
multi-head hh hh 1
grouped-query hh gg g/hg/h
multi-query hh 1 1/h1/h

In software

  • nn.MultiheadAttention(embed_dim, num_heads, batch_first=True).
  • GQA is implemented by repeating each KV head across its group (repeat_interleave) before the attention kernel, or natively by FlashAttention.
  • Typical head size is 64 or 128: GPT-2 small has d=768d = 768 and 12 heads of 64.

Exercises

Exercise 1: Head size

A model has d=4096d = 4096 and 32 heads. What is dhd_h, and how many parameters do the four attention projections have?

Answer

dh=128d_h = 128; 4⋅40962=67,108,8644 \cdot 4096^2 = 67{,}108{,}864.

Solution

4096/32=1284096/32 = 128. The projections are four 4096×40964096 \times 4096 matrices.

Exercise 2: GQA savings

The same model uses 8 KV heads. By what factor do the WKW_K and WVW_V parameters and the KV cache shrink?

Answer

By 4.

Solution

WKW_K and WVW_V become 4096×(8⋅128)=4096×10244096 \times (8 \cdot 128) = 4096 \times 1024, a quarter of the size, and the cache stores 8 instead of 32 heads.

Exercise 3: Reshape round trip (code)

Check that splitting a (n,d)(n, d) matrix into heads with reshape(n, h, dh).transpose(1, 0, 2) and merging back recovers it exactly.

Answer

The round trip is exact.

Solution
python · try it yourself
import numpy as np
n, d, h = 3, 8, 2
X = np.arange(n * d).reshape(n, d)
heads = X.reshape(n, h, d // h).transpose(1, 0, 2)
print(heads.shape, np.array_equal(heads.transpose(1, 0, 2).reshape(n, d), X))
(2, 3, 4) True

Test yourself

With hh heads, the parameter count of the attention projections is…

  1. 4d2h4d^2h
  2. 4d24d^2, independent of hh
  3. 4dh24d_h^2
  4. h2h^2

Why use several heads instead of one?

  1. To reduce parameters
  2. Each head can attend according to a different low-rank similarity, capturing different relations
  3. To avoid the softmax
  4. Heads are required for causal masking

Grouped-query attention reduces…

  1. the number of query heads
  2. the size of the KV cache by sharing key/value heads across query heads
  3. the vocabulary size
  4. the sequence length