AI State of the Art
SOTA/Advanced Attention Mechanisms/24 min
Section 73

Grouped Query Attention (GQA)

Listen as a podcast →

The all-or-nothing problem

MQA (Multi-Query Attention, previous lesson) is great for efficiency, but sharing a single K/V pair across all heads might be too radical. It's like having one waiter for an entire restaurant, quick to coordinate, but the service suffers when tables have different needs.

MHA (Multi-Head Attention, the standard mechanism) is perfect for quality, but its gigantic KV cache, the memory of keys and values of every token seen so far, re-read at every new token (why K and V are cached, and Q never is) limits what you can do in practice. Each head has its own set of keys and values, it's like a dedicated waiter per table, impeccable service, but the payroll explodes.

What if you didn't have to choose? What if you could have as many K/V groups as you want, from 1 (MQA) to H (MHA), including any value in between?

That's Grouped Query Attention (GQA), introduced by the Google team, and now adopted by virtually all modern open-source LLMs.

GQA: Training Generalized Multi-Query Models from Multi-Head Checkpoints

The GQA principle

Grouping the heads

Instead of one K/V pair per head (MHA) or one K/V pair for everyone (MQA), GQA creates G groups, each group sharing a K/V pair:

Qi=X⋅WiQ(DISTINCT: each head has its own query)Q_i = X \cdot W_i^Q \quad \text{(DISTINCT: each head has its own query)} Kg=X⋅WgK(G projections: one per group)K_g = X \cdot W_g^K \quad \text{(G projections: one per group)} Vg=X⋅WgV(G projections: one per group)V_g = X \cdot W_g^V \quad \text{(G projections: one per group)}

Reading these three lines: each head ii keeps its own query matrix WiQW_i^Q (a learned parameter), but there are now only G key matrices WgKW_g^K and G value matrices WgVW_g^V, one per group. The H heads are divided into G groups of H/G heads each. All heads within the same group therefore use the same K and V, but keep distinct queries. Each head asks its own "question" to the context, but the context is represented by a reduced number of K/V perspectives.

Note in passing that saying "the heads of a group share the matrix WgKW_g^K" or "they share the keys KgK_g" is saying the same thing: one matrix applied to one input gives one result. The distinction that matters is elsewhere: the matrix is a learned parameter with a fixed size; the keys and values are computed results on the current text, piling up in the cache with every token. That cache (and it alone) is what GQA shrinks.

Diagram comparing Multi-head Attention and Grouped-query Attention over 6 heads: in MHA each head has its own key/value pair, while in GQA the 6 query heads are split into 3 groups of 2, each group sharing a single key/value pair.
Grouping, made visual. On the left, MHA: 6 heads, 6 K/V pairs. On the right, GQA with 3 groups: heads 1-2, 3-4 and 5-6 each keep their own query but share their group K/V pair. The group size is simply H divided by G, here 6 over 3 = 2.Source : Sebastian Raschka, LLMs from Scratch

The MHA -> GQA -> MQA continuum

GQA elegantly unifies MHA and MQA as extreme cases of the same mechanism:

  • G = H: each group contains exactly one head -> this is standard MHA
  • G = 1: a single group contains all heads -> this is MQA
  • 1 < G < H: intermediate configuration -> this is GQA

You turn a single knob (the number of groups G) to navigate the entire quality-efficiency spectrum.

Figure from the GQA paper lining up three configurations over 8 query heads: Multi-head with 8 key/value pairs, Grouped-query with 4 pairs each shared by 2 heads, and Multi-query with a single key/value pair for all 8 heads.
The original paper figure puts the three regimes side by side, with the same number of queries (8) in all three. Only the key and value row changes: 8 pairs in MHA, 4 in GQA, 1 in MQA. GQA is nothing more than the slider between those two extremes.Source : GQA paper, Ainslie et al. (figure 2)
The most common configuration

The dominant configuration in modern models is G = H/8, that is, 8 groups for 64 heads (each group contains 8 heads sharing the same K/V). The KV cache is reduced by a factor of 8 compared to MHA, while maintaining 8 distinct K/V sets to capture different aspects of the context. This is the choice of LLaMA 2 70B, Mistral 7B, and many other reference models.

KV cache reduction: the real numbers

For a model with H = 64 heads, d_k = 128, and L context tokens:

ConfigurationGKV cache per layer per tokenReduction vs MHA
MHA642 x 64 x 128 = 16,384 elements1x
GQA-882 x 8 x 128 = 2,048 elements8x
GQA-442 x 4 x 128 = 1,024 elements16x
MQA12 x 1 x 128 = 256 elements64x

In the middle column, the factor of 2 counts the two objects stored per K/V head and per token: the key and the value (never the query, which is used only once).

Let's put this in concrete perspective by finishing the arithmetic: 16,384 elements × 128,000 tokens × 80 layers × 2 bytes ≈ 335 GB of GPU memory for the MHA cache of a single request. With GQA-8, the same arithmetic gives ~42 GB. The difference (nearly 300 GB) is several 80 GB graphics cards saved, a direct impact on deployment cost.

How to choose G?

In practice, G = 8 offers an excellent balance for large models: 8x KV cache reduction with nearly imperceptible quality loss on benchmarks. For very memory-constrained deployments (mobile, edge), G = 4 or G = 2 are viable with moderate degradation. G = 1 (MQA) remains useful for the most extreme cases where every megabyte counts. The rule of thumb: start with G = 8 and reduce only if memory requires it.

Converting MHA -> GQA: reusing existing models

One of GQA's most important practical advantages: you can convert an existing MHA model to GQA without retraining from scratch. This is crucial when you've invested millions of dollars in an MHA training run.

The uptrained conversion process

