Grouped-Query Attention (GQA) and Multi-Query Attention (MQA): Mathematical Foundations, Arithmetic Intensity, and KV-Cache Scaling Mechanics

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 gen

10 min
Grouped-Query Attention (GQA) and Multi-Query Attention (MQA): Mathematical Foundations, Arithmetic Intensity, and KV-Cache Scaling Mechanics

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 (HQ=HK=HV=HH_Q = H_K = H_V = H). 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:

  1. Multi-Query Attention (MQA), introduced by Shazeer (2019), which collapses the key and value heads into a single shared head (HK=HV=1H_K = H_V = 1) across all query heads.
  2. Grouped-Query Attention (GQA), introduced by Ainslie et al. (2023), which generalizes MQA by partitioning HQH_Q query heads into GG disjoint groups, with each group sharing a single key-value head pair (HK=HV=GH_K = H_V = G).

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 II of an operation is defined as the ratio of floating-point operations (FLOPs) performed to bytes transferred from global memory:

I=FLOPsBytes Transferred[FLOPByte]I = \frac{\text{FLOPs}}{\text{Bytes Transferred}} \quad \left[\frac{\text{FLOP}}{\text{Byte}}\right]

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 Isat=Peak FLOPSPeak Memory BandwidthI_{\text{sat}} = \frac{\text{Peak FLOPS}}{\text{Peak Memory Bandwidth}}. For an H100 SXM5 GPU:

Isat=989×1012 FLOP/s3.35×1012 Byte/s295.2 FLOP/ByteI_{\text{sat}} = \frac{989 \times 10^{12} \text{ FLOP/s}}{3.35 \times 10^{12} \text{ Byte/s}} \approx 295.2 \text{ FLOP/Byte}

During single-batch decoding (b=1b = 1) of a single token:

  • Loading model weights WW requires reading 2×P2 \times P bytes (at 16-bit precision), where PP is the parameter count.
  • Computing the forward pass for a single token requires approximately 2×P2 \times P FLOPs.
  • The arithmetic intensity of linear projections is I2P2P=1 FLOP/ByteI \approx \frac{2P}{2P} = 1 \text{ FLOP/Byte}, which is over 200 times lower than IsatI_{\text{sat}}.

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 O(s2)O(s^2) recomputation. For a model with LL layers, hidden dimension dmodeld_{\text{model}}, sequence length ss, batch size bb, and number of key-value heads HKVH_{KV} each with head dimension dk=dmodelHQd_k = \frac{d_{\text{model}}}{H_Q}, the total memory required for the KV cache in bytes (using 16-bit floats, 2 bytes per element) is:

MemoryKV=2×2×b×s×L×HKV×dkbytes\text{Memory}_{\text{KV}} = 2 \times 2 \times b \times s \times L \times H_{KV} \times d_k \quad \text{bytes}

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 xRb×s×dmodelx \in \mathbb{R}^{b \times s \times d_{\text{model}}} denote the input activation tensor, where bb is the batch size, ss is the sequence length, and dmodeld_{\text{model}} is the model hidden dimension. Let HQH_Q be the number of query heads, and dk=dv=dmodelHQd_k = d_v = \frac{d_{\text{model}}}{H_Q} be the per-head dimension.

Comparison of Multi-Head Attention, Grouped-Query Attention, and Multi-Query Attention architectures

Multi-Head Attention (MHA)

In standard Multi-Head Attention, independent linear transformations project the input into HQH_Q query heads, HQH_Q key heads, and HQH_Q value heads:

WQRdmodel×(HQdk),WKRdmodel×(HQdk),WVRdmodel×(HQdk)W_Q \in \mathbb{R}^{d_{\text{model}} \times (H_Q \cdot d_k)}, \quad W_K \in \mathbb{R}^{d_{\text{model}} \times (H_Q \cdot d_k)}, \quad W_V \in \mathbb{R}^{d_{\text{model}} \times (H_Q \cdot d_k)}

The projections produce:

Q=xWQRb×s×HQ×dkQ = x W_Q \in \mathbb{R}^{b \times s \times H_Q \times d_k} K=xWKRb×s×HQ×dkK = x W_K \in \mathbb{R}^{b \times s \times H_Q \times d_k} V=xWVRb×s×HQ×dkV = x W_V \in \mathbb{R}^{b \times s \times H_Q \times d_k}

For each head i{1,,HQ}i \in \{1, \dots, H_Q\}, the scaled dot-product attention is computed independently:

Headi=softmax(QiKiTdk+M)Vi\text{Head}_i = \text{softmax}\left(\frac{Q_i K_i^T}{\sqrt{d_k}} + M\right) V_i

where MRs×sM \in \mathbb{R}^{s \times s} is the causal attention mask. The output projection combines all heads:

