GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
- Publication
- EMNLP 2023Conference
- First submitted to arXiv
- arXiv:2305.13245
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{transformersgqa2023,
title = {{GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints}},
author = {Joshua Ainslie and James Lee-Thorp and Michiel de Jong and Yury Zemlyanskiy and Federico Lebrón and Sumit Sanghai},
year = {2023},
eprint = {2305.13245},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2305.13245}
}
In 2019, Noam Shazeer proposed multi-query attention (MQA), in which all attention heads share a single set of keys and values. On the translation model in that paper, the decoder's amortized time per generated token dropped from 46 µs to 3.8 µs.
Three and a half years later, some large models had adopted MQA, such as Google's own PaLM; many had not, and open models like T5 and LLaMA still used standard multi-head attention (MHA). If you already have an MHA model that cost a fortune to train and you want MQA's decoding speed, do you really have to train it all over again from scratch?
In May 2023, a Google Research paper with a main text of under five pages offered two answers. First, an existing MHA checkpoint can be converted to MQA for only about 5% of the original pre-training compute. Second, there is a middle point between MHA and MQA. Split the query heads into groups and let each group share one set of keys and values; this is called grouped-query attention (GQA).
Two months later, Meta used GQA in Llama 2 34B and 70B, citing this very paper.
Defining the problem
A language model generates one token at a time. At each step, the new token's query is compared against the keys of all the tokens before it, and the resulting weights are used to combine their values. The keys and values of earlier tokens are stored once they have been computed; that's the KV cache.
The paper opens by pointing out that the bottleneck is memory bandwidth. For every token generated, the decoder's weights and the entire KV cache have to be read from memory. In other words, each step involves little computation, and the accelerator spends most of its time waiting for data.
The size of the cache can be estimated like this:
is the number of layers, the number of KV heads, the dimension of each head, the number of tokens, and the number of bytes per value.
The leading 2 stands for K and V. The number of layers and the head dimension affect the whole model, and the token count is up to the user; the one factor you can adjust on its own when designing attention is the number of KV heads. In MHA, each query head has its own set of keys and values, so the number of KV heads equals the number of heads . MQA squeezes it down to 1, shrinking both the cache and the KV read at each step by a factor of .
So why not just switch everything to MQA? The paper raises two problems.
The first is quality. When every query head can only look at the same set of keys and values, model capacity shrinks and quality drops. The paper's appendix also records training instability. The authors trained several MQA versions of T5-Large from scratch; during pre-training the loss kept spiking, and when the models were fine-tuned on long-input tasks, they diverged right from the start.
The second is cost. If you want MQA, you have to train a separate model. As the paper puts it, rerunning the entire pre-training just to make inference a bit faster isn't necessarily worth it, or even feasible.
There's one more wrinkle. Bigger models usually have more heads; T5.1.1 Large has 16, and XXL has 64. Cutting the KV heads from 64 down to 1 is a much harsher cut than going from 16 to 1.
So this paper sets out to answer two questions. Can an MHA model that has already been trained be converted to MQA cheaply? And between 1 and , is there a number of KV heads that offers a better deal?
Solving the problem
Grouped-query attention

Look at where the blue query heads in the bottom row connect upward. In MHA on the left, each of the 8 query heads has its own set of keys and values; in MQA on the right, all 8 query heads crowd onto a single set; in GQA in the middle, every two adjacent query heads share one set, for 4 sets in total.
In general form, the query heads are split into groups, each sharing one key head and one value head, written as GQA-. GQA-1 has only one group, which makes it MQA; GQA- has only one query head per group, which makes it MHA.
The paper doesn't state which query heads go in the same group. Following the adjacent grouping drawn in Figure 2, this note writes it as the formulas below. With query heads numbered from 0, the -th query head belongs to group and computes attention with that group's and :
is the dimension of each head. The number of query heads, the computation for the attention scores and the output projection are all the same as in MHA; only the key and value projections and the cache get smaller.
Let's walk through it with the paper's main model, T5 XXL. Its decoder has 64 heads per layer, with 64 dimensions per head. With MHA, each token stores values per layer. GQA-8 splits the 64 query heads into 8 groups of 8, leaving only . MQA has even fewer, 128.
The authors use GQA only in the decoder, covering both the decoder's self-attention and the cross-attention that reads the encoder output. Encoder self-attention computes over the whole input in parallel, so memory bandwidth isn't its main bottleneck, and it is left as it was.
Converting MHA to GQA

