All courses

Multi-query and grouped-query attention

Share key/value heads across groups of query heads (h_kv < h). Compute the KV-cache reduction and explain why the quality cost is small.

Builds on: The KV cache

▶ Watch this lesson Start the whole course

What the animation says

The KV cache is huge

Every token a model processes leaves a key and a value behind, in every layer and every head. That stash is the KV cache. Per token, multiply: two, for keys and values, times thirty-two layers, times thirty-two heads, times one hundred twenty-eight numbers per head, times two bytes. That's five hundred twelve kibibytes for a single token. After eight thousand tokens, one sequence holds four gibibytes. Every new token reads all of it. To shrink it, what could heads share while each still gets its own attention pattern?

Share keys and values

Right: keys and values. Here are eight query heads, each with its own query weights. Now just two key-value heads. Each one serves a group of four query heads. Every query head still asks its own question, so it still gets its own attention pattern. Only what each past token offers, its key and its value, is shared. Tap the key-value head that query head five reads from.

GQA, MQA, and the cache formula

Choose how many key-value heads to keep. Each one serves the total heads divided by that number. Keep all thirty-two, and it's ordinary multi-head attention. Keep eight: grouped-query attention. Keep just one: multi-query attention. Query head i uses group i, times key-value heads, divided by total heads, rounded down. Only the shared keys and values are cached. So in the cache formula, the head count becomes the key-value head count. For our thirty-two-layer model with eight key-value heads, how big is each token's cache?

What it buys, what it costs

Answer: one hundred twenty-eight kibibytes per token. One gibibyte per sequence, down from four. With one key-value head, multi-query: sixteen kibibytes per token, one hundred twenty-eight mebibytes per sequence. Key and value weights shrink too. Query and output weights don't, and all thirty-two attention patterns remain. Quality holds because separate key-value heads were largely redundant; trained with sharing, they learn to serve the group. About eight key-value heads: close to full quality. Just one: a small, noticeable drop.

GQA in numpy

In code, compute just the few key-value heads, then copy each one across its group. This line projects keys into two heads. The next line repeats each head twice, giving four, one per query head. From there it's ordinary attention: scores, causal mask, softmax, weighted values. Four attention patterns, five by five, and an output of five by sixteen, ready for the output projection. One of these lines produces exactly what the cache stores. Tap it.

The KV cache is huge. Can we shrink it?

The KV cache costs $2\cdot L\cdot h\cdot d_{head}\cdot T\cdot$bytes per sequence. With $L=32$, $h=32$, $d_{head}=128$ in bf16, that is 512 KiB per token, or 4 GiB for one 8,192-token sequence. Every generation step reads the whole cache, and the cache limits how many sequences fit on a GPU at once. Can we make it much smaller without losing much quality?

Share keys and values, keep the queries

Let a group of query heads share one key head and one value head. Each query head keeps its own $W_Q$, so it still asks its own question and gets its own attention pattern. Heads in a group can still attend to different positions. Only *what each past position offers*, its key and value vectors, is shared. Why little is lost: separately learned K/V heads are largely redundant, and a model trained (or briefly retrained) with sharing learns keys and values that serve the whole group. Measured results: with about 8 K/V heads, quality is close to full multi-head. With 1, there is a small but noticeable drop.

GQA and MQA precisely

**GQA**: $h_{kv}$ K/V heads ($h$ divisible by $h_{kv}$), each shared by $h/h_{kv}$ query heads. **MQA** is the extreme $h_{kv}=1$. $h_{kv}=h$ is ordinary multi-head. Query head $i$ (0-indexed) has $Q_i=XW_Q^{(i)}$ and uses K/V head $g=\lfloor i\,h_{kv}/h\rfloor$, with $K_g=XW_K^{(g)}$, $V_g=XW_V^{(g)}$: $$A_i=\text{softmax}(Q_iK_g^\top/\sqrt{d_{head}}+M),\quad O_i=A_iV_g$$ The $h$ outputs are concatenated and fed into $W_O\in\mathbb R^{(h\cdot d_{head})\times d}$ as before. Only $K_g,V_g$ are cached: $$2\cdot L\cdot h_{kv}\cdot d_{head}\cdot T\cdot\text{bytes}$$ That is $h/h_{kv}$ times smaller.

Cache sizes: MHA vs GQA vs MQA

$L=32$, $h=32$, $d_{head}=128$, bf16 (2 bytes), $T=8192$. - **MHA**, per token: $2\cdot32\cdot32\cdot128\cdot2=524{,}288$ bytes = 512 KiB. Times 8192 tokens = 4 GiB. - **GQA**, $h_{kv}=8$: factor $32/8=4$, so 128 KiB/token and 1 GiB. - **MQA**, $h_{kv}=1$: factor 32, so 16 KiB/token and 128 MiB. $W_K,W_V$ shrink by the same factor. $W_Q$ and $W_O$ keep their sizes, and there are still 32 attention patterns per position.

GQA in numpy

Compute $h_{kv}$ K/V heads, then repeat each one to cover its group of query heads. The cache stores K and V *before* the repeat, with shape [T, $h_{\text{kv}}$, $d_{\text{head}}$].
import numpy as np
T, d, h, h_kv, dh = 5, 16, 4, 2, 4
X = np.random.randn(T, d)
WQ, WK, WV = (np.random.randn(d, n * dh) for n in (h, h_kv, h_kv))
Q = (X @ WQ).reshape(T, h, dh)
K = (X @ WK).reshape(T, h_kv, dh).repeat(h // h_kv, axis=1)  # [T,h,dh]
V = (X @ WV).reshape(T, h_kv, dh).repeat(h // h_kv, axis=1)
S = np.einsum('qhd,khd->hqk', Q, K) / np.sqrt(dh) + np.triu(np.full((T, T), -np.inf), 1)
A = np.exp(S - S.max(-1, keepdims=True)); A /= A.sum(-1, keepdims=True)
out = np.einsum('hqk,khd->qhd', A, V).reshape(T, h * dh)  # then @ W_O
print(A.shape, out.shape)  # (4, 5, 5) (5, 16)

Remember

GQA lets each key/value head serve $h/h_{kv}$ query heads. This cuts the KV cache, and $W_K,W_V$, by a factor of $h/h_{kv}$. Quality barely drops for two reasons. Every query head still forms its own attention pattern. And separate K/V heads were largely redundant, so a model trained with sharing learns keys and values that serve the whole group.

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.