MHA(x)=Concat(Head1,,HeadHQ)WO,WOR(HQdk)×dmodel\text{MHA}(x) = \text{Concat}(\text{Head}_1, \dots, \text{Head}_{H_Q}) W_O, \quad W_O \in \mathbb{R}^{(H_Q \cdot d_k) \times d_{\text{model}}}

Multi-Query Attention (MQA)

Multi-Query Attention, proposed by Shazeer (2019), retains HQH_Q distinct query heads but restricts the key and value projections to a single shared head:

WQRdmodel×(HQdk),WKRdmodel×dk,WVRdmodel×dkW_Q \in \mathbb{R}^{d_{\text{model}} \times (H_Q \cdot d_k)}, \quad W_K \in \mathbb{R}^{d_{\text{model}} \times d_k}, \quad W_V \in \mathbb{R}^{d_{\text{model}} \times d_k}

The resulting key and value tensors have no head dimension (or equivalently, a head dimension of 1):

QRb×s×HQ×dk,KRb×s×1×dk,VRb×s×1×dkQ \in \mathbb{R}^{b \times s \times H_Q \times d_k}, \quad K \in \mathbb{R}^{b \times s \times 1 \times d_k}, \quad V \in \mathbb{R}^{b \times s \times 1 \times d_k}

During attention calculation, KK and VV are broadcast across all HQH_Q query heads:

Headi=softmax(QiKTdk+M)V\text{Head}_i = \text{softmax}\left(\frac{Q_i K^T}{\sqrt{d_k}} + M\right) V

While MQA slashes memory bandwidth consumption during decoding by a factor of HQH_Q, 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 HQH_Q query heads into GG disjoint groups, where 1GHQ1 \le G \le H_Q:

  • Group size: R=HQGR = \frac{H_Q}{G} query heads per group.
  • Number of key and value heads: HKV=GH_{KV} = G.
  • When G=HQG = H_Q, GQA reduces exactly to MHA.
  • When G=1G = 1, GQA reduces exactly to MQA.

The projection weights have shapes:

WQRdmodel×(HQdk),WKRdmodel×(Gdk),WVRdmodel×(Gdk)W_Q \in \mathbb{R}^{d_{\text{model}} \times (H_Q \cdot d_k)}, \quad W_K \in \mathbb{R}^{d_{\text{model}} \times (G \cdot d_k)}, \quad W_V \in \mathbb{R}^{d_{\text{model}} \times (G \cdot d_k)}

Let g(i)=i1R+1g(i) = \left\lfloor \frac{i-1}{R} \right\rfloor + 1 denote the group index corresponding to query head ii. The attention computation for query head ii pairs with the shared key and value head of its group g(i)g(i):

Headi=softmax(QiKg(i)Tdk+M)Vg(i)\text{Head}_i = \text{softmax}\left(\frac{Q_i K_{g(i)}^T}{\sqrt{d_k}} + M\right) V_{g(i)}

In matrix contraction terms, let K,VRb×s×G×dkK, V \in \mathbb{R}^{b \times s \times G \times d_k}. In tensor operations, KK and VV are expanded to match QRb×s×HQ×dkQ \in \mathbb{R}^{b \times s \times H_Q \times d_k} using a repeat-interleave transformation:

K~=repeat_interleave(K,repeats=R,dim=2)Rb×s×HQ×dk\tilde{K} = \text{repeat\_interleave}(K, \text{repeats}=R, \text{dim}=2) \in \mathbb{R}^{b \times s \times H_Q \times d_k} V~=repeat_interleave(V,repeats=R,dim=2)Rb×s×HQ×dk\tilde{V} = \text{repeat\_interleave}(V, \text{repeats}=R, \text{dim}=2) \in \mathbb{R}^{b \times s \times H_Q \times d_k}

The attention operation is then computed efficiently across all query heads:

Attention(Q,K~,V~)=softmax(QK~Tdk+M)V~\text{Attention}(Q, \tilde{K}, \tilde{V}) = \text{softmax}\left(\frac{Q \tilde{K}^T}{\sqrt{d_k}} + M\right) \tilde{V}


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 WKGQARdmodel×(Gdk)W_K^{\text{GQA}} \in \mathbb{R}^{d_{\text{model}} \times (G \cdot d_k)} and WVGQARdmodel×(Gdk)W_V^{\text{GQA}} \in \mathbb{R}^{d_{\text{model}} \times (G \cdot d_k)} from pre-trained MHA matrices WKMHAW_K^{\text{MHA}} and WVMHAW_V^{\text{MHA}}:

  1. Mean Pooling: The key projection weights belonging to each group g{1,,G}g \in \{1, \dots, G\} are averaged:

WKGQA[g]=1Rj=(g1)R+1gRWKMHA[j]W_K^{\text{GQA}}[g] = \frac{1}{R} \sum_{j=(g-1)R + 1}^{gR} W_K^{\text{MHA}}[j]

