Skip to content
Transformers and LLMs Core 21 min read

Multi-head attention

One attention head gives each position one weighted average — one question, one answer. Multi-head attention splits the model's width into $h$ smaller heads that ask $h$ different questions at once, for exactly the same parameter count. It is also where the most famous circuits in interpretability live.

10,000 ft

Single-head attention lets a position gather information from the rest of the sequence, but only through one softmax distribution. Language needs many relations at once — the subject of this verb, the previous token, the antecedent of "it", the matching bracket. Multi-head attention (MHA) runs several attentions in parallel in separate low-dimensional subspaces and adds their results back together. It is used in every transformer layer; its heads are the units that mechanistic interpretability dissects (previous-token heads, induction heads); and the way heads share keys and values — multi-query, grouped-query and latent attention — is the main lever on inference memory, covered fully in KV cache and efficient attention.

2,000 ft

Take model width \(d\) and \(h\) heads, each of width \(d_h = d/h\).

  1. Project \(X\) to \(Q, K, V\) with full \(d \times d\) matrices, exactly as for one head.
  2. Split the last dimension into \(h\) blocks of \(d_h\): each head gets its own slice of the queries, keys and values.
  3. Attend independently in every head: \(h\) separate \(n \times n\) weight matrices.
  4. Concatenate the \(h\) outputs back to width \(d\).
  5. Mix with an output projection \(W_O\) (\(d \times d\)), which is the same as each head adding its own contribution into the output.

Multi-head attention: split, attend in parallel, concatenate, project
Multi-head attention: split, attend in parallel, concatenate, project. X (n × d), Q, K, V full projections, head 1 softmax(q₁k₁ᵀ/√d_h)·v₁, head 2, head h, concat (n × d), W_O (d × d), output (n × d), slice 1, slice 2, slice hMulti-head attention: split, attend in parallel, concatenate, project. X (n × d), Q, K, V full projections, head 1 softmax(q₁k₁ᵀ/√d_h)·v₁, head 2, head h, concat (n × d), W_O (d × d), output (n × d), slice 1, slice 2, slice h

Ground level

One head, one average

Look at what a single head computes for position \(i\): \(\mathbf{o}_i = \sum_j a_{ij}\mathbf{v}_j\), with one set of weights \(a_{i\cdot}\). Suppose the token at \(i\) is the verb "chased" in "the dog that the cat saw chased the ball", and the model wants both its subject ("dog", far back) and its object ("ball", ahead in an encoder, or the pattern so far in a decoder). One softmax can split its mass between them, but then the output is a blend — half dog, half ball — and nothing downstream can tell which part came from where. The transformer paper names the problem directly: multi-head attention "allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this" (§3.2.2).

With two heads, one can put its weight on "dog" and write into one subspace, the other on "ball" into another. The two facts arrive separately.

Splitting the width

MHA does not add heads on top of a full-width attention; it divides the width. A model with \(d = 768\) and 12 heads gives each head \(d_h = 64\) dimensions. Real configurations:

Model \(d\) heads \(h\) \(d_h\) key/value heads
Original transformer, base (2017) 512 8 64 8
GPT-2 small (124M) 768 12 64 12
GPT-3 175B (Table 2.1) 12,288 96 128 96
Llama 3 8B (Table 3) 4,096 32 128 8
Llama 3 70B 8,192 64 128 8
Llama 3 405B 16,384 128 128 8

Two patterns stand out. Head width settles at 64–128 regardless of model size: bigger models get more heads, not wider ones. And the newest models have fewer key/value heads than query heads — grouped-query attention, explained below.

The same cost as one head

Because the projections are still \(d \times d\), the parameter count is \(4d^2\) (for \(W_Q, W_K, W_V, W_O\)) whatever \(h\) is. The FLOPs are the same too: computing \(h\) score matrices of \(n \times n\) at width \(d_h\) costs \(h \cdot 2n^2 d_h = 2n^2 d\), identical to one head at width \(d\). What changes is memory for the attention weights — \(h\) matrices of \(n \times n\) instead of one — and what can be expressed. You get \(h\) independent distributions per position for free.

Concatenate-then-project is a sum of independent writes

The textbook form is \(\operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)\,W_O\). Split \(W_O\) into \(h\) horizontal blocks \(W_O^{(1)},\dots,W_O^{(h)}\), each \(d_h \times d\). Multiplying a concatenated row vector by a block-stacked matrix is the sum of block products, so