The conversion has two steps. The first converts the checkpoint. Each layer originally has key projection matrices ; the ones in the same group are averaged into that group's projection. The value projections get the same treatment, while the query and output projections stay untouched. The figure shows the case of converting to MQA, where all projections are averaged into one.
Write the set of query heads in group as ; each group has heads:
Projections are linear, so averaging the matrices is the same as averaging the outputs. Multiplying the same input by gives exactly the average of the original keys of the heads in the group.
In other words, right after the conversion, each query head no longer gets its own original key, but an average that blends together the keys of several heads in its group. GQA-8 averages 8 heads per group, while MQA averages all 64 at once; the bigger the group, the more information gets blended away. The experiments later on show this difference.
The second step is uptraining. Using the original pre-training recipe and data, the model trains for an extra fraction of the original number of steps so it can adapt to the new structure. The approach is borrowed from sparse upcycling, which converted a dense T5 into a mixture-of-experts model. The main experiments use , and for T5 XXL this step took about 600 TPUv3 chip-days. Scaling by that ratio, rerunning the entire pre-training under the same setup would take about 12,000 chip-days.
Why stop in the middle
The paper also explains why a middle point is especially worthwhile for large models:
- Head count grows with the model. MQA's reduction factor is exactly , so the bigger the model, the harder it cuts. GQA can keep the reduction at a fixed factor.
- Large models worry less about KV. The KV cache is proportional to model width , while parameter count and computation are proportional to . The wider the model, the smaller attention's share of the memory burden, and the less it costs to keep a few more KV heads.
- Waste when sharding. Large-model inference is split across multiple accelerators, commonly by attention head. MQA has only one set of KV, so every partition has to store a copy of it; GQA's multiple KV sets can go to different partitions, which removes that waste.
The third point is more abstract, so let's work it out with a model we've already read on this site.
Applying it to Llama 2 70B
Llama 2 70B has 80 layers, 64 query heads and 128 dimensions per head, and it uses 8 KV heads, so . The cache is stored in a 16-bit format such as bf16 or fp16, at 2 bytes per value. Plugging these into the formula above, the KV cache per token is bytes, exactly times 40 KiB:
| Per token | 4,096 tokens | |
|---|---|---|
| 1 (MQA) | 40 KiB | 160 MiB |
| 4 | 160 KiB | 640 MiB |
| 8 (actual) | 320 KiB | 1.25 GiB |
| 16 | 640 KiB | 2.5 GiB |
| 32 | 1.25 MiB | 5 GiB |
| 64 (MHA) | 2.5 MiB | 10 GiB |
For one 4,096-token sequence, the MHA version needs 10 GiB, while GQA-8 needs only 1.25 GiB. Serve 32 such sequences at once, and that's 320 GiB versus 40 GiB.
Now for sharding. Meta's official inference code splits 70B across 8 GPUs (model-parallel size 8), and its attention layer is written like this:
class Attention(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.n_kv_heads = args.n_heads if args.n_kv_heads is None else args.n_kv_heads
model_parallel_size = fs_init.get_model_parallel_world_size()
self.n_local_heads = args.n_heads // model_parallel_size
self.n_local_kv_heads = self.n_kv_heads // model_parallel_size
self.n_rep = self.n_local_heads // self.n_local_kv_heads
...
self.cache_k = torch.zeros(
(
args.max_batch_size,
args.max_seq_len,
self.n_local_kv_heads,
self.head_dim,
)
).cuda()
...
def forward(
self,
x: torch.Tensor,
start_pos: int,
freqs_cis: torch.Tensor,
mask: Optional[torch.Tensor],
):
...
self.cache_k[:bsz, start_pos : start_pos + seqlen] = xk
self.cache_v[:bsz, start_pos : start_pos + seqlen] = xv
keys = self.cache_k[:bsz, : start_pos + seqlen]
values = self.cache_v[:bsz, : start_pos + seqlen]
# repeat k/v heads if n_kv_heads < n_heads
keys = repeat_kv(keys, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
values = repeat_kv(values, self.n_rep) # (bs, seqlen, n_local_heads, head_dim)
Excerpted from llama/model.py in meta-llama/llama (commit 6d4c0c2, the version from the day Llama 2 was released); each ... marks lines this note leaves out, including the projection layers, the allocation of cache_v and the positional encoding.
Plug in the 70B numbers. With n_heads=64 and n_kv_heads=8 divided across 8 GPUs, each GPU gets 8 query heads and 1 KV head, and n_rep=8. The third dimension of the cache cache_k is just 1, so each GPU stores only bytes per token, 40 KiB.
Before attention is computed, repeat_kv expands this 1 KV head into 8 copies for the 8 query heads on that GPU. Its effect is the same as torch.repeat_interleave, so adjacent query heads form a group: query heads 0 to 7 read KV head 0, 8 to 15 read KV head 1, and so on. repeat_kv is written as an expand followed by a reshape. When a GPU holds 2 or more KV heads, the reshape really does allocate a copy with as many heads as there are query heads. With 70B split across 8 GPUs, each GPU has only 1 KV head, so the shape produced by expand can be reshaped directly, and this step is just a view that shares memory, taking no extra space. Either way, the cache itself holds only the KV heads; the copies exist only while attention is being computed.
What happens with MQA? n_kv_heads=1, 1 // 8 gives 0, and the next line divides by zero when it computes n_rep. As the appendix of the Llama 2 paper explains, to actually run MQA on 8 GPUs, either every GPU stores the same KV, or you shard along the batch instead, which needs a batch larger than the number of GPUs and makes serving more complicated.
With the first option, each GPU again holds 40 KiB, exactly the same as GQA-8. In this kind of 8-GPU tensor-parallel deployment, MQA saves no KV cache at all, yet its quality is worse. That's the waste the paper's third point describes.
Once the number of KV heads became part of the model configuration, the surrounding tools had to catch up too. The day after Llama 2 was released, Georgi Gerganov, the author of llama.cpp, opened a PR to support 70B; until the new GGUF format came out, users had to add -gqa 8 on the command line themselves (8 for 70B, 1 for other models).
Discussion
Experimental setup
All models use the T5.1.1 architecture and are implemented in JAX and Flaxformer. The main experiments compare four models: MHA T5 Large, MHA T5 XXL, and the MQA and GQA-8 versions converted from the public T5.1.1 XXL checkpoint and uptrained for 5%.
There are seven evaluation tasks. Five are summarization (CNN/Daily Mail, arXiv, PubMed, MediaSum, Multi-News), scored with ROUGE-1, which measures how much the words in the model's summary overlap with the reference summary; translation uses BLEU on WMT 2014 English-to-German; question answering uses F1 on TriviaQA. Each task is fine-tuned separately to convergence, the best checkpoint on the dev set is used, and decoding is always greedy. CNN/Daily Mail and WMT use 512 input and 256 output tokens, the other summarization tasks 2,048 input and 512 output, and TriviaQA 2,048 input and 32 output.
Speed is measured on 8 TPUv4 chips, with each chip running the largest batch it can fit (up to 32) and the parallelism tuned separately for each model; the reported figure is the average time per sample per chip.
Main results
| Model | KV heads | s/sample | Average |
|---|---|---|---|
| MHA-Large | 16 | 0.37 | 46.0 |
| MHA-XXL | 64 | 1.51 | 47.2 |
| MQA-XXL | 1 | 0.24 | 46.6 |
| GQA-8-XXL | 8 | 0.28 | 47.1 |
GQA-8 averages 47.1, only 0.1 below MHA-XXL's 47.2, while the time per sample drops from 1.51 s to 0.28 s, 5.4× faster. Compared with MQA, GQA-8 takes 0.04 s more per sample and scores 0.5 higher on average. Task by task, GQA-8 is even slightly above MHA-XXL on PubMed (47.7 vs. 47.5) and Multi-News (47.2 vs. 46.9), while on TriviaQA it's 81.6 vs. 81.9, a little lower.
MQA-XXL has more than ten times the parameters of MHA-Large, yet its inference time is shorter (0.24 vs. 0.37 s) and its average score is higher (46.6 vs. 46.0). Look at the KV heads column. Both sizes have 64 dimensions per head and 24 decoder layers, but MQA-XXL stores only 1 KV head per layer, while MHA-Large stores 16. Sort the four models by inference time from shortest to longest, and you get exactly the order of KV heads from fewest to most. The comparison is this note's own, and it fits the bandwidth bottleneck the paper points to at the start.
How to convert, how long to train, how many groups
The ablations use only three tasks, CNN/Daily Mail (short summarization), Multi-News (long summarization) and TriviaQA (question answering); the performance scores in Figures 4 and 5 are all measured on these three.
First, what's the best way to convert the checkpoint?

This comparison is done on T5-Large, converted to MQA and then uptrained for 5%. Mean averages all the heads, First simply takes the first head, and Random reinitializes the projection randomly. Averaging comes out best, at about 55.55; taking a single head gives about 55.45, and random initialization about 55.2. The authors' explanation is that the more pre-trained information is preserved, the better the result.
Note that the horizontal axis starts at 54.4. The three actually differ by about 0.3 points, and the figure shows no error bars or number of runs. The appendix also mentions that the fine-tuning results of uptrained MQA vary a lot, so unstable tasks are run three times and averaged; this figure compares exactly those MQA models, so the ordering is a useful guide, but don't put too much weight on the gaps.
Next, how much uptraining does it take?

The red dashed line is the level of the original MHA-XXL, about 57.5. means right after conversion, with no uptraining at all. At that point GQA-8 is already at 56.7, while MQA is only at 53.9.
About this gap, the paper says only that GQA is usable right after conversion, while MQA needs uptraining before it's of any use; it gives no reason. In light of the averaging effect described earlier, GQA-8 averages only 8 heads per group, while MQA blends the keys of all 64 heads together, so a much larger loss is hardly surprising; that reading is this note's own. An unofficial community implementation that converts T5 to GQA also notes in its README that without uptraining, the fewer the KV heads, the faster the generated text falls apart.
After 5% uptraining, GQA-8 is back to about 57.4, and MQA catches up to 56.9; at 10%, both gain a little more, GQA-8 reaching about 57.55 and MQA about 57.15. The improvement from 5% to 10% is clearly smaller, which the authors call diminishing returns, and the main experiments use 5%. The figure measures only three points, 0, 0.05 and 0.1; the curves between them simply connect the dots.
Stability points the same way. The appendix notes that uptrained MQA is more stable than MQA trained from scratch, but its fine-tuning results vary a lot, so on the unstable tasks the authors had to run three times and average. Uptrained GQA, by contrast, appears stable, so the authors didn't look further into why MQA is unstable.
Finally, how many groups?

This figure shows the speed of GQA-XXL with 2,048 input and 512 output tokens, with the horizontal axis on a log scale. From 1 group to 8, the time goes only from about 0.48 s to 0.51 s; 16 groups take about 0.6 s, 32 groups about 0.8 s, and at 64 groups (that is, MHA) it jumps all at once to about 2.55 s. The authors picked 8 groups as the compromise.
Keep two things in mind when reading this figure.
First, going from 32 groups to 64 only doubles the KV, yet the time more than triples. The paper says only that the closer you get to MHA, the higher the cost, without explaining the size of this jump. Timing uses the largest batch each TPU can fit, so a larger KV may force a smaller batch, which in turn makes the time amortized per sample longer; that explanation is this note's speculation.
Second, this figure shows speed only. Quality was measured for just three group counts, all in Table 1, with (MQA) at 46.6, at 47.1 and (the original MHA-XXL) at 47.2; Figure 5 also gives GQA-8's performance at three uptraining proportions. There are no quality numbers for 4, 16 or 32 groups, and the paper doesn't answer whether 8 groups is the sweet spot for quality.
What the paper leaves unanswered
In their limitations section, the authors list three points themselves. KV bandwidth matters most when generating long text, but the quality of long text is hard to evaluate in the first place, and the authors admit that ROUGE has flaws. Limited by compute, they didn't train an XXL GQA model from scratch for comparison, so it remains unclear whether uptraining or training from scratch is better. And all experiments are on encoder-decoder models; the authors expect GQA's advantage over MQA to be larger in decoder-only models, but there are no experiments.
Later decoder-only models added two sets of evidence. Both trained from scratch, and they reach somewhat different conclusions.
In its appendix, Llama 2 trained three 30B models on 150 billion tokens each, widening the feed-forward layers in the MQA and GQA versions to match MHA's parameter count. GQA performs about the same as MHA on most evaluations and is better than MQA on average.
DeepSeek-V2's appendix, in turn, trained three 7B dense models on 1.33 trillion tokens each, adjusting the number of layers to keep them all at about 7B parameters. This time MHA clearly leads. On MMLU, MHA scores 45.2, GQA-8 41.2 and MQA 37.9, and BBH, C-Eval and CMMLU show the same order. DeepSeek used these results to show what GQA costs, and then introduced its own MLA.
The two experiments differ in scale, amount of training and evaluation. Whether GQA “comes close to MHA” depends on which tasks you compare and how long you train; on T5's seven tasks the average gap is 0.1 points, but on harder knowledge benchmarks with longer training, the gap may widen to several points.
Mean pooling itself rests on an unstated assumption, that the heads in a group are similar enough for their average not to distort too much. The paper doesn't discuss how to form the groups, and Figure 2 draws adjacent heads as a group. Later research takes on this problem directly. For example, QCQA in June 2024 uses an evolutionary algorithm to choose which heads go into a group, and another paper in December 2024 first aligns the heads in a group with Procrustes analysis and then merges them.
There are engineering pitfalls too. GQA doesn't reduce the computation for attention scores; what it saves is the bandwidth for reading KV, so it only helps if the kernel really reads just heads. FlashAttention built this into its interface in version 2.0 in July 2023, directly supporting fewer KV heads than query heads. On the flip side, the community implementation mentioned above has an issue from January 2024 reporting that after using it to convert T5 to GQA on an A100, generation time actually went up from 97 ms to 414 ms; someone followed up in May of that year, and the maintainer never replied. Reasoning from the same point that led the paper to leave the encoder unchanged, one would expect prefill, which computes the whole prompt in parallel in one go, to save little time as well; the speed benefit is concentrated in token-by-token decoding.
As for reproduction, the paper released neither code nor the converted checkpoints. That unofficial implementation reproduced only the speed trend in Figure 6, on a single 2080 Ti; the “reproduce the paper's fine-tuning results” box in its README was still unchecked at its last update in May 2024 (600 TPUv3 chip-days against one gaming card, so the empty box is forgivable).
Conclusion
This paper does two things. First, it gives a conversion recipe, which averages an MHA checkpoint's key and value projections by group and then uptrains for 5% of the original pre-training steps. Second, it proposes GQA, which uses a group count between 1 and to land between MHA's quality and MQA's speed.
The whole paper rests on Table 1. After T5 XXL is converted to GQA-8, its average score over the seven tasks is only 0.1 below MHA, decoding is 5.4× faster, and its speed is only slightly behind MQA. Figure 5 shows that GQA is much better than MQA right after conversion, and that 5% uptraining already wins back most of the gap.
The limitations are clear too. The experiments cover only T5, an encoder-decoder model, and quality rests on ROUGE; the group count gets only a speed curve, with quality measured for just three group counts, 1, 8 and 64; and there is no comparison with GQA trained from scratch. Later, DeepSeek-V2 measured a 4-point gap on MMLU between GQA-8 and MHA in a setting with 7B parameters and 1.33 trillion tokens.
Before deploying or designing a model, plug the number of KV heads into the KV cache formula and see whether your context length and batch size will fit. It's best not to use more tensor-parallel GPUs than there are KV heads, or the extra GPUs can only store copies. Before switching inference frameworks, also confirm that the kernel supports GQA natively; with implementations that replicate the KV up to the number of query heads before computing, the bandwidth you saved may get eaten back up. If you want to convert an MHA model you already have, budget about 5% of the original pre-training compute, and keep in mind that GQA holds up to conversion better than MQA.
Looking back, the paper's two contributions went different ways. Llama 2 70B was pre-trained with GQA from scratch rather than taking the conversion route, and Mistral 7B is also natively GQA; GQA itself, meanwhile, has been carried forward ever since. Across Llama 3 from 8B to 405B, the query heads grow from 32 to 128, while the KV heads stay at 8. A year later, when DeepSeek proposed MLA, the baseline it used to compare cache sizes was GQA as well, and it described its own cache as equivalent to GQA with only 2.25 groups. From then on, the number of KV heads became, like the number of layers and the model width, one of the boxes you fill in first when designing a large language model.