Grouped-Query Attention (GQA) and Multi-Query Attention (MQA): Mathematical Foundations, Arithmetic Intensity, and KV-Cache Scaling Mechanics
Autoregressive large language model inference is governed by a fundamental hardware asymmetry. During the initial prompt processing phase (prefill), computation is compute-bound because matrix multiplications process entire sequences in parallel. During sequential token generation (decoding), execution becomes strictly memory-bandwidth bound. For each generated token, the accelerator must transfer the entire model weight matrix and the accumulated Key-Value (KV) cache from High Bandwidth Memory (HBM) to on-chip SRAM to execute a single token step.
In standard Multi-Head Attention (MHA), introduced by Vaswani et al. (2017), the number of key-value projection heads equals the number of query heads (). As sequence lengths expand into tens of thousands of tokens and concurrent batch sizes scale, the memory footprint and bandwidth consumption of the KV cache dominate total serving costs.
To resolve this memory bottleneck, two architectural variants alter the projection dimensionality of keys and values:
- Multi-Query Attention (MQA), introduced by Shazeer (2019), which collapses the key and value heads into a single shared head () across all query heads.
- Grouped-Query Attention (GQA), introduced by Ainslie et al. (2023), which generalizes MQA by partitioning query heads into disjoint groups, with each group sharing a single key-value head pair ().
Modern open-weight architectures, including Llama 2 70B and Llama 3, Mistral 7B, and Gemma 2, adopt GQA as the default attention mechanism. This post provides a rigorous breakdown of the memory dynamics, mathematical formulation, hardware roofline mechanics, checkpoint up-training procedures, and serving trade-offs between MHA, MQA, and GQA.
1. The Hardware Bottleneck: Arithmetic Intensity and Memory Bandwidth
To understand why key-value head reduction is essential, consider the operational mechanics of autoregressive decoding on modern GPU hardware such as the NVIDIA H100 SXM5 (3.35 TB/s HBM3 memory bandwidth, 989 TFLOPS dense FP16/BF16 Tensor Core compute).
Arithmetic Intensity in Autoregressive Decoding
The arithmetic intensity of an operation is defined as the ratio of floating-point operations (FLOPs) performed to bytes transferred from global memory:
According to the roofline model analyzed by Pope et al. (2022), a workload is memory-bandwidth bound if its arithmetic intensity is lower than the hardware operational intensity balance point . For an H100 SXM5 GPU:
During single-batch decoding () of a single token:
- Loading model weights requires reading bytes (at 16-bit precision), where is the parameter count.
- Computing the forward pass for a single token requires approximately FLOPs.
- The arithmetic intensity of linear projections is , which is over 200 times lower than .
As a result, the Tensor Cores spend more than 99% of execution cycles stalled waiting for memory transfers from HBM.
KV Cache Memory Footprint
In addition to static model weights, attention requires caching the key and value vectors of all past tokens in the sequence to prevent redundant recomputation. For a model with layers, hidden dimension , sequence length , batch size , and number of key-value heads each with head dimension , the total memory required for the KV cache in bytes (using 16-bit floats, 2 bytes per element) is:
The leading factor of 2 accounts for storing both Keys and Values, and the second factor of 2 accounts for FP16/BF16 precision.
+-------------------------------------------------------------------------------+
| KV CACHE SCALING REGIMES (FP16) |
| Model: 70B (L=80, d_model=8192, H_Q=64, d_k=128) |
+-------------------+--------------------+------------------+-------------------+
| Sequence Length | MHA (H_KV = 64) | GQA-8 (H_KV = 8) | MQA (H_KV = 1) |
+-------------------+--------------------+------------------+-------------------+
| 4,096 tokens | 10.74 GB / stream | 1.34 GB / stream | 0.17 GB / stream |
| 32,768 tokens | 85.90 GB / stream | 10.74 GB / stream| 1.34 GB / stream |
| 131,072 tokens | 343.60 GB / stream | 42.95 GB / stream| 5.37 GB / stream |
+-------------------+--------------------+------------------+-------------------+Under Multi-Head Attention, a single 128k context stream for a 70B parameter model requires 343.6 GB of VRAM solely for its KV cache, exceeding the total physical memory capacity of four 80GB H100 GPUs. GQA with 8 groups reduces this cache requirement by an exact factor of 8 (42.95 GB), enabling concurrent serving of long-context requests on a single multi-GPU node.
2. Mathematical Formulation: MHA vs. MQA vs. GQA
Let denote the input activation tensor, where is the batch size, is the sequence length, and is the model hidden dimension. Let be the number of query heads, and be the per-head dimension.

