Paper notes

GQA: Turning Multi-Head Checkpoints into Grouped-Query Attention for 5% of Pretraining Compute

GQA lets groups of query heads share one key/value head, between multi-head (MHA) and multi-query attention (MQA); MHA checkpoints convert by mean-pooling heads plus about 5% extra pretraining. On T5-XXL it nears MHA quality at close to MQA speed. We check Table 1 and compute Llama 3's KV cache.

Published Updated 10 min read

On this page
  1. Why this paper matters
  2. Background: decoding reads the cache, not FLOPs
  3. Method 1: GQA as an interpolation
  4. Method 2: uptraining, converting MHA to GQA for 5%
  5. Experiments
  6. Checking Table 1 and the KV cache in code
  7. Limits and cautions
  8. What to take away
  9. Further reading
  10. FAQ

Why this paper matters

When a language model generates text, every new token requires reading all earlier keys and values from memory; that store is the KV cache. In 2019 Shazeer proposed multi-query attention (MQA): all query heads share one key/value head, so the cache is 1/H of its size and decoding is much faster, but quality drops and training can be unstable. In May 2023 Ainslie et al. at Google Research made two contributions: a way to turn an existing multi-head attention (MHA) model into an MQA model with a little extra training, and grouped-query attention (GQA), a compromise between MHA and MQA.

GQA has become the default choice of open LLMs since: Llama 2’s 34B and 70B use it, all three Llama 3 sizes (8B, 70B, 405B) have 8 key/value heads, and the Qwen3 report lists GQA as well. The paper’s value lies in two plain but practical things: a structure you can interpolate and a cheap conversion recipe.

Background: decoding reads the cache, not FLOPs

In autoregressive decoding each step produces one token, so the arithmetic is small and the bottleneck is memory bandwidth for loading weights and the KV cache. The cache size is

KV bytes=2×L×hkv×dhead×bytes×T\text{KV bytes} = 2 \times L \times h_{kv} \times d_{head} \times \text{bytes} \times T

where LL is the number of layers, hkvh_{kv} the number of key/value heads, dheadd_{head} the head dimension, TT the number of cached tokens, and the 2 counts keys and values. The most direct lever is hkvh_{kv}: MHA has hkv=Hh_{kv}=H, MQA has hkv=1h_{kv}=1, and GQA picks something in between, GG.

Method 1: GQA as an interpolation

GQA splits the HH query heads into GG groups that each share one key/value head. G=1G=1 is MQA, G=HG=H is MHA, and the KV cache shrinks to G/HG/H of MHA’s. The paper gives three reasons why GQA suits large models especially well:

  • Large models tend to scale the number of heads, so MQA, which cuts HH heads to one, becomes an ever more aggressive reduction; GQA keeps the same proportional cut in cache and bandwidth as models grow.
  • A large model’s KV cache grows linearly with model dimension while parameters and FLOPs grow quadratically, so attention bandwidth is relatively less of a burden for large models.
  • Standard tensor parallelism replicates a single key/value head onto every model shard, which GQA avoids. The Llama 2 paper points to the same problem on an 8-GPU A100 node: MQA cannot be sharded across heads, so you either replicate the KV (making the cache as large as GQA’s) or shard across the batch, which complicates serving.

GQA is applied to decoder self-attention and cross-attention but not to encoder self-attention, because encoder representations are computed in parallel and memory bandwidth is usually not their bottleneck.

Method 2: uptraining, converting MHA to GQA for 5%

The conversion recipe has two steps, modelled on Komatsuzaki et al.’s uptraining of dense T5 checkpoints into sparse mixture-of-experts models:

  1. Convert the checkpoint. For each group, mean-pool the key projection matrices (and value projections) of all its heads into a single head. The paper finds this works better than keeping only the first head or randomly initialising new key/value heads.
  2. Continue pretraining. Use the original pretraining recipe for a small proportion α\alpha of the original steps. The main experiments use α=0.05\alpha=0.05, which took about 600 TPUv3 chip-days for T5-XXL.

Experiments

All models are based on T5.1.1, implemented in JAX and Flax, with the Adafactor optimizer and T5’s hyperparameters and learning-rate schedule. The main comparison is MHA T5-Large and T5-XXL against T5-XXL uptrained with 5% for MQA and for GQA-8. Evaluation covers five summarisation sets (CNN/Daily Mail, arXiv, PubMed, MediaSum, Multi-News), WMT 2014 English-German translation and TriviaQA. Fine-tuning uses a constant learning rate of 0.001, batch size 128 and dropout 0.1, with greedy decoding; inference time is per sample per TPUv4 chip (via xprof, 8 TPUs, the largest per-chip batch that fits, up to 32).