\[ \operatorname{MHA}(X) = \sum_{i=1}^{h} \text{head}_i\, W_O^{(i)} = \sum_{i=1}^{h} A^{(i)}\, X\, W_V^{(i)} W_O^{(i)} . \]

Each head reads from the input, chooses where to look with its own weights \(A^{(i)}\), and writes its own contribution into the output; the contributions add. This is the view Anthropic's interpretability team made standard (A Mathematical Framework for Transformer Circuits, 2021). It splits every head into two circuits:

  • QK circuit \(W_Q^{(i)}W_K^{(i)\top}\) (\(d \times d\)): decides where to look. The score between token vectors \(\mathbf{x}\) and \(\mathbf{y}\) is \(\mathbf{x}^\top W_Q^{(i)}W_K^{(i)\top}\mathbf{y}/\sqrt{d_h}\).
  • OV circuit \(W_V^{(i)}W_O^{(i)}\) (\(d \times d\)): decides what gets written when a position is attended to.

Both are \(d \times d\) matrices of rank at most \(d_h\). A head is a low-rank read, a low-rank write, and a softmax routing pattern between them.

One head = a QK circuit (where to look) + an OV circuit (what to write)
One head = a QK circuit (where to look) + an OV circuit (what to write). token j (residual stream), token i (residual stream), QK circuit xᵢᵀ W_Q W_Kᵀ xⱼ → weight aᵢⱼ, OV circuit xⱼ W_V W_O (rank ≤ d_h), add aᵢⱼ · (xⱼ W_V W_O) into token i, query, key, value, how much, what, residual +=One head = a QK circuit (where to look) + an OV circuit (what to write). token j (residual stream), token i (residual stream), QK circuit xᵢᵀ W_Q W_Kᵀ xⱼ → weight aᵢⱼ, OV circuit xⱼ W_V W_O (rank ≤ d_h), add aᵢⱼ · (xⱼ W_V W_O) into token i, query, key, value, how much, what, residual +=

What heads learn

Trained heads specialise, and some specialisations recur across models and seeds:

  • Previous-token heads attend almost entirely to position \(i-1\). Useless alone; essential as a building block.
  • Induction heads implement "find the previous occurrence of my current token, and copy the token that came after it": in … Harry Potter … Harry, predict Potter. They need two heads in different layers — a previous-token head first, then a head whose key reads what the previous-token head wrote. Olsson et al. found that induction heads form during a sudden phase change early in training, coinciding with a jump in in-context learning, and presented evidence "that induction heads might constitute the mechanism for the actual majority of all in-context learning in large transformer models" (In-context Learning and Induction Heads, 2022).
  • Positional and syntactic heads. Voita et al. found translation-model heads with consistent, interpretable roles — attending to adjacent positions, following specific syntactic relations, or attending to rare tokens (arXiv:1905.09418).

And many heads are redundant. Michel, Levy and Neubig found that "a large percentage of attention heads can be removed at test time without significantly impacting performance", some layers down to one head (Are Sixteen Heads Really Better than One?); Voita et al. pruned 38 of 48 encoder heads for a drop of only 0.15 BLEU on English–Russian. Multiple heads seem to matter most during training — more parallel hypotheses for gradient descent to explore — than in the finished model.

Worked example: an induction head, built by hand

You can wire up the two-head induction circuit with hand-set weights and watch it predict. The sequence is ^ A B C A (^ marks the start of text). The residual stream for each position has three slots: its token (one-hot), its position (one-hot), and an empty "previous token" slot.

  • Layer 1, previous-token head. Query of position \(i\) = "position \(i-1\)"; key of position \(j\) = "I am position \(j\)". So position \(i\) attends to \(i-1\), and its value — the token there — is written into the previous-token slot. The residual connection adds this to the stream; nothing is overwritten.
  • Layer 2, induction head. Query = "my current token"; key = "the token that came before me" (read from the slot layer 1 filled). The last position holds A; the only earlier position whose previous token was A is position 2, holding B. Its value — its own token — is copied out.

Real output of the code in Build it:

layer-1 (previous-token head) weights:
 [[1. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]]
layer-2 (induction head) weights, last row: [0. 0. 1. 0. 0.]
prediction after '^ABCA' -> B

The layer-1 matrix is a shifted identity (position 0 has nothing before it and attends to itself). The layer-2 head puts all its weight on position 2 and predicts B. This is composition: a head's key reads something another head wrote. It cannot happen in a one-layer model, which is why Olsson et al. saw the phase change only in models with at least two layers. Note the role of the start token: without it, position 0 would copy its own token into its previous-token slot and the induction head would split its attention between two matches. Real models have the same need for a harmless place to put attention.

