Grouped-Query Attention: Fewer KV Heads, Same Quality
Building GQA from the ground up — from multi-head attention to multi-query attention to grouped-query attention — showing exactly how sharing KV heads across query groups reduces the KV cache by a factor of h/g while preserving nearly all of MHA's quality. Every formula derived, every number verified.
The previous blog established that autoregressive inference is memory-bandwidth-bound, and that the KV cache is the dominant memory load at long contexts. The formula was exact: . The factor — the number of KV heads — appears linearly. Reduce and the cache shrinks proportionally.
This blog derives the two techniques that pull this lever: Multi-Query Attention (MQA, Shazeer 2019), which collapses all KV heads to one, and Grouped-Query Attention (GQA, Ainslie et al. 2023), which finds the sweet spot in between. We re-derive both from the vanilla formula, verify every number with our running model, and trace through the GQA paper’s key experimental results.
The Running Model
Same as every blog in this series:
- query heads
- layers
- fp16 (2 bytes per element)
All KV cache numbers are per-token unless stated otherwise.
Vanilla MHA: The Baseline to Beat
In standard multi-head attention, each head has its own query, key, and value projection:
where and . Each head computes attention independently:
The outputs are concatenated and projected:
Counting every parameter and byte
Let us be extremely precise about what MHA costs. We count three things: parameters, cache, and bandwidth.
Total attention parameters per layer. There are four categories of weight matrices:
- Query projections: matrices , each with parameters. Total: .
- Key projections: same count. Total: .
- Value projections: same count (). Total: .
- Output projection: . Total: .
Grand total per layer: parameters.
Numerical check: This is . Correct — MHA’s attention block has exactly parameters, independent of how those parameters are divided among heads.
KV parameters specifically. The KV projections are categories 2 and 3 above:
As a fraction of total attention parameters: . Exactly half of the attention parameters are in KV projections. This makes sense: Q and O each contribute parameters, and K+V together also contribute in our running model where and .
KV cache per token per layer. At inference, for each processed token, we store one key vector and one value vector per head:
Let us break this down further — element by element — to make sure we understand exactly what is stored:
- Head 1: (128 bytes) + (128 bytes) = 256 bytes
- Head 2: (128 bytes) + (128 bytes) = 256 bytes
- …
- Head 8: (128 bytes) + (128 bytes) = 256 bytes
Total: bytes per token per layer. Across layers:
KV memory bandwidth per step. At context length , generating the next token requires loading all cached K and V vectors from HBM (one full read of the entire cache per step):
At : bytes MB per step.
At : bytes GB per step.
These are the numbers to beat. Every variant in this blog reduces one or more of these costs.
Multi-Query Attention: The Extreme Case
Multi-Query Attention (MQA) was introduced by Shazeer (2019). The idea is the simplest possible attack on the KV cache: keep separate query heads, but use a single shared key head and a single shared value head.
Deriving MQA from MHA
Start from the MHA formula and make one change: instead of separate key matrices and separate value matrices , use a single shared and a single shared .
There is now one and one . Each query head still has its own :
Head computes attention using its own query against the shared key and value:
Every head uses the same and . The concatenation and output projection are unchanged:
Deriving the savings step by step
KV parameters per layer. We now have one and one instead of of each:
Compare to MHA: . The ratio:
MQA uses fewer KV parameters. The factor is exactly the number of heads, because we went from copies to 1 copy.
Total attention parameters per layer. Q projections are unchanged: . KV projections: (down from ). Output projection: (unchanged).
Total: .
Compare to MHA: . Ratio: . MQA has fewer attention parameters — a significant reduction, but less than the cache reduction because the Q and O matrices are unchanged.
KV cache per token per layer. Only one K vector and one V vector are cached (shared across all heads):
Let us spell out exactly what is stored per token per layer in MQA:
- Shared K: (128 bytes)
- Shared V: (128 bytes)
- Total: 256 bytes
Compare to MHA’s 2,048 bytes per token per layer. Ratio: . Exactly smaller.
Across layers: bytes KB/token.
Numerical check: MHA was 24 KB/token. . Correct.
Bandwidth per step at :
Compare to MHA’s 96 MB — an reduction. At A100 bandwidth of 2 TB/s:
Compare to MHA’s 48 microseconds. The KV cache loading time dropped from 48 s to 6 s. This is the primary source of MQA’s inference speedup.
Bandwidth per step at :
Compare to MHA’s 3 GB. Still smaller.
What MQA changes about the attention computation
This is the part that confuses almost everyone on first encounter. In MHA, each head’s attention scores are:
Head ‘s query is dotted with head ‘s keys . Each head operates in its own subspace.
In MQA:
Head ‘s query — which lives in a head-specific subspace defined by — is dotted with the shared key — which lives in a single subspace defined by the shared .
The attention scores are different per head (because each is different), so each head produces a different attention distribution . But the values being weighted are the same for all heads. So the output of each head is:
Different heads produce different weighted combinations of the same value vectors. In MHA, different heads produce different weighted combinations of different value vectors.
Concrete example. Suppose at position , head 1 assigns attention weight 0.8 to token 5 and 0.2 to token 12, while head 3 assigns weight 0.5 to each. In MHA:
The two outputs differ in both the weights and the values. In MQA:
The outputs differ only in the weights. Both heads are selecting from the same “library” of value representations. This is a meaningful capacity reduction — the model can no longer represent different information per head in the value space.
The cost of MQA: empirical evidence
The GQA paper (Ainslie et al., 2023, Table 1) quantifies the quality cost on T5-XXL:
| Model | Avg. quality | Inference time (s/sample) |
|---|---|---|
| MHA-XXL | 47.2 | 1.51 |
| MQA-XXL (uptrained) | 46.6 | 0.24 |
The quality drops by 0.6 points. The inference time drops by .
Is a 0.6-point quality drop acceptable? It depends on the application. For some tasks, 0.6 points is noise. For others — especially when the model is already near the state of the art — 0.6 points is the difference between best-in-class and second-tier.
The question becomes: can we find a middle ground that recovers most of the quality while keeping most of the speed?
Grouped-Query Attention: The Interpolation
Grouped-Query Attention (GQA) is the answer. It was introduced by Ainslie et al. (2023) as a generalization that places MHA and MQA at opposite ends of a single spectrum.
The idea
Divide the query heads into groups of equal size. Each group of query heads shares one key head and one value head. There are KV heads total.
Three boundary cases:
- : every group has exactly one query head → every query head has its own KV head → this is MHA
- : all query heads are in one group → all share one KV head → this is MQA
- : the intermediate case → this is GQA
Writing the formula explicitly
Let denote the number of KV groups. The number of query heads per group is (we require divides ). The heads are partitioned into consecutive groups:
- Group 1: query heads
- Group 2: query heads
- …
- Group : query heads
For our running model with and : group 1 has query heads , group 2 has query heads . Each group has query heads sharing one KV head.
For KV group , compute the shared key and value:
For query head belonging to group , compute:
The output is the same concatenation and projection as always:
Deriving the savings for general
KV parameters per layer. There are key matrices of size and value matrices of size :
With :
With :
Numerical check of the reduction factor for :
For : . Correct in both cases.
KV cache per token per layer. Each of the KV groups caches one K vector and one V vector:
Let us compute this for every possible in our model. Since must divide , the options are :
(MQA): bytes per layer
: bytes per layer
: bytes per layer
(MHA): bytes per layer
Across layers:
| bytes/token/layer | bytes/token (all layers) | KB/token | |
|---|---|---|---|
| 1 (MQA) | 256 | 3,072 | 3 |
| 2 | 512 | 6,144 | 6 |
| 4 | 1,024 | 12,288 | 12 |
| 8 (MHA) | 2,048 | 24,576 | 24 |
Numerical check: each row is exactly of the MHA row. , , . Correct.
The general reduction formula
Dividing the MHA cache by the GQA cache:
The factor appears in both numerator and denominator — it cancels. The factor of 2 (bytes per element) also cancels. What remains is:
This is the central equation. The reduction depends only on the ratio of query heads to KV groups. Not on , not on , not on , not on , not on the sequence length. Just .
Interpretation. This result says something powerful: regardless of model size, head dimension, or sequence length, GQA with groups reduces the KV cache by exactly . A model with 128 heads and 16 groups gets the same reduction as a model with 8 heads and 1 group (MQA). The formula is universal.
Bandwidth savings at every context length
The bandwidth per step for GQA at context length :
For our model with , at several context lengths:
| Context | MHA bandwidth | GQA-2 bandwidth | MQA bandwidth |
|---|---|---|---|
| 512 | 12 MB | 3 MB | 1.5 MB |
| 1,024 | 24 MB | 6 MB | 3 MB |
| 4,096 | 96 MB | 24 MB | 12 MB |
| 16,384 | 384 MB | 96 MB | 48 MB |
| 128,000 | 3,000 MB | 750 MB | 375 MB |
Numerical check for GQA-2 at : bytes MB. . Correct.
At : MB. . Correct.
Converting an MHA Checkpoint to GQA
A key practical contribution of the GQA paper is a recipe for converting existing MHA models to GQA without training from scratch. Pre-training from scratch costs millions of dollars. If we can convert an existing checkpoint, we save almost all of that cost.
The conversion problem
We have a trained MHA model with key projection matrices and value projection matrices . We want to produce key matrices and value matrices.
The query projections and the output projection remain unchanged. Only the KV projections change.
The mean-pooling conversion
The paper’s approach: for each group, average the original KV heads assigned to that group.
Step 1. Choose (must divide ). Partition heads into groups of size .
Step 2. For group , let be the set of original head indices in this group. Compute:
This is mean pooling — each element of the new weight matrix is the arithmetic mean of the corresponding elements from the original heads in the group. Matrix addition is elementwise: .
Tracing the conversion for our running model
In our model with and :
- Group 1 (): original heads
- Group 2 (): original heads
Each original has 32,768 parameters. The mean-pooled group key:
To see what happens at the element level, take element for row and column :
Suppose the four original values at position are . Then:
This is repeated for all elements.
Counting the resulting parameters. Before conversion: KV parameters. After conversion: KV parameters. Reduction: . Correct.
Why mean pooling works best
The paper (Ainslie et al., 2023, Figure 4) compares three conversion methods for T5-Large uptrained to MQA with :
| Method | Performance score |
|---|---|
| Mean pooling | |
| First head selection | |
| Random initialization |
Mean pooling averages all original heads in each group. It preserves the componentwise average signal across those heads, so it tends to retain the shared structure that multiple heads learned in common.
First head selection picks and discards . It preserves one head’s learned features perfectly but completely loses the other heads’ contributions. In our model with , selecting the first head discards 3 out of 4 heads’ worth of learned representations.
Random initialization creates with random weights drawn from an initialization distribution. It discards all learned information and relies entirely on uptraining to learn new representations from scratch.
The ranking makes intuitive sense: more information preserved → better starting point → less work for uptraining → higher final quality.
Numerical argument for why mean beats first. Consider a toy case where each head’s key projection adds a different “feature direction” to the representation. Head 1 projects onto direction , head 2 onto , etc. The mean pooling result retains a component along all four directions — attenuated by , but present. First-head selection keeps only and has zero component along . In this toy setup, the mean is a more balanced initialization because it preserves information from all four original directions rather than discarding three of them outright.
Uptraining: adapting to the new structure
After conversion, the model is pre-trained for an additional fraction of the original pre-training steps. The paper uses — just 5% of the original compute.
Why uptraining is necessary. After mean-pooling, the KV projections have changed. Head 1’s query was trained to work with head 1’s key — they learned complementary representations. Now head 1’s query must work with the group’s mean key . The dot products will produce different attention patterns than .
Let us trace this quantitatively. Before conversion, the attention score for head 1 between query position and key position is:
After conversion (before uptraining):
By the distributive law of matrix multiplication:
where is what head 1’s query would score against head ‘s key.
The post-conversion score is the average of what head 1’s query would have scored against all four original keys. This is a reasonable starting point — but it is not what the model was optimized for. The terms are “cross-head” interactions that the original model never trained on.
Uptraining allows to adapt. It learns to produce queries that give useful attention patterns when scored against the mean key projection. With 5% uptraining (), this adaptation is sufficient to recover nearly all quality.
Uptraining cost. The paper reports approximately 600 TPUv3 chip-days for uptraining T5-XXL at . The original T5-XXL pre-training cost was roughly 12,000 chip-days. So chip-days — consistent with the reported number. This is a one-time investment that converts an MHA model to a faster inference model.
How quality changes with uptraining proportion
The paper (Figure 5) shows performance as a function of for T5-XXL with MQA and GQA-8:
| MQA quality | GQA-8 quality | MHA baseline | |
|---|---|---|---|
| 0 (no uptraining) | ~53.5 | ~55.5 | 56.2 |
| 0.02 | ~55.5 | ~56.5 | 56.2 |
| 0.05 | ~56.5 | ~57.0 | 56.2 |
| 0.10 | ~57.0 | ~57.0 | 56.2 |
Two observations:
-
GQA starts higher than MQA even at . The mean-pooled GQA checkpoint is a better starting point because it has distinct KV heads rather than just 1, preserving more of the original model’s representational capacity.
-
Both reach diminishing returns around . Doubling the uptraining to gives marginal improvement. The 5% threshold appears to be sufficient for the query projections to adapt.
The Quality-Speed Tradeoff: Tracing the Paper’s Results
The GQA paper’s central result (Figure 3, Table 1) shows the Pareto frontier of quality vs. inference speed. We trace the key data points in detail.
Experimental setup
The paper uses T5 models (Raffel et al., 2020) implemented in JAX with Flax:
- T5-Large with standard MHA (baseline, small but fast)
- T5-XXL with MHA (baseline, large and slow)
- T5-XXL uptrained to MQA ()
- T5-XXL uptrained to GQA-8 (, i.e., 8 KV groups out of 64 query heads)
Evaluation on summarization tasks (CNN/Daily Mail, arXiv, PubMed, MediaSum, MultiNews), translation (WMT), and question answering (TriviaQA).
Main results
| Model | Attention | (s) | Average | CNN | arXiv | PubMed | MediaSum | MultiNews | WMT | TriviaQA |
|---|---|---|---|---|---|---|---|---|---|---|
| MHA-Large | MHA | 0.37 | 46.0 | 42.9 | 44.6 | 46.2 | 35.5 | 46.6 | 27.7 | 78.2 |
| MHA-XXL | MHA | 1.51 | 47.2 | 43.8 | 45.6 | 47.5 | 36.4 | 46.9 | 28.4 | 81.9 |
| MQA-XXL | MQA | 0.24 | 46.6 | 43.0 | 45.0 | 46.9 | 36.1 | 46.5 | 28.5 | 81.3 |
| GQA-8-XXL | GQA-8 | 0.28 | 47.1 | 43.5 | 45.4 | 47.7 | 36.3 | 47.2 | 28.4 | 81.6 |
Interpreting the numbers
GQA-8-XXL vs. MHA-XXL (the key comparison):
- Quality: 47.1 vs. 47.2, a drop of just 0.1 points
- Speed: 0.28s vs. 1.51s, a speedup
The quality difference is small on the reported tasks. On PubMed, GQA-8 actually outperforms MHA (47.7 vs. 47.5). On arXiv, GQA-8 loses 0.2 points (45.4 vs. 45.6). These per-task fluctuations are consistent with the average gap being small, though the paper does not report a formal significance test here.
MQA-XXL vs. MHA-XXL:
- Quality: 46.6 vs. 47.2, a drop of 0.6 points
- Speed: 0.24s vs. 1.51s, a speedup
MQA is faster than GQA-8 (0.24s vs. 0.28s) but loses more quality (0.6 vs. 0.1 points).
GQA-8-XXL vs. MHA-Large (the “free lunch” comparison):
- Quality: 47.1 vs. 46.0, GQA-8-XXL is 1.1 points better
- Speed: 0.28s vs. 0.37s, GQA-8-XXL is also faster
This comparison reveals GQA’s real power: a large model with GQA can be both higher quality and faster than a smaller model with full MHA. You get the quality of a large model at an inference cost below a smaller model. This helps explain why GQA became a common choice in production deployments of large models.
Why the speedup is and not
T5-XXL has query heads. GQA-8 uses KV groups, so the KV cache is smaller. But the end-to-end speedup is only .
We derived the formula in the previous blog:
The KV cache is not the only contributor to per-step time. Model weight loading, FFN computation, LayerNorm, and the output projection all contribute fixed costs that are the same for MHA and GQA. The term in both numerator and denominator pulls the speedup below .
At infinite context length, becomes negligible and the speedup approaches . The T5-XXL experiments use moderate context lengths (512–2048 tokens for most tasks), where the weight load is still significant relative to the KV cache.
The effect of number of groups (Figure 6)
The paper varies from 1 (MQA) to 64 (MHA) for GQA-XXL and measures inference time per sample:
| GQA groups | Time per sample (s) | Relative to MHA |
|---|---|---|
| 1 (MQA) | ~0.24 | faster |
| 4 | ~0.26 | faster |
| 8 | ~0.28 | faster |
| 16 | ~0.4 | faster |
| 32 | ~0.7 | faster |
| 64 (MHA) | ~1.51 |
The inference time increases roughly linearly with for small and then steeply as approaches . Going from 1 to 8 groups adds only 0.04s. Going from 8 to 64 groups adds 1.23s.
This non-linearity arises because the KV cache load is , but the fixed costs (weights, FFN) create a floor below which the total time cannot drop regardless of . At small , the fixed costs dominate and changes in have little effect. At large , the KV cache dominates and changes in are proportionally expensive.
Why GQA Preserves Quality
This is the part that confuses almost everyone. Reducing KV heads from 64 to 8 is an reduction in the key-value capacity. Why doesn’t quality collapse?
Head redundancy
Research on attention head pruning has consistently found that many heads are redundant:
- Voita et al. (2019) showed that in a 6-layer, 8-head Transformer, only 2–3 heads per layer are “important” for translation quality. The rest can be pruned with minimal quality loss.
- Michel et al. (2019) demonstrated that for BERT, removing 20–40% of heads has negligible effect on downstream task performance.
The implication: in MHA with 64 heads, many heads learn overlapping or nearly identical key-value representations. When GQA groups these heads and replaces their individual K/V with a shared K/V, the information loss is small because the individual heads were not contributing unique information.
What the query heads learn to do
In GQA, the query heads within each group share one K and V. But each query head still has its own . The query projections are free to learn different “questions” to ask of the shared key-value representation.
Think of it as a library analogy. In MHA, each head has its own library (K and V) and its own search query (Q). In GQA, groups of heads share a library but each head still has its own search query. If the individual libraries were mostly redundant copies of the same books, consolidating them into one shared library per group loses little — the search queries can still find different information by asking different questions.
The key insight: the diversity in attention comes more from the queries than from the keys and values. Different heads attend to different positions primarily because their query projections differ, not because their key projections differ. GQA preserves all query diversity while reducing key-value redundancy.
Mathematical argument
Consider two query heads and in the same group, sharing key . Their attention distributions are:
Even though is the same, the attention distributions differ because . The query matrices project the input into different subspaces, producing different attention scores against the same keys.
The two heads will attend to different positions as long as and are sufficiently different. Since these query projections are not constrained to be similar (they are separate learned parameters), the model retains the ability to attend to multiple different features simultaneously — as many as there are query heads.
Deriving the Inference Time Improvement
We can predict the speedup from GQA analytically.
The speedup formula
Per-step inference time is dominated by memory bandwidth. The total bytes loaded per step:
For MHA:
For GQA with groups:
The speedup ratio:
Limiting behavior
Short context (). Both numerator and denominator approach :
No speedup. The model spends all its time loading weights, which are the same for MHA and GQA.
Long context (). The term becomes negligible:
The , , 2, and all cancel:
The maximum achievable speedup is exactly — the same as the cache reduction factor.
Numerical verification at every context length
Using our running model ( MB, , ):
At :
- MB
- MB
At short context, almost no speedup.
At :
- MB
- MB
At :
- MB
- MB
At :
- MB
- MB
At :
- MB
- MB
Approaching the theoretical maximum of .
| Context | Speedup | % of theoretical max () |
|---|---|---|
| 512 | 28% | |
| 2,048 | 36% | |
| 4,096 | 44% | |
| 16,384 | 68% | |
| 128,000 | 93% |
The speedup grows monotonically with context length, approaching asymptotically. At 128K tokens, we achieve 93% of the theoretical maximum. GQA’s value increases with context length — precisely when inference is most expensive.
GQA and Related KV-Head Choices in Modern Architectures
Since the GQA paper, modern language models have explored different points on the MHA-GQA-MQA spectrum. We trace a few concrete choices made by major architectures.
LLaMA 2 70B (Meta, 2023): query heads, KV groups. Cache reduction: . At and , the MHA cache would be MB/token. With GQA-8: KB/token. At 128K tokens: GB instead of 320 GB.
Mistral 7B (Mistral AI, 2023): query heads, KV groups. Cache reduction: . Combined with sliding window attention (), the cache is bounded at bytes regardless of sequence length. This is Lever 1 (GQA) and Lever 3 (sliding window) composed.
Gemma (Google, 2024): uses different KV-head choices by model size rather than one uniform GQA setting. Gemma 2B uses MQA (), while Gemma 7B uses full MHA (). This is a useful reminder that modern models do not all choose the same point on the MHA-GQA-MQA spectrum; the right choice depends on size, quality targets, and serving constraints.
Across these examples, architects are clearly optimizing the same tradeoff between KV-cache size and quality, even when they land on different points of the spectrum. LLaMA 2 70B and Mistral 7B both use GQA, while Gemma spans MQA and MHA across sizes. The broader pattern is that KV-head sharing became a central deployment design choice after GQA made the tradeoff explicit.
The Unified View: MHA, GQA, MQA as One Formula
All three variants — MHA, GQA, and MQA — are a single attention mechanism parameterized by :
where for query head with group index :
The only thing that varies is . Everything else — the query projections, the output projection, the softmax, the scaling — is identical.
| Name | KV heads | KV cache per token | Query heads per KV head | |
|---|---|---|---|---|
| MHA | unique | 1 | ||
| GQA- | shared | |||
| MQA | 1 shared |
There is no structural difference between these three methods. They are the same formula with different values of one integer parameter. GQA is the general family. MHA () and MQA () are boundary cases.
This unified view makes clear that choosing is a single design decision with a clean tradeoff: smaller → smaller cache → faster inference → potentially lower quality. The engineering challenge is finding the that maximizes inference speed while keeping quality within tolerance. The GQA paper showed this exists and is easy to find.
Summary
The KV cache during autoregressive inference costs bytes per token. Multi-Query Attention (MQA) collapses all KV heads to 1, reducing the cache by at the cost of a measurable quality drop (0.6 points on T5-XXL). Grouped-Query Attention (GQA) generalizes this to KV groups, each shared by query heads, reducing the cache by exactly . The GQA paper showed that with on T5-XXL, quality is within 0.1 points of full MHA while inference is faster. Existing MHA checkpoints can be converted to GQA by mean-pooling KV heads within each group and uptraining for just 5% of the original pre-training compute. The inference speedup approaches at long context lengths and is most impactful exactly when inference is most expensive. MHA, GQA, and MQA are not three separate inventions — they are a single formula parameterized by the number of KV groups .
Previous: The KV Bottleneck Explained Deeply
Next: Mathematical Prerequisites for DeepSeek-V2
Enjoyed this post?
Subscribe to get notified when I publish new posts. No spam, unsubscribe anytime.