Table 1 (dev sets; ROUGE-1 for summarisation, BLEU for translation, F1 for TriviaQA):

ModelInference time (unit s as printed)AvgCNNarXivPubMedMediaSumMultiNewsWMTTriviaQA
MHA-Large0.3746.042.944.646.235.546.627.778.2
MHA-XXL1.5147.243.845.647.536.446.928.481.9
MQA-XXL0.2446.643.045.046.936.146.528.581.3
GQA-8-XXL0.2847.143.545.447.736.347.228.481.6

The paper’s conclusion: the 5%-uptrained MQA model is both better and faster than MHA-Large, and GQA-8 comes close to MHA-XXL in quality at close to MQA’s speed. Three ablations:

  • Conversion method (Figure 4, T5-Large converted to MQA, α=0.05\alpha=0.05): mean pooling is best, then selecting the first head, then random initialisation.
  • Uptraining proportion (Figure 5, T5-XXL): GQA already performs reasonably right after conversion, while MQA needs training to be useful; both gain clearly from 5%, with diminishing returns beyond 10%.
  • Number of groups (Figure 6): going from 1 group (MQA) to 8 adds only modest inference time, and the cost rises as the group count approaches MHA; the paper picks 8.

Checking Table 1 and the KV cache in code

The code below does three things: it checks the averages and speed ratios in Table 1, measures how much of the gap between MQA and MHA GQA closes, and, using the configurations in Table 3 of the Llama 3 paper, computes the KV cache at a 128K context if those models used MHA, GQA or MQA:

# Table 1: (seconds per sample, printed average, scores on seven datasets)
# columns: CNN, arXiv, PubMed, MediaSum, MultiNews, WMT, TriviaQA
rows = {
    "MHA-Large": (0.37, 46.0, [42.9, 44.6, 46.2, 35.5, 46.6, 27.7, 78.2]),
    "MHA-XXL": (1.51, 47.2, [43.8, 45.6, 47.5, 36.4, 46.9, 28.4, 81.9]),
    "MQA-XXL": (0.24, 46.6, [43.0, 45.0, 46.9, 36.1, 46.5, 28.5, 81.3]),
    "GQA-8-XXL": (0.28, 47.1, [43.5, 45.4, 47.7, 36.3, 47.2, 28.4, 81.6]),
}
for name, (t, avg, xs) in rows.items():
    m = sum(xs) / len(xs)
    print(f"{name:<10s} printed {avg:4.1f}  columns {m:5.2f}  "
          f"speedup {1.51 / t:3.1f}x")

# how far GQA goes from MQA towards MHA
for label, f in [("printed", lambda r: r[1]),
                 ("columns", lambda r: sum(r[2]) / 7)]:
    mha, mqa, gqa = (f(rows[k]) for k in ("MHA-XXL", "MQA-XXL", "GQA-8-XXL"))
    print(f"{label}: GQA closes {(gqa - mqa) / (mha - mqa):.0%} of the gap")

# KV cache (bf16, one 128K-token sequence), configs from Llama 3 Table 3
cfgs = {"8B": (32, 32, 8, 4096), "70B": (80, 64, 8, 8192),
        "405B": (126, 128, 8, 16384)}  # layers, q heads, kv heads, width
for name, (layers, heads, kv_heads, dim) in cfgs.items():
    d_head = dim // heads
    out = []
    for label, g in [("MHA", heads), ("GQA", kv_heads), ("MQA", 1)]:
        per_token = 2 * layers * g * d_head * 2  # K and V, 2 bytes each
        out.append(f"{label} {per_token * 128 * 1024 / 2**30:7.1f} GiB")
    print(f"{name:>4s} (groups of {heads // kv_heads:2d}):", "  ".join(out))

Output:

MHA-Large  printed 46.0  columns 45.96  speedup 4.1x
MHA-XXL    printed 47.2  columns 47.21  speedup 1.0x
MQA-XXL    printed 46.6  columns 46.76  speedup 6.3x
GQA-8-XXL  printed 47.1  columns 47.16  speedup 5.4x
printed: GQA closes 83% of the gap
columns: GQA closes 88% of the gap
  8B (groups of  4): MHA    64.0 GiB  GQA    16.0 GiB  MQA     2.0 GiB
 70B (groups of  8): MHA   320.0 GiB  GQA    40.0 GiB  MQA     5.0 GiB
