On this page
Eight query heads can attend to the exact same conversation and produce eight completely different outputs. Do they really need eight separate copies of the key and value history? Multi-Query Attention (MQA) says no: keep every query head distinct, and share one key/value head across all of them.[1] Grouped-Query Attention (GQA) sits in the sweet spot between MQA and full Multi-Head Attention (MHA), sharing one KV head across each group of queries.[2]
Why does that one architectural tweak matter so much? Because during autoregressive decoding on a 72B-class model (80 layers, 64 heads, , FP16), 32 concurrent 4K requests consume 343.6 GB of raw MHA KV cache, more than double the model's 144 GB of weights! Sharing KV heads in groups of 8 (GQA-8) slashes that cache 8x to 42.95 GB, and DeepSeek's Multi-Head Latent Attention (MLA) compresses it even further into a learned 512-dim latent plus a 64-dim RoPE vector.[3]

What do MQA and GQA change compared with standard multi-head attention?
Answer
They keep all query heads distinct but reduce the number of stored key and value heads. MQA shares one KV head across all queries; GQA shares KV heads across groups of queries.
Why KV cache memory becomes the bottleneck
During autoregressive decode, each step generates one token () while reading the entire stored KV history from HBM.[4][5] For a batch of sequences at length with query heads, KV heads of width , and bytes per element (2 for FP16/BF16):
- Attention FLOPs ( + ):
- Ideal KV HBM traffic (each distinct KV head loaded once):
Divide the two and , , and cancel completely, leaving decode operational intensity:
In FP16 MHA (, ), operational intensity is 1 FLOP/byte. On an NVIDIA H100 SXM (989.5 TFLOPS dense BF16, 3.35 TB/s HBM, ridge point 295.4 FLOPs/byte),[6][7] 1 FLOP/byte caps compute at 3.35 TFLOPS, leaving over 99.6% of Tensor Core throughput idle waiting on memory!
Total KV cache formula
Multiply per-token-per-layer KV storage () across layers, tokens, and concurrent requests:
On 72B-style dimensions () over 131,072 stored positions (either 32 × 4K or 1 × 128K):
- MHA (
64KV heads): 343.60 GB (32 KiBper token per layer) - GQA-8 (
8KV heads): 42.95 GB (4 KiBper token per layer, 8x smaller, 8 FLOPs/byte) - MQA (
1KV head): 5.37 GB (512 Bper token per layer, 64x smaller, 64 FLOPs/byte)