Sharing keys and values: MQA, GQA, MLA

At inference time a decoder stores every past token's keys and values (the KV cache) so it doesn't recompute them; see KV cache and efficient attention. Its size per token is

\[ \text{KV bytes per token} = 2 \times n_\text{layers} \times h_{kv} \times d_h \times \text{bytes per number}, \]

where \(h_{kv}\) is the number of key/value heads. For Llama 3 70B (80 layers, \(d_h = 128\), 16-bit numbers):

  • full MHA, \(h_{kv} = 64\): \(2 \times 80 \times 64 \times 128 \times 2 = 2{,}621{,}440\) bytes = 2.5 MiB per token, or 320 GiB for a 128K-token context;
  • with its actual \(h_{kv} = 8\): 320 KiB per token, 40 GiB at 128K.

Reading that cache from memory at every generated token is what limits decoding speed, so the field shrank it:

  • Multi-query attention (MQA): all query heads share one key head and one value head (Shazeer, arXiv:1911.02150). Smallest cache, some quality loss.
  • Grouped-query attention (GQA): query heads are split into \(h_{kv}\) groups that each share a key/value head — "an interpolation between multi-head and multi-query attention", which "achieves quality close to multi-head attention with comparable speed to MQA" (Ainslie et al., arXiv:2305.13245). Llama 3 uses 8 key/value heads at every size.
  • Multi-head latent attention (MLA): cache a single low-rank latent vector per token and reconstruct per-head keys and values from it. DeepSeek-V2 reports it "reduces the KV cache by 93.3%" relative to DeepSeek 67B (arXiv:2405.04434).
Key/value sharing across 8 query heads
Key/value sharing across 8 query heads. MHA: 8 query heads, 8 KV heads (cache ×8), GQA: 8 query heads, 2 KV heads (cache ×2), MQA: 8 query heads, 1 KV head (cache ×1), MLA: KV rebuilt from a small per-token latent (cache ≪ ×1 MHA head set), group query heads, one group, compress instead of shareKey/value sharing across 8 query heads. MHA: 8 query heads, 8 KV heads (cache ×8), GQA: 8 query heads, 2 KV heads (cache ×2), MQA: 8 query heads, 1 KV head (cache ×1), MLA: KV rebuilt from a small per-token latent (cache ≪ ×1 MHA head set), group query heads, one group, compress instead of share

History

Heads, from translation to circuits

2017 — Vaswani et al. introduce multi-head attention with \(h = 8\) heads of \(d_h = 64\), and in Table 3 show a sweet spot: on English–German development BLEU, 8 or 16 heads score 25.8, one head 24.9 and 32 heads (at \(d_h = 16\)) 25.4 (arXiv:1706.03762). 2019 — analysis papers show heads specialise and are largely prunable (Voita et al.; Michel et al.); Shazeer proposes multi-query attention for faster decoding. 2020 — Bhojanapalli et al. identify the low-rank bottleneck of small heads (arXiv:2002.07028). 2021–2022 — Anthropic's circuits work recasts heads as QK and OV circuits and identifies induction heads. 2023 — GQA becomes the default in open models (Llama 2 70B, Mistral 7B, Llama 3). 2024 — DeepSeek-V2 introduces multi-head latent attention.

First principles

Why many low-rank heads instead of one full-rank head? One head at width \(d\) gives each position a single distribution over positions and a single full-rank read/write. \(h\) heads at width \(d/h\) give \(h\) distributions, each with a rank-\(d/h\) read/write. Which is better depends on what the data needs. Language has many simultaneous, mostly simple relations (copy the previous token, find the subject, match the bracket) — each needs its own routing pattern but only a few dimensions of content. So many cheap heads beat one rich one, and the original paper's ablation confirms a sweet spot at fixed \(d = 512\) (8–16 heads beat both 1 and 32).

What breaks if heads are too narrow? A head's score matrix is \(Q_h K_h^\top\) with \(Q_h, K_h \in \mathbb{R}^{n \times d_h}\), so its rank is at most \(d_h\). For \(n > d_h\), a head cannot represent an arbitrary \(n \times n\) pattern of scores — it can only express patterns that factor through \(d_h\) dimensions. Bhojanapalli et al. argue this low-rank bottleneck is why models need large total width, and propose setting \(d_h\) independently of \(h\) (arXiv:2002.07028). In practice the community settled on \(d_h \in \{64, 128\}\) and adds heads as models widen.

