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 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 and heads of size :
In practice the query projections are one matrix whose output is reshaped into chunks of size , and likewise for keys and values. Parameters: (plus biases) for , independent of .
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 uses the bilinear form of rank at most . So multi-head attention replaces one full-rank similarity by different low-rank ones, each free to focus on a different subspace of the representation. Likewise, each head's contribution to the output is , a rank- map: the output projection is a sum over heads.
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 | 1 | ||
| grouped-query | |||
| multi-query | 1 |
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 and 12 heads of 64.
Exercises
Exercise 1: Head size
A model has and 32 heads. What is , and how many parameters do the four attention projections have?
Answer
; .
Solution
. The projections are four matrices.
Exercise 2: GQA savings
The same model uses 8 KV heads. By what factor do the and parameters and the KV cache shrink?
Answer
By 4.
Solution
and become , a quarter of the size, and the cache stores 8 instead of 32 heads.
Exercise 3: Reshape round trip (code)
Check that splitting a 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
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 heads, the parameter count of the attention projections is…
- , independent of
Why use several heads instead of one?
- To reduce parameters
- Each head can attend according to a different low-rank similarity, capturing different relations
- To avoid the softmax
- Heads are required for causal masking
Grouped-query attention reduces…
- the number of query heads
- the size of the KV cache by sharing key/value heads across query heads
- the vocabulary size
- the sequence length