Multi-Head Attention (MHA)
In standard Multi-Head Attention, independent linear transformations project the input into query heads, key heads, and value heads:
The projections produce:
For each head , the scaled dot-product attention is computed independently:
where is the causal attention mask. The output projection combines all heads:
Multi-Query Attention (MQA)
Multi-Query Attention, proposed by Shazeer (2019), retains distinct query heads but restricts the key and value projections to a single shared head:
The resulting key and value tensors have no head dimension (or equivalently, a head dimension of 1):
During attention calculation, and are broadcast across all query heads:
While MQA slashes memory bandwidth consumption during decoding by a factor of , it can cause capacity degradation and training instability on complex reasoning and retrieval tasks due to the extreme bottleneck of compressing all token relationships into one key-value subspace.
Grouped-Query Attention (GQA)
Grouped-Query Attention, formulated by Ainslie et al. (2023), interpolates between MHA and MQA. It divides the query heads into disjoint groups, where :
- Group size: query heads per group.
- Number of key and value heads: .
- When , GQA reduces exactly to MHA.
- When , GQA reduces exactly to MQA.
The projection weights have shapes:
Let denote the group index corresponding to query head . The attention computation for query head pairs with the shared key and value head of its group :
In matrix contraction terms, let . In tensor operations, and are expanded to match using a repeat-interleave transformation:
The attention operation is then computed efficiently across all query heads:
3. Checkpoint Up-Training: Converting MHA to GQA
Training a large language model from scratch requires millions of GPU hours. A significant contribution of Ainslie et al. (2023) was demonstrating that existing pre-trained MHA checkpoints can be converted to GQA architectures via up-training using only 5% of original pre-training compute.
+-------------------------------------------------------------------------------+
| MHA TO GQA CONVERSION PIPELINE |
| |
| Pre-trained MHA Weights |
| W_K: [d_model, H_Q * d_k] ---> Partition into G groups of R heads |
| |
| Mean Pooling Projection: |
| For group g in {1 ... G}: |
| W_K_pooled[g] = (1 / R) * Sum_{h in Group_g} W_K[h] |
| W_V_pooled[g] = (1 / R) * Sum_{h in Group_g} W_V[h] |
| |
| Resulting GQA Weights: |
| W_K_gqa: [d_model, G * d_k] |
| W_V_gqa: [d_model, G * d_k] |
| |
| Up-Training: |
| Fine-tune converted model on 5% of original pre-training token budget |
+-------------------------------------------------------------------------------+Weight Pooling Initialization
To construct the initial GQA projection matrices and from pre-trained MHA matrices and :
- Mean Pooling: The key projection weights belonging to each group are averaged:
- First-Head Selection (Alternative): Selecting only the first head of each group (). Empirical evaluations show that mean pooling consistently yields lower initial perplexity and faster convergence during up-training compared to single-head selection.
Convergence Dynamics
During up-training on the C4 dataset, Ainslie et al. observed the following convergence patterns:
- Up-trained GQA with (GQA-8) recovered 99.7% of the original MHA model's benchmark performance across downstream tasks (including CNN/DailyMail, MNLI, and SQuAD) within 5% of original pre-training steps.
- Direct MQA conversion () exhibited a larger initial perplexity spike and required longer adaptation to approach MHA performance.
- GQA-8 achieved identical generation throughput to MQA while matching the task accuracy of full MHA.
4. Serving Dynamics and Tensor Parallelism
Deploying GQA models in production inference systems introduces specific constraints and speedups across multi-GPU environments.
Tensor Parallelism (TP) Head Partitioning
In distributed serving frameworks like vLLM and TensorRT-LLM, multi-head attention is partitioned across GPUs via Megatron-LM tensor parallelism:
- The query projection weight is split column-wise: each GPU holds query heads.
- The key and value projection weights are split column-wise: each GPU holds key-value heads.
- The output projection weight is split row-wise, followed by an all-reduce collective communication step.
For tensor parallelism to function without head duplication:
For example, Llama 3 70B uses and . It partitions evenly across GPUs. On an 8-GPU node (), each GPU hosts exactly query heads and key-value head, operating locally as an MQA structure without inter-GPU KV cache communication.
If (for instance, running a model with across 8 GPUs), the key-value heads must be broadcast or duplicated across GPUs within each tensor parallel group, increasing redundant memory allocation.
+-------------------------------------------------------------------------------+
| TENSOR PARALLEL PARTITIONING (Llama 3 70B on TP=8) |
| |
| GPU 0: Q_heads [0..7] --> KV_head 0 (Local GQA-8 -> MQA behavior) |
| GPU 1: Q_heads [8..15] --> KV_head 1 |
| GPU 2: Q_heads [16..23] --> KV_head 2 |
| GPU 3: Q_heads [24..31] --> KV_head 3 |
| GPU 4: Q_heads [32..39] --> KV_head 4 |
| GPU 5: Q_heads [40..47] --> KV_head 5 |
| GPU 6: Q_heads [48..55] --> KV_head 6 |
| GPU 7: Q_heads [56..63] --> KV_head 7 |
| |
| All-Reduce sum over W_O row-slices yields identical final output. |
+-------------------------------------------------------------------------------+Rotary Position Embeddings (RoPE) Interaction
When applying Rotary Position Embeddings (Su et al., 2021), rotational transformations are applied to and representations prior to dot-product evaluation:
In GQA:
- RoPE is applied to each of the query heads: .
- RoPE is applied once to each of the key heads: .
- The query head and the transformed group key preserve the exact relative positional distance property:
Because RoPE operates per-head on vectors of dimension , the mathematical guarantees of relative position encoding remain identical in GQA and MHA.
5. Architectural Comparison and Empirical Trade-offs
The table below summarizes the architectural configurations and serving characteristics across leading open-weight language models.
+--------------------------------------------------------------------------------------------------+
| ATTENTION ARCHITECTURES IN PRODUCTION |
+----------------------+--------------------+---------+----------+----------+----------------------+
| Model | Attention Type | H_Q | H_KV | Group (R)| KV Cache Compression |
+----------------------+--------------------+---------+----------+----------+----------------------+
| Llama 1 (65B) | MHA | 64 | 64 | 1 | 1.0x (Baseline) |
| Llama 2 (70B) | GQA | 64 | 8 | 8 | 8.0x reduction |
| Llama 3 (8B) | GQA | 32 | 8 | 4 | 4.0x reduction |
| Llama 3 (70B) | GQA | 64 | 8 | 8 | 8.0x reduction |
| Mistral 7B | GQA | 32 | 8 | 4 | 4.0x reduction |
| Mixtral 8x7B | GQA | 32 | 8 | 4 | 4.0x reduction |
| Gemma 2 (9B / 27B) | GQA | 16 / 32 | 8 / 16 | 2 | 2.0x reduction |
| Falcon 40B | MQA | 64 | 1 | 64 | 64.0x reduction |
+----------------------+--------------------+---------+----------+----------+----------------------+Empirical Serving Performance
According to evaluations on NVIDIA A100/H100 clusters running vLLM:
- Serving Throughput: On long-context workloads (32k sequence lengths), GQA-8 achieves up to 4.5x higher token throughput compared to MHA by fitting larger concurrent batch sizes into GPU memory.
- Time-to-First-Token (TTFT): TTFT is largely compute-bound (prefill) and shows minimal variation between MHA and GQA, since total GEMM compute remains comparable.
- Time-Per-Output-Token (TPOT): In memory-bound generation regimes with batch sizes , TPOT decreases by 3x to 6x under GQA due to the substantial reduction in HBM bandwidth saturation per decode step.
6. Summary
Grouped-Query Attention resolves the central tension between model quality and serving efficiency in autoregressive Transformers:
- Memory Bandwidth Amortization: Reducing key-value projection heads directly matches the memory-bound constraints of the GPU roofline model during token decoding.
- Tunable Interpolation: Setting allows system designers to select the optimal operating point between MHA representation capacity () and MQA bandwidth minimization ().
- Hardware Alignment: Choosing provides an 8x reduction in KV cache memory footprint with no measurable loss in perplexity or task performance, establishing GQA as the standard attention architecture for modern foundation models.
Sources
- Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023)
- Attention Is All You Need (Vaswani et al., 2017)
- Efficiently Scaling Transformer Inference (Pope et al., 2022)
- Llama 2: Open Foundation and Fine-Tuned Chat Models (Touvron et al., 2023)
- Mistral 7B (Jiang et al., 2023)
- Gemma 2: Improving Open Language Models at a Practical Size (Gemma Team, 2024)
- RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)
- vLLM: Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023)