Why sum rather than concatenate? They are the same thing (derived below). But thinking of each head as adding into a shared vector — the residual stream — is the key to reading transformers. It means heads in later layers can read what earlier heads wrote (composition), and a head can be studied by asking what it adds.

Why share keys and values but not queries? During generation, queries exist only for the new token, while keys and values must be kept for every past token. Sharing keys and values shrinks the thing that grows with context; queries cost nothing to keep diverse.

The maths

Definition. For input \(X \in \mathbb{R}^{n \times d}\), heads \(i = 1..h\) with \(d_h = d/h\) and parameters \(W_Q^{(i)}, W_K^{(i)}, W_V^{(i)} \in \mathbb{R}^{d \times d_h}\), \(W_O^{(i)} \in \mathbb{R}^{d_h \times d}\):

\[ \text{head}_i = \operatorname{softmax}\!\left(\frac{XW_Q^{(i)}\,(XW_K^{(i)})^\top}{\sqrt{d_h}} + M\right) XW_V^{(i)} \;\in \mathbb{R}^{n \times d_h}, \]
\[ \operatorname{MHA}(X) = \operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)\,W_O,\qquad W_O = \begin{bmatrix} W_O^{(1)} \\ \vdots \\ W_O^{(h)}\end{bmatrix} \in \mathbb{R}^{d \times d}. \]

In code the per-head matrices are the column blocks of one \(d \times d\) matrix: \(W_Q = [W_Q^{(1)} \,\cdots\, W_Q^{(h)}]\), which is why a single matmul followed by a reshape computes all heads.

Derivation: concatenation then projection equals a sum over heads

Let \(H = [H_1 \; H_2 \; \cdots \; H_h] \in \mathbb{R}^{n \times d}\) with \(H_i \in \mathbb{R}^{n \times d_h}\), and \(W_O\) stacked from row blocks \(W_O^{(i)} \in \mathbb{R}^{d_h \times d}\). Entry \((r, c)\) of \(HW_O\) is

\[ (HW_O)_{rc} = \sum_{m=1}^{d} H_{rm}(W_O)_{mc} = \sum_{i=1}^{h}\;\sum_{m \in \text{block } i} H_{rm}(W_O)_{mc} = \sum_{i=1}^{h} \big(H_iW_O^{(i)}\big)_{rc}. \]

So \(HW_O = \sum_i H_iW_O^{(i)}\). Substituting \(H_i = A^{(i)}XW_V^{(i)}\) gives \(\operatorname{MHA}(X) = \sum_i A^{(i)}X\,\big(W_V^{(i)}W_O^{(i)}\big)\): each head's attention pattern \(A^{(i)}\) times the input, times that head's OV matrix.

Rank of the circuits. \(W_Q^{(i)}W_K^{(i)\top}\) and \(W_V^{(i)}W_O^{(i)}\) are products through a \(d_h\)-dimensional space, so \(\operatorname{rank} \le d_h\). A score matrix \(S^{(i)} = XW_Q^{(i)}W_K^{(i)\top}X^\top\) likewise has rank \(\le d_h\).

Shapes in a batch. \(X: (B, n, d) \to XW_Q: (B, n, d) \to\) reshape \((B, n, h, d_h) \to\) transpose \((B, h, n, d_h)\). Scores: \((B, h, n, d_h) \times (B, h, d_h, n) \to (B, h, n, n)\). Output: \((B, h, n, n) \times (B, h, n, d_h) \to (B, h, n, d_h) \to\) transpose and reshape to \((B, n, d) \to \times W_O\).

Cost. Parameters: \(4d^2\) (plus \(4d\) biases if used), independent of \(h\). FLOPs per sequence: projections \(4 \cdot 2nd^2\); scores and weighted sum \(2 \cdot 2n^2d\). Attention-weight memory: \(h\,n^2\) per sequence (if materialised).

Grouped-query attention. With \(h\) query heads and \(h_{kv}\) key/value heads (\(h_{kv}\) divides \(h\)), query head \(i\) uses key/value head \(g(i) = \lfloor i \, h_{kv}/h \rfloor\) (0-indexed):

\[ \text{head}_i = \operatorname{softmax}\!\left(\frac{XW_Q^{(i)}\,(XW_K^{(g(i))})^\top}{\sqrt{d_h}} + M\right)XW_V^{(g(i))}. \]