405B (groups of 16): MHA  1008.0 GiB  GQA    63.0 GiB  MQA     7.9 GiB
  • Speed. From the table, GQA-8-XXL is about 5.4 times faster than MHA-XXL and MQA-XXL about 6.3 times; GQA is only about 17% slower than MQA (0.28 versus 0.24).
  • Quality. With the printed averages GQA recovers 83% of the gap between MQA and MHA; with averages computed from the columns it recovers about 88%. The conclusion is the same, but the two readings differ: the printed 46.6 for MQA-XXL is 0.16 below the 46.76 mean of its seven columns, the printed 47.1 for GQA-8-XXL is 0.06 below 47.16, while both MHA rows agree with their column means. The paper does not say how the average is computed, so treat that column as approximate. Also, Table 1 gives the time unit as s while the Figure 3 axis says ms; this note uses only the relative values.
  • Cache. With the real Llama 3 configurations, if the three models used MHA the KV cache for one 128K-token sequence would be 64, 320 and 1008 GiB; with 8 key/value heads it is only 16, 40 and 63 GiB. That is why a model like 405B must use GQA: 1008 GiB for one sequence will not fit in a whole node’s memory. Note that this is a counterfactual - the real Llama 3 models are all GQA.

Limits and cautions

  • Flawed metrics. The authors say ROUGE is a flawed evaluation, so it is hard to be sure the trade-offs are right, and inference overhead matters most for long generations, exactly where quality is hardest to measure.
  • No from-scratch control. With limited compute the paper did not train a comparable GQA model from scratch, so it is unknown whether “convert then uptrain” or “train GQA directly” is better.
  • Encoder-decoder only. The paper expects GQA’s advantage over MQA to be larger for decoder-only models (which have no separate cross-attention), but does not test it. The Llama 2 paper later compared MHA, MQA and GQA at 30B parameters on 150B tokens and reports GQA comparable to MHA on most tasks and better than MQA on average; the wiki page on efficient attention also collects DeepSeek-V2’s ablation, and the two do not fully agree, which shows the gap depends on scale, training budget and evaluation difficulty.
  • Timings are hardware-specific. They come from TPUv4 with a particular batch size and parallelism; on GPUs and different serving stacks the speedups will differ.
  • Mean pooling is only an initialisation. The paper shows the extra training matters (especially for MQA), so “free conversion” is not true, and 5% of pretraining is still a lot: about 600 TPUv3 chip-days for T5-XXL.

What to take away

  1. The number of KV heads is a knob. Cache size is proportional to hkvh_{kv}, and GQA lets you choose between MHA and MQA.
  2. The middle value gets most of the benefit. 8 groups recovered more than 80% of the quality gap between MQA and MHA while keeping almost all of MQA’s speed.
  3. Existing checkpoints can be converted cheaply. Mean pooling plus 5% extra training is far cheaper than training a new architecture.
  4. Recompute what you read. The averages in the table are not exactly consistent with the columns; it does not change the conclusion, but it is a reminder not to treat a single number as final.

Further reading

FAQ

What is the difference between GQA, MQA and MHA?
All three have H query heads and differ in how many key/value heads they keep. MHA has one key/value head per query head (H of them), MQA has a single one shared by every query head, and GQA splits the query heads into G groups that each share one. GQA-1 is MQA and GQA-H is MHA. The KV cache is proportional to the number of key/value heads, so GQA shrinks it to G/H of MHA's.
Can an already trained MHA model be converted to GQA?
The paper's recipe has two steps. First mean-pool the key and value projection matrices of all heads in a group into one head for that group. Then continue pretraining with the original recipe for a small fraction of the original steps (5% in the paper). In the ablations mean pooling beats keeping only the first head and beats random initialisation; converted GQA already works reasonably without training, while MQA needs the extra training.
How many groups should GQA use?
On T5-XXL the paper finds that going from 1 group (MQA) to 8 groups adds only a little inference time, while moving closer to MHA costs more and more, so it settles on 8. Llama 2's 34B and 70B models and all three Llama 3 sizes (8B, 70B, 405B) also use 8 key/value heads, again as a compromise between inference cost and quality.
What are the limitations of the GQA paper?
The authors list three. Long-form generation is evaluated with ROUGE, a flawed metric; there is no from-scratch GQA model to compare against, so it is unknown whether converting beats training GQA directly; and experiments cover only encoder-decoder T5 models, so the benefit for decoder-only models is an expectation, not a measurement. The Llama 2 paper later added a decoder-only comparison at 30B scale.