Uptrained conversion refers to converting an already-trained MHA model to GQA, followed by a short retraining, you don't start from scratch.

  1. Group the heads: distribute the H heads into G groups of consecutive heads
  2. Average the K/V: within each group, compute the average of the K and V weight matrices of the H/G constituent heads
  3. Retrain briefly: continue training the converted model at ~5% of the original pre-training compute to recover performance
Diagram of the conversion from a multi-head to a multi-query model: the key projection matrices K_1, K_2 through K_H, each of size d_h by d_model, feed a Mean Pool block that outputs a single projection matrix K_MQ of the same size.
Averaging as the authors draw it. The H key projection matrices of the already-trained model are mean pooled into a single matrix with the shape of one head projection. The same treatment is applied to the values, group by group in the GQA case.Source : GQA paper, Ainslie et al. (figure 1)
Conversion results

In the paper, the conversion is done on Google's T5-XXL model (not on LLaMA): converted to GQA-8 and then retrained at 5% of the original compute, it recovers quality close to the original MHA model, at inference speed close to MQA's. The return on investment is enormous: a fraction of the training run versus months of full training.

Averaging vs selection

The paper compares three ways of forming a group's K/V:

  • Averaging: the group's K projection is the average of the K projections of the constituent heads. This approach preserves information from all original heads and gives the best results.
  • Selection: keep the first head of the group, discard the others. Simpler, slightly worse.
  • Random reinitialization: start from fresh matrices. Clearly worse, the knowledge in the original heads is worth keeping.

The industry standard: who uses GQA?

GQA has become the de facto standard for open-source LLMs since mid-2023. The list speaks for itself:

  • LLaMA 2 70B (Meta): first major model to popularize GQA (G = 8 for H = 64)
  • LLaMA 3 (Meta): GQA across the entire family, from 8B to 405B
  • Mistral 7B: GQA with G = 8 for H = 32 (8 K/V heads for 32 query heads, i.e. groups of 4)
  • Gemma (Google): GQA across all sizes
  • Qwen 2 (Alibaba): GQA as the standard configuration
  • Command R (Cohere): GQA for inference efficiency
Why this massive adoption?

GQA is the first mechanism to offer a quality-efficiency trade-off good enough to be adopted without hesitation by teams targeting top performance. MQA was too aggressive, the quality loss became visible on demanding tasks. GQA-8 is practically indistinguishable from MHA on benchmarks, while dividing the KV cache by 8. It's the rare case where you can have your cake and (almost) eat it too.

Why does GQA work so well?

K/V redundancy

The usual intuition: the keys and values produced by different heads overlap substantially, they capture essentially the same semantic information with slight variations. Grouping them by averaging therefore only destroys a small fraction of useful information. This is consistent with an observation made in early studies of multi-head attention: entire heads can be removed from a trained model without a collapse in performance.

Queries carry the diversity

The real diversity of attention patterns comes from the queries: different heads ask different questions about the same content. One head asks "what's the grammatical subject?", another "what's the main verb?", a third "is there a cause-and-effect relationship?". These questions remain entirely distinct per head in GQA, only the K/V "dictionary" they search is shared within a group.

Sufficient residual capacity

With G = 8 K/V groups, the model still has 8 distinct representations of the context. That's enough to capture the different aspects needed: syntax, semantics, coreference, logical relationships, etc. The real loss only becomes noticeable below G = 4, on tasks that require multiple simultaneous perspectives on the context.

Combinations with other optimizations

GQA isn't an isolated technique, it combines naturally with other optimizations, and the gains multiply:

GQA + Flash Attention: perfectly compatible. Reducing the number of K/V heads reduces the size of manipulated tensors, which amplifies Flash Attention's gains by reducing memory transfers.

GQA + KV cache quantization: quantizing the KV cache in INT8 or INT4 further multiplies the reduction. The two techniques are orthogonal: GQA reduces the number of K/V groups, quantization reduces the precision of each value. Together, you can achieve 32x or more reduction (8 from GQA-8 × 4 from INT4).

GQA + Sliding Window Attention: Mistral combines GQA with a sliding context window. Double lever: fewer K/V groups and K/V history truncated to the window size.

Beware of very small G

With G = 1 or G = 2, the loss of K/V diversity can become significant, particularly for tasks requiring fine attention on multiple distinct aspects of the context simultaneously, complex multi-step reasoning, questions about long documents with many varied details, or translation between structurally very different languages.

Comparative performance

The paper's measurements on converted T5-XXL sum up as follows:

ModelAttentionQualityInference speed
T5-XXL (MHA)MHAReferenceSlowest
T5-XXL -> GQA-8GQA-8Close to MHAClose to MQA
T5-XXL -> MQAMQABehind on several tasksFastest

GQA-8's trade-off is crystal clear: a barely measurable quality loss for speed nearly equal to MQA's. For the vast majority of applications, that's a highly profitable exchange, you serve far more users with the same hardware.

Conclusion

Grouped Query Attention represents a pragmatic and decisive advance for LLM inference optimization. By offering a continuum between MHA (maximum quality) and MQA (maximum efficiency), it allows practitioners to choose exactly the optimal trade-off for their use case. Its near-universal adoption confirms that GQA has become a standard component of every modern Transformer architecture, as fundamental as layer normalization or residual connections.

Check your understanding0 / 5

1. In GQA you set the number of groups G. What happens at the two ends of the dial?

2. A group's matrix W_K versus the keys K_g computed from it: what is the difference, and which of the two does GQA shrink?

3. To convert an already-trained MHA model to GQA, which recipe gives the best results?

4. Why can K/V be shared within a group without a large quality loss?

5. When does GQA's quality loss become truly noticeable?