\(h_{kv} = h\) is MHA; \(h_{kv} = 1\) is MQA. The key and value projections shrink to \(d \times h_{kv}d_h\), so attention parameters become \(2d^2 + 2d\,h_{kv}d_h\), and the KV cache shrinks by the factor \(h/h_{kv}\).

Build it

Multi-head attention in NumPy with the reshape trick, checked against an explicit per-head loop that uses the sum of writes form:

import numpy as np
rng = np.random.default_rng(0)

def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)

def mha(X, W_Q, W_K, W_V, W_O, h):
    """X: (B, T, d). W_*: (d, d). Returns (B, T, d) and weights (B, h, T, T)."""
    B, T, d = X.shape; dh = d // h
    def split(Y):                                  # (B, T, d) -> (B, h, T, dh)
        return Y.reshape(B, T, h, dh).transpose(0, 2, 1, 3)
    Q, K, V = split(X @ W_Q), split(X @ W_K), split(X @ W_V)
    S = Q @ K.transpose(0, 1, 3, 2) / np.sqrt(dh)  # (B, h, T, T): every head at once
    S = np.where(np.tril(np.ones((T, T), bool)), S, -np.inf)
    A = softmax(S)
    O = (A @ V).transpose(0, 2, 1, 3).reshape(B, T, d)   # concatenate heads
    return O @ W_O, A

B, T, d, h = 2, 6, 16, 4
X = rng.standard_normal((B, T, d))
W_Q, W_K, W_V, W_O = (rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(4))
Y, A = mha(X, W_Q, W_K, W_V, W_O, h)
print("output", Y.shape, "| weights", A.shape)

# 1) Same thing with an explicit loop over heads, each using its own column block
dh = d // h
Y_loop = np.zeros_like(Y)
for i in range(h):
    cols = slice(i * dh, (i + 1) * dh)
    q, k, v = X @ W_Q[:, cols], X @ W_K[:, cols], X @ W_V[:, cols]
    S = q @ k.transpose(0, 2, 1) / np.sqrt(dh)
    S = np.where(np.tril(np.ones((T, T), bool)), S, -np.inf)
    # 2) concat-then-project == sum over heads of (head output) @ (its rows of W_O)
    Y_loop += softmax(S) @ v @ W_O[cols, :]
print("reshape version == per-head loop == sum of per-head writes:", np.allclose(Y, Y_loop))

# 3) Parameter count does not depend on h
print("params:", sum(W.size for W in (W_Q, W_K, W_V, W_O)), "= 4 d^2 =", 4 * d * d)
output (2, 6, 16) | weights (2, 4, 6, 6)
reshape version == per-head loop == sum of per-head writes: True
params: 1024 = 4 d^2 = 1024

The hand-built induction circuit from the worked example:

import numpy as np
np.set_printoptions(precision=2, suppress=True)

def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)

def head(X, W_Q, W_K, W_V):
    n = len(X)
    S = (X @ W_Q) @ (X @ W_K).T                       # (we skip 1/sqrt(d): weights are hand-set)
    S = np.where(np.tril(np.ones((n, n), bool)), S, -np.inf)
    A = softmax(S)
    return A @ (X @ W_V), A

vocab = "^ABC"; seq = "^ABCA"                         # ^ marks the beginning of the text
n, V = len(seq), len(vocab)
TOK, PREV = slice(0, V), slice(V + n, 2 * V + n)       # residual-stream "slots": token | position | prev
d = 2 * V + n
X = np.zeros((n, d))
for i, ch in enumerate(seq):
    X[i, vocab.index(ch)] = 1                          # token one-hot
    X[i, V + i] = 1                                    # position one-hot

# Layer 1, a previous-token head: position i looks for position i-1 and copies its token into PREV
W_Q1 = np.zeros((d, n)); W_K1 = np.zeros((d, n)); W_V1 = np.zeros((d, d))
for i in range(1, n):
    W_Q1[V + i, i - 1] = 10                            # query of position i = "position i-1"
for j in range(n):
    W_K1[V + j, j] = 1                                 # key of position j = "I am position j"
W_V1[TOK, PREV] = np.eye(V)                            # value = my token, written to the PREV slot
out1, A1 = head(X, W_Q1, W_K1, W_V1)
X1 = X + out1                                          # residual: add, don't overwrite