WVGQA[g]=1Rj=(g1)R+1gRWVMHA[j]W_V^{\text{GQA}}[g] = \frac{1}{R} \sum_{j=(g-1)R + 1}^{gR} W_V^{\text{MHA}}[j]

  1. First-Head Selection (Alternative): Selecting only the first head of each group (WKGQA[g]=WKMHA[(g1)R+1]W_K^{\text{GQA}}[g] = W_K^{\text{MHA}}[(g-1)R + 1]). 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 G=8G=8 (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 (G=1G=1) 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 NTPN_{\text{TP}} GPUs via Megatron-LM tensor parallelism:

  • The query projection weight WQW_Q is split column-wise: each GPU holds HQNTP\frac{H_Q}{N_{\text{TP}}} query heads.
  • The key and value projection weights WK,WVW_K, W_V are split column-wise: each GPU holds HKVNTP\frac{H_{KV}}{N_{\text{TP}}} key-value heads.
  • The output projection weight WOW_O is split row-wise, followed by an all-reduce collective communication step.

For tensor parallelism to function without head duplication:

HKV(modNTP)=0H_{KV} \pmod{N_{\text{TP}}} = 0

For example, Llama 3 70B uses HQ=64H_Q = 64 and HKV=8H_{KV} = 8. It partitions evenly across NTP{1,2,4,8}N_{\text{TP}} \in \{1, 2, 4, 8\} GPUs. On an 8-GPU node (TP=8\text{TP}=8), each GPU hosts exactly 648=8\frac{64}{8} = 8 query heads and 88=1\frac{8}{8} = 1 key-value head, operating locally as an MQA structure without inter-GPU KV cache communication.

If TP>HKV\text{TP} > H_{KV} (for instance, running a model with HKV=4H_{KV}=4 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 QQ and KK representations prior to dot-product evaluation:

RΘ,md=diag(Rθ1,m,Rθ2,m,,Rθd/2,m)R_{\Theta, m}^d = \text{diag}\left(R_{\theta_1, m}, R_{\theta_2, m}, \dots, R_{\theta_{d/2}, m}\right)

In GQA:

  • RoPE is applied to each of the HQH_Q query heads: Qi(m)=RΘ,mQiQ_i^{(m)} = R_{\Theta, m} Q_i.
  • RoPE is applied once to each of the GG key heads: Kg(m)=RΘ,mKgK_g^{(m)} = R_{\Theta, m} K_g.
  • The query head Qi(m)Q_i^{(m)} and the transformed group key Kg(i)(m)K_{g(i)}^{(m)} preserve the exact relative positional distance property:

Qi(m),Kg(i)(n)=(QiRΘ,m)(Kg(i)RΘ,n)T=QiRΘ,mnKg(i)T\langle Q_i^{(m)}, K_{g(i)}^{(n)} \rangle = \left(Q_i R_{\Theta, m}\right) \left(K_{g(i)} R_{\Theta, n}\right)^T = Q_i R_{\Theta, m-n} K_{g(i)}^T

Because RoPE operates per-head on vectors of dimension dkd_k, 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 b16b \ge 16, 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 GG allows system designers to select the optimal operating point between MHA representation capacity (G=HQG=H_Q) and MQA bandwidth minimization (G=1G=1).
  • Hardware Alignment: Choosing G=8G=8 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

Written by

More to read

  • Aurora Ransomware Deployed Cursor AI Coding Agent for Autonomous Network Exploitation

    A threat intelligence report from Gambit Security has revealed that the Russian-speaking ransomware operation known as Aur0ra (Aurora) utilized the Cursor AI coding assistant to conduct hands-on network intrusions and automated exploitation across at least seven enterprise environments between April and May 2026. According to session logs recovered from exposed threat actor infrastructure, the attacker drove Cursor Agent configured with the claude-4.5-sonnet-thinking model identifier to execute

    1 min
  • Google DeepMind Pilots Double-Blind AI Evaluations in Hardware-Isolated Cryptographic Enclaves

    Google DeepMind has introduced a framework for conducting double-blind evaluations of proprietary frontier AI models within cryptographically isolated computing environments. The initiative, developed in partnership with the Singapore AI Safety Institute, OpenMined, AVERI, and MLCommons, aims to resolve the tension between protecting benchmark datasets from contamination and safeguarding proprietary model weights. In traditional third-party model evaluations, organizations face an unavoidable c

    1 min
  • Autonomous Coding Agent Harnesses in Production: Comparing OpenHands, SWE-agent, Aider, and Cline

    The transition from inline code completion to autonomous software engineering harnesses marks a structural shift in how frontier models interact with codebases. Where early coding assistants operated within narrow token completion windows, modern agentic harnesses construct closed action-observation loops. These systems inspect repository structures, invoke compiler toolchains, execute unit test suites, parse stdout diagnostics, and iteratively correct syntax and logic errors until a pull reques

    1 min