Module 2 · Lesson 2.3 of 2.5

MHA vs MQA vs GQA

Learning goal: explain how multi-head, multi-query and grouped-query attention differ only in how many key/value heads they keep; map any query head to its KV head; and compute how that choice changes the raw KV cache for one sequence.

In Lesson 2.2 every head had its own query, key and value projections. During decode, the keys and values of every processed token are cached (Module 1), so the number of key/value heads decides how much is stored and read per step. This lesson changes only that number and keeps everything else fixed.

Explore this inside the 3D Transformer → Follow the full input through Q/K/V and head sharing; later architecture topics are optional.

2.3.1 Three ways to share key/value heads

Write Hq for the number of query heads (the count that Lesson 2.2 wrote as H; H = Hq) and HKV for the number of key/value heads in one attention layer. Each KV head has one key projection and one value projection, so it produces one cached key vector and one cached value vector per token. Query heads never shrink in these designs: every query head still computes its own attention pattern. What changes is how many distinct key/value heads those queries read.

Reference layouts with 16 query heads and head dimension D = 128 (example values)
LayoutQuery heads HqKey headsValue headsQuery heads per KV headK (and V) projection output width HKV·D
MHA (multi-head)16161612,048
GQA (grouped-query)16444512
MQA (multi-query)161116128
  • MHA (Vaswani et al., 2017) gives every query head a private key head and value head.
  • MQA (Shazeer, 2019) keeps many query heads but one shared key head and one shared value head.
  • GQA (Ainslie et al., 2023) splits the query heads into equal groups; each group shares one key head and one value head.

Intuition, not mechanism: think of KV heads as shared reference tables. MHA gives each reader its own copy built by its own projection; MQA makes all readers consult one table; GQA gives each team of readers one table. Each reader still asks its own question (its own query), so attention weights can still differ across heads that share K and V.

2.3.2 GQA generalises MHA and MQA

In grouped-query attention, each KV head serves a fixed group of query heads. With 16 query heads and 4 KV heads, each group contains 4 query heads. They ask different questions using their own Q vectors, but read the same K/V rows. The architecture defines these groups; the input tokens do not choose them.

G = Hq / HKV
g(i) = ⌊i / G⌋
headi = Attention(XWQi, XWKg(i), XWVg(i))
Hq, HKV
query heads and key/value heads in the layer; Hq must be divisible by HKV so every group has the same size.
G
group size: how many query heads share one KV head.
i
query head index, numbered from 0 to Hq − 1.
g(i)
index of the KV head (and group) that query head i reads.
X, W
layer input [T, dmodel] and learned projections; WQi, WKg, WVg each have shape [dmodel, D] (biases omitted).

Example: Hq = 16, HKV = 4, so G = 4. Query head 5 reads KV head ⌊5 / 4⌋ = 1, together with query heads 4, 6 and 7. Query head 15 reads KV head ⌊15 / 4⌋ = 3.

Special cases:

  • HKV = Hq → G = 1 → g(i) = i: every query head has its own KV head. This is MHA.
  • HKV = 1 → G = Hq → g(i) = 0 for all i: one KV head for everyone. This is MQA.

Tensor view

Per layer, without a batch dimension: Q has shape [T, Hq, D], while K and V have shape [T, HKV, D]. Only the smaller K and V tensors go into the cache. The illustrative pseudo-code below shows two ways to compute the same result.

# Q: [T, H_q, D]   K, V: [T, H_kv, D]   (one layer, no batch dimension)
G = H_q // H_kv

# Naive: materialise repeated copies so shapes match MHA code.
K_rep = repeat_each_head(K, G, axis=1)   # [T, H_q, D]: KV0 x G, KV1 x G, ...
V_rep = repeat_each_head(V, G, axis=1)   # [T, H_q, D]
for i in range(H_q):
    out[:, i] = attention(Q[:, i], K_rep[:, i], V_rep[:, i])