# Layer 2, an induction head: "find where my token appeared *before*, copy what followed it"
W_Q2 = np.zeros((d, V)); W_K2 = np.zeros((d, V)); W_V2 = np.zeros((d, V))
W_Q2[TOK, :] = 10 * np.eye(V)                          # query = my current token
W_K2[PREV, :] = np.eye(V)                              # key = the token that preceded me
W_V2[TOK, :] = np.eye(V)                               # value = my own token
out2, A2 = head(X1, W_Q2, W_K2, W_V2)

print("layer-1 (previous-token head) weights:\n", A1)
print("layer-2 (induction head) weights, last row:", A2[-1])
print("prediction after", repr(seq), "->", vocab[int(out2[-1].argmax())])

Output is shown in the worked example.

In PyTorch, torch.nn.MultiheadAttention(embed_dim=d, num_heads=h, batch_first=True) packages the same computation; most LLM codebases instead write the reshape by hand around F.scaled_dot_product_attention, which takes tensors shaped (B, h, T, d_h).

Things to try

  • Change seq to "^ABCDBCA". Does the induction head still predict the right token? What if A appears twice earlier, followed by different tokens?
  • Remove the residual connection (X1 = out1) and rerun. Why does the induction head break? (Hint: what is in the token slot now?)
  • Implement GQA in mha: take W_K, W_V of shape (d, h_kv * dh) and repeat each key/value head h // h_kv times before the score computation. Check h_kv = h reproduces MHA.
  • For random X with T = 64 and d_h = 4, compute np.linalg.matrix_rank of one head's score matrix. Then try d_h = 16.

In practice

  • Head width 64 or 128 is near-universal; GPU attention kernels are tuned for these sizes.
  • GQA with 8 KV heads is the open-model default as of 2026; MLA appears in DeepSeek's models and their derivatives. If you are choosing an architecture for long-context serving, the KV-cache formula above is the first calculation to do.
  • Converting an MHA checkpoint to GQA works by mean-pooling key/value heads within each group and briefly continuing training — the GQA paper's "uptraining" uses about 5% of the original pre-training compute.
  • Pruning heads after training is cheap and often nearly free in quality for encoder models; it is rarer in LLMs, where serving cost is dominated by the KV cache and the MLP.

Check yourself

With d = 4096 and 32 heads, what is d_h, and how many parameters do W_Q, W_K, W_V, W_O hold together (no biases)?

\(d_h = 4096/32 = 128\). Parameters: \(4d^2 = 4 \times 4096^2 = 67{,}108{,}864\) — the same as with 1 head or 64 heads.

Why can't one head attend sharply to two different positions for two different purposes?

It has one softmax distribution per query and one value projection, so its output is a single convex combination of values. Putting weight on two positions blends their values into one vector; nothing records which component came from which position or for what purpose.

Show that Concat(heads)·W_O equals a sum over heads.

Split \(W_O\) into row blocks \(W_O^{(i)}\) matching the head blocks of the concatenation. Block matrix multiplication gives \([H_1\cdots H_h]\,[W_O^{(1)};\dots;W_O^{(h)}] = \sum_i H_iW_O^{(i)}\).

Llama 3 8B has 32 layers, 8 KV heads and d_h = 128. How large is its KV cache per token in 16-bit, and for an 8,192-token context?

\(2 \times 32 \times 8 \times 128 \times 2 = 131{,}072\) bytes = 128 KiB per token. For 8,192 tokens: \(8192 \times 128\) KiB \(= 1\) GiB per sequence.

Why does an induction head need two layers?

It needs a key that encodes "the token before me", which is not in any single token's embedding. A previous-token head in an earlier layer must first copy that information into the residual stream; only then can a later head's key read it. A head cannot use what a head in the same layer writes.

Hard: what is the maximum rank of a head's n × n score matrix, and why does it matter for long sequences?

\(\operatorname{rank}(Q_hK_h^\top) \le d_h\). With \(n = 8192\) and \(d_h = 128\), each head can only express score patterns that factor through 128 dimensions — it cannot implement an arbitrary \(n \times n\) attention pattern. Positional schemes such as RoPE and ALiBi, and the use of many heads, are partly ways to express rich patterns despite this.

Hard: GQA shares K and V across query heads. Why not share Q instead?

The KV cache grows with the number of past tokens and must be read at every generation step; queries exist only for the current token and are never cached. Sharing K/V shrinks the memory-bound part of decoding; sharing Q would save almost nothing and lose expressivity.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Code

  • karpathy/nanoGPT — CausalSelfAttention: one c_attn matmul, a view/transpose into heads, and scaled_dot_product_attention.
  • meta-llama/llama3 — Reference GQA implementation (repeat_kv).

Where this leads