Multi-Query and Grouped-Query Attention
Why can two query heads sharing the exact same keys and values still extract completely different information? Because each query head multiplies those shared keys by its own distinct query vector , producing a different softmax weight distribution over the shared values!
![Two query vectors read the same shared key and value rows. Scaling by square root of two gives score rows [0.707, 0] and [0, 0.707]; softmax gives [0.67, 0.33] and [0.33, 0.67]. With value rows [1, 0] and [0, 1], each output equals its own weights.](https://assets.leetllm.com/v1/e72ce29f7203/fundamentals/multi-query-grouped-query-attention/illustrations/_generated/shared_kv_different_queries_dark.png)
MQA gives the maximum savings at the cost of squeezing every head through one shared KV subspace, which can slightly degrade quality on complex tasks.[1] GQA keeps KV heads (), serving queries per KV group and matching MHA quality closely across modern open-weight models:[2]
| Model | Ratio | Context notes | ||
|---|---|---|---|---|
| Llama 3.1 8B / 70B / 405B[8] | 32 / 64 / 128 | 8 / 8 / 8 | 4:1 / 8:1 / 16:1 | 128K |
| Llama 2 70B[9] | 64 | 8 | 8:1 | 4K |
| Qwen2.5-72B-Instruct[10] | 64 | 8 | 8:1 | 32K (128K w/ YaRN) |
| Mistral 7B v0.3[11][12] | 32 | 8 | 4:1 | 32K (sliding_window: null) |
| Gemma 2 9B[13] | 16 | 8 | 2:1 | Alternating 4K local / 8K global |
| Qwen3.6-27B attention path[14] | 24 | 4 | 6:1 | 256K native (hybrid recurrent layers) |
Tensor parallelism and KV-head replication
In engines like vLLM, TP must divide . When , each rank owns unique KV heads with zero duplication. When (for instance, Llama 3.1 70B's 8 KV heads at TP=16), each rank stores 1 KV head, duplicating every logical KV head across ranks and trimming the aggregate savings from 8x down to 4x.[15]

Converting MHA to GQA via uptraining
You do not need to retrain from scratch to turn an MHA checkpoint into GQA. Ainslie et al.'s uptraining recipe initializes each grouped KV head as the mean of its original MHA head projections, keeps and intact, and runs continued pretraining for roughly 5% of original steps:[2]
Why is uptraining mandatory after mean-pooling? Because averaging two opposing heads (k = [1, -1] and [-1, 1]) cancels their keys to [0, 0] and smears their outputs from 8.81 down to 5.00 before gradient steps adapt the queries to share!

Beyond GQA: Multi-head latent attention (MLA)
Instead of dropping KV heads, DeepSeek-V2 and DeepSeek-V3's Multi-Head Latent Attention (MLA) compresses every token's keys and values into a single shared low-rank latent ( vs. !).[3][16]
During decode, matrix absorption lets the engine never materialize expanded per-head keys : by associativity, absorb directly into the current query vector:
Wait: why does MLA keep a separate decoupled RoPE vector outside ? Because RoPE inserts a position-dependent rotation matrix between and , and does not commute with ! Leaving RoPE on the compressed key would force a different absorbed query for every single past position . Decoupling content () from position () keeps cache size at just 576 floats/token/layer (3.56x smaller than GQA-8's 2,048 and 56.9x smaller than 128-head MHA's 32,768, equivalent to 2.25 GQA heads!).

import torch
# 1. Exact MLA matrix absorption: (q @ W_UK) @ c == q @ (W_UK @ c)
W_UK = torch.tensor([[2.0, -1.0], [1.0, 3.0]], dtype=torch.float64)
q = torch.tensor([1.0, 2.0], dtype=torch.float64)
c = torch.tensor([3.0, 1.0], dtype=torch.float64)
absorbed_q = W_UK.T @ q
print(f"expanded score={torch.dot(q, W_UK @ c):.1f}, absorbed score={torch.dot(absorbed_q, c):.1f}")
# 2. Why RoPE must be decoupled: different positions s need different absorbed queries
rot90 = torch.tensor([[0.0, -1.0], [1.0, 0.0]], dtype=torch.float64)
q_pos0 = W_UK.T @ torch.eye(2, dtype=torch.float64).T @ q
q_pos1 = W_UK.T @ rot90.T @ q
print("same absorbed query across positions?:", torch.equal(q_pos0, q_pos1))expanded score=17.0, absorbed score=17.0
same absorbed query across positions?: FalseServing impact, native kernels, and KV cache correctness
In a fixed 10 GiB (10.74 GB) raw KV pool on a 72B-style model at 4K context, MHA fits 1 request (10.00 GiB / 10.74 GB), GQA-8 fits 8 (1.25 GiB / 1.34 GB each), and MQA fits 64 (0.156 GiB / 0.17 GB each), directly unlocking larger decode batches.

Three runtime implementation details separate fast, bug-free GQA serving from silent corruption or OOMs:
- Never materialize
repeat_interleavein production: Expanding heads to heads allocates temporary MHA-sized copies in VRAM. Use native grouped kernels such as FlashAttention (flash_attn_with_kvcache) or FlashInfer.[17][18] - Track per-request cursors and RoPE positions: Rotate new and at logical position , write only the compact heads into persistent cache, and track separate cursors per sequence in ragged batches.
- Watch non-square causal masks: PyTorch's
F.scaled_dot_product_attention(..., is_causal=True)aligns the triangle upper-left, hiding cached keysk1, k2from a single latest query (output = 1.0instead of4.0)![19] Disable the mask only for a single unpadded latest query, and build explicit position-aware masks (k_pos <= q_pos) for multi-token chunks.


Let's verify grouped attention + RoPE + incremental single-step and two-token chunk decoding against full-prefix recomputation in PyTorch:
import math
import torch
import torch.nn.functional as F
torch.manual_seed(7)
def rope(t, start):
d = t.shape[-1]
pos = torch.arange(start, start + t.shape[-2], dtype=t.dtype)
freq = 10000.0 ** (-torch.arange(0, d, 2, dtype=t.dtype) / d)
ang = pos[:, None] * freq[None, :]
e, o = t[..., 0::2], t[..., 1::2]
return torch.stack((e * ang.cos() - o * ang.sin(), e * ang.sin() + o * ang.cos()), dim=-1).flatten(-2)
def grouped_attn(q, k, v, q_start=0):
B, H, L, D = q.shape
G, S = k.shape[1:3]
qg = q.reshape(B, G, H // G, L, D)
scores = torch.einsum("bgrld,bgsd->bgrls", qg, k) / math.sqrt(D)
visible = torch.arange(S)[None, :] <= torch.arange(q_start, q_start + L)[:, None]
w = scores.masked_fill(~visible, -torch.inf).softmax(dim=-1)
return torch.einsum("bgrls,bgsd->bgrld", w, v).reshape(B, H, L, v.shape[-1])
B, H, G, T, D = 2, 8, 2, 6, 4
x = torch.randn(B, T, H * D, dtype=torch.float64)
wq, wk, wv = [torch.randn(H * D, n * D, dtype=torch.float64) / math.sqrt(H * D) for n in (H, G, G)]
def proj(toks, start=0):
b, n, _ = toks.shape
q = (toks @ wq).reshape(b, n, H, D).transpose(1, 2)
k = (toks @ wk).reshape(b, n, G, D).transpose(1, 2)
v = (toks @ wv).reshape(b, n, G, D).transpose(1, 2)
return rope(q, start), rope(k, start), v
q_all, k_all, v_all = proj(x)
full = grouped_attn(q_all, k_all, v_all)
ref_sdpa = F.scaled_dot_product_attention(q_all, k_all.repeat_interleave(H // G, 1), v_all.repeat_interleave(H // G, 1), is_causal=True)
torch.testing.assert_close(full, ref_sdpa)
# Step-by-step cached decode + 2-token chunk check
kc, vc, outs = torch.empty(B, G, 0, D, dtype=x.dtype), torch.empty(B, G, 0, D, dtype=x.dtype), []
for pos in range(T):
qn, kn, vn = proj(x[:, pos:pos+1], start=pos)
kc, vc = torch.cat((kc, kn), 2), torch.cat((vc, vn), 2)
outs.append(grouped_attn(qn, kc, vc, q_start=pos))
torch.testing.assert_close(torch.cat(outs, 2), full)
q_chunk, _, _ = proj(x[:, 3:5], start=3)
chunk_out = grouped_attn(q_chunk, k_all[:, :, :5], v_all[:, :, :5], q_start=3)
torch.testing.assert_close(chunk_out, full[:, :, 3:5])
print("cached single-step & 2-token chunk parity: exact | compact K shape:", tuple(kc.shape))cached single-step & 2-token chunk parity: exact | compact K shape: (2, 2, 6, 4)Common pitfalls before deployment
- Expecting an 8x KV cut to give an 8x speedup: Model weights (e.g., 56 GB weights vs. 8 GB KV) still stream on every decode step, so shrinking KV 8x moves total reads from
64 GBto57 GB(~1.12xfaster at batch 1) until larger batches shift the bottleneck onto KV. - Expecting GQA to speed up pretraining: Every query head still computes and ; GQA primarily accelerates memory-bound decoding and raises serving concurrency.
- Shipping a converted GQA model without parity checks: Always validate single-token and multi-token cached parity against full-prefix recompute, ragged-batch cursor isolation, per-rank TP memory (including KV replication), and held-out task quality.