# Index-based: read the shared head directly; no [T, H_q, D] copies.
for i in range(H_q):
    out[:, i] = attention(Q[:, i], K[:, i // G], V[:, i // G])

The repeat must place copies next to each other (KV0, KV0, KV0, KV0, KV1, …) so that position i holds KV head ⌊i/G⌋. Even in the naive version the cache stores only [T, HKV, D]; the repeated tensors are temporaries. Optimised attention kernels typically avoid materialising them and load each shared K/V block once for all G query heads.

2.3.3 Comparing head layouts and KV memory

The cache stores one key and one value vector of length D per KV head, per token, per layer. Lesson 2.5 derives this formula step by step; here we use it to compare layouts.

MKV = 2 · L · T · HKV · D · B
2
one key tensor and one value tensor.
L
number of attention layers (fixed at 32 in the tool).
T
cached sequence length in tokens.
HKV
key/value heads per layer. Hq does not appear.
D
head dimension: the length of one key or value vector. It is the same number as dhead in Lesson 2.2 and dk = dv in Lesson 2.1, since heads have equal width here.
B
bytes per element (fixed at 2 for BF16 in the tool).

Head layout and KV memory comparison

What this shows
Which KV head each query head reads, and the raw KV storage of MHA, your layout and MQA for one sequence.
Try
Use the presets, then change KV heads with query heads fixed. Select a query head to see its group. Then change query heads alone.
What to notice
Memory follows HKV, D and T linearly. Changing Hq alone changes the sharing, not the current layout's memory.

Shared dimensions: head width 128, sequence length 4,096 positions, 32 layers and 2 bytes per element in every comparison row.

Advanced: change shared dimensions

First compare the head layouts at the reference dimensions above. Changing head width or sequence length scales every row's raw storage equally; grouping and percentage savings stay the same at fixed head counts. All rows always use the same dimensions. For other model and precision assumptions, use the KV memory calculator.

Grouping (heads numbered from 0)

Each box is one group: its query-head buttons on top, the key head (K) and value head (V) they share below. In MHA every box holds one query head. Select a query head.

    Raw KV storage for one sequence; Hq, D, T, L = 32 and B = 2 identical in every row
    LayoutHq / HKVGroup sizeBytes per token (all layers)MKV per sequenceReduction vs MHA

    Assumptions: fixed L = 32 layers and BF16 (B = 2 bytes); one sequence, no batch; every row uses the same Hq and D (real models may also change dmodel or D); contiguous cache with no padding, block or allocator overhead. MKV is raw KV storage, not total GPU memory: weights, activations, temporary buffers and fragmentation are excluded. MiB = 220 bytes, GiB = 230 bytes.

    Read the defaults: at T = 4,096 and D = 128, MHA stores 2 · 32 · 4,096 · 16 · 128 · 2 = 1,073,741,824 bytes (1 GiB) per sequence. GQA with 4 KV heads stores a quarter of that (256 MiB, 75% less) and MQA a sixteenth (64 MiB, 93.75% less). The reduction is always 1 − HKV/Hq, independent of T, D, L and B, because those factors cancel.

    2.3.4 Why fewer KV heads matter during decode

    Each decode step processes one new token per sequence. In every layer, each query head of that token scores against the keys of all cached positions and mixes their values. So, in a simplified model where nothing stays in on-chip memory between steps, a step at cache length T reads about MKV bytes of cached K/V, and that read volume scales with HKV exactly as storage does.

    1. Fewer KV heads
    2. Fewer cached bytes per token
    3. Less KV memory per sequence and fewer KV bytes read per decode step
    4. Less capacity and bandwidth pressure from the cache
    The chain of effects in the simplified model. Each step is a reduction in pressure, not a guaranteed speedup.
    • Memory capacity: with a fixed amount of memory set aside for the cache, a quarter of the bytes per token means roughly four times as many cached tokens fit, whether as longer contexts or more concurrent sequences (ignoring allocator overhead).
    • Decode read traffic: attention during decode does little arithmetic per byte loaded from the cache. Reducing the bytes loaded per step lowers the bandwidth demand from attention, which matters most when decode is bandwidth-sensitive.
    • Smaller K/V projections: WK and WV shrink from [dmodel, Hq·D] to [dmodel, HKV·D]. This saves some parameters and projection work, but the query and output projections are unchanged.
    Advanced: sharing raises arithmetic intensity, it does not remove score computation

    Per new token and layer, all Hq query heads still compute T scores each, about Hq · T · D multiply-adds for QKT and the same again for the weighted sum of values. Those counts do not depend on HKV. What drops is the K/V data needed: 2 · T · HKV · D elements. A kernel that loads each shared K/V block once and uses it for all G query heads of the group performs about G times more arithmetic per cached byte loaded. Whether that turns into lower latency depends on whether the step was limited by memory bandwidth in the first place.

    2.3.5 Limits and trade-offs

    Fewer KV heads reduce raw cache memory when the other dimensions stay fixed. All query heads still calculate their attention results. Less cache memory does not guarantee an equally large speedup or unchanged answer quality; changing a trained model’s head layout generally requires adaptation or retraining.

    What the arithmetic does not tell you

    • No guaranteed proportional speedup. A 75% smaller cache does not make generation four times faster. End-to-end time also depends on attention kernels, batch size, sequence length and hardware, and at small batch sizes reading the model weights for every step can dominate the memory traffic. Short sequences have small caches to begin with.
    • Quality cannot be read from this diagram. Sharing K/V reduces how many distinct key and value projections the model can learn. Whether that costs accuracy is an empirical result for a given model, data set and training budget.
    • Reported findings, not guarantees. Shazeer (2019) reports that multi-query attention decodes much faster in his experiments with only minor quality degradation. Ainslie et al. (2023) report that uptrained GQA models reach quality close to MHA while running at speeds comparable to MQA, on the models and tasks they evaluated.
    • Trained models cannot be converted arbitrarily. The number of KV heads is baked into the learned WK and WV. Ainslie et al. convert multi-head checkpoints by mean-pooling the key and value projection heads within each group, then continue pre-training (uptraining) using about 5% of the original pre-training compute. Simply deleting or repeating heads in a trained model is not the same model.
    • Cache-compression designs change the formula. Multi-head latent attention (MLA), introduced in DeepSeek-V2, caches one compressed latent vector per token instead of per-head keys and values, so the HKV and D formula in this lesson does not describe it. Everything here assumes ordinary K and V rows per KV head.
    • Divisibility. In the standard formulation, Hq must be divisible by HKV; the tool only offers such values.

    References

    Knowledge check

    Answer, then read the explanation. You can retry any question.