Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceMulti-Query & Grouped-Query Attention
HardInference Optimization11 min read

Multi-Query & Grouped-Query Attention

Eight query heads don't need eight key and value histories. Sharing them changes how much cache a long conversation stores.

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, dk=128d_k = 128, 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]

Three attention head sharing topologies across eight query heads alongside a calibrated KV head count chart. Top diagrams show MHA (8 Q heads to 8 KV heads, 1.00x storage), GQA (8 Q heads grouped 4+4 into 2 KV heads, 0.25x storage), and MQA (all 8 Q heads sharing 1 KV head, 0.125x storage). Bottom horizontal bar chart plots stored KV heads per layer on a 0, 2, 4, 6, 8 axis: MHA 8, GQA-2 2, MQA 1.
All eight query heads stay distinct while stored KV pairs drop from 8 (MHA) to 2 (GQA) and 1 (MQA), shrinking raw KV storage by 4x and 8x.

Why KV cache memory becomes the bottleneck

During autoregressive decode, each step generates one token (Nq=1N_q = 1) while reading the entire stored KV history from HBM.[4][5] For a batch of BB sequences at length SS with HqH_q query heads, HkvH_{kv} KV heads of width dkd_k, and PP bytes per element (2 for FP16/BF16):

  • Attention FLOPs (QK⊤QK^\top + αV\alpha V): 4BHqSdk4 B H_q S d_k
  • Ideal KV HBM traffic (each distinct KV head loaded once): 2BHkvSdkP bytes2 B H_{kv} S d_k P\text{ bytes}

Divide the two and BB, SS, and dkd_k cancel completely, leaving decode operational intensity:

Operational Intensity=4BHqSdk2BHkvSdkP=2P⋅HqHkv FLOPs/byte\text{Operational Intensity} = \frac{4 B H_q S d_k}{2 B H_{kv} S d_k P} = \frac{2}{P} \cdot \frac{H_q}{H_{kv}} \text{ FLOPs/byte}

In FP16 MHA (Hq=HkvH_q = H_{kv}, P=2P = 2), 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 (2⋅Hkv⋅dk⋅P2 \cdot H_{kv} \cdot d_k \cdot P) across LL layers, SS tokens, and BB concurrent requests:

Total KV cache=2⋅L⋅S⋅B⋅Hkv⋅dk⋅P bytes\text{Total KV cache} = 2 \cdot L \cdot S \cdot B \cdot H_{kv} \cdot d_k \cdot P \text{ bytes}

On 72B-style dimensions (L=80,Hq=64,dk=128,P=2L=80, H_q=64, d_k=128, P=2) over 131,072 stored positions (either 32 × 4K or 1 × 128K):

  • MHA (64 KV heads): 343.60 GB (32 KiB per token per layer)
  • GQA-8 (8 KV heads): 42.95 GB (4 KiB per token per layer, 8x smaller, 8 FLOPs/byte)
  • MQA (1 KV head): 5.37 GB (512 B per token per layer, 64x smaller, 64 FLOPs/byte)
Bar chart comparing 70B 128K FP16 KV cache across MHA (343.6 GB), GQA-8 (42.95 GB), and MQA (5.37 GB) with a dashed 80 GB H100 HBM reference line, alongside a visual equal-element comparison showing 32 heads at 4K context equals 1 head at 128K context (40M floats / 80 MB per layer).
Raw 70B/128K FP16 KV cache drops from 343.6 GB (MHA) to 42.95 GB (GQA-8) and 5.37 GB (MQA).

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 qiq_i, 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.
Two distinct queries attend over the same shared K/V rows and produce completely distinct outputs (`[0.67, 0.33]` vs. `[0.33, 0.67]`).

MQA gives the maximum Hq×H_q\times savings at the cost of squeezing every head through one shared KV subspace, which can slightly degrade quality on complex tasks.[1] GQA keeps gg KV heads (1<g<Hq1 < g < H_q), serving G=Hq/gG = H_q / g queries per KV group and matching MHA quality closely across modern open-weight models:[2]

Tensor parallelism and KV-head replication

In engines like vLLM, TP must divide HqH_q. When TP≤Hkv\text{TP} \le H_{kv}, each rank owns Hkv/TPH_{kv} / \text{TP} unique KV heads with zero duplication. When TP>Hkv\text{TP} > H_{kv} (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 TP/Hkv=2\text{TP} / H_{kv} = 2 ranks and trimming the aggregate savings from 8x down to 4x.[15]

Tensor-parallel KV head sharding for Hkv=8: TP=4 stores two unique KV heads per GPU (8 physical total), whereas TP=16 replicates KV heads twice across GPUs (16 physical total).
At TP=4, 8 KV heads split cleanly (2/GPU, 8x savings). At TP=16, every KV head replicates onto 2 GPUs (16 physical copies, 4x savings).

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 GG original MHA head projections, keeps WQW_Q and WOW_O intact, and runs continued pretraining for roughly 5% of original steps:[2]

WK,jGQA=1G∑i∈group jWK,iMHA,WV,jGQA=1G∑i∈group jWV,iMHAW_{K, j}^{\text{GQA}} = \frac{1}{G} \sum_{i \in \text{group } j} W_{K, i}^{\text{MHA}}, \qquad W_{V, j}^{\text{GQA}} = \frac{1}{G} \sum_{i \in \text{group } j} W_{V, i}^{\text{MHA}}

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!

GQA uptraining pipeline: train MHA, mean-pool key and value heads per group, uptrain queries for 5% of pretraining budget, and evaluate GQA quality, alongside an opposing-key mean-pool output shift chart.
Uptraining mean-pools MHA KV heads into GQA groups and continues training (~5% of pretraining steps) to repair the immediate output shift caused by averaging opposing heads.

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 ctKV=WDKVht∈Rdcc_t^{KV} = W^{DKV} h_t \in \mathbb{R}^{d_c} (dc=512d_c = 512 vs. 128×128=16,384128 \times 128 = 16{,}384!).[3][16]

During decode, matrix absorption lets the engine never materialize expanded per-head keys ks,iC=WiUKcsKVk_{s,i}^C = W_i^{UK} c_s^{KV}: by associativity, absorb (WiUK)⊤(W_i^{UK})^\top directly into the current query vector:

(qt,iC)⊤(WiUKcsKV)=((WiUK)⊤qt,iC)⊤csKV(q_{t,i}^C)^\top (W_i^{UK} c_s^{KV}) = \big((W_i^{UK})^\top q_{t,i}^C\big)^\top c_s^{KV}

Wait: why does MLA keep a separate decoupled RoPE vector ksR∈R64k_s^R \in \mathbb{R}^{64} outside csKVc_s^{KV}? Because RoPE inserts a position-dependent rotation matrix Rs\mathcal{R}_s between qtq_t and WiUKW_i^{UK}, and Rs\mathcal{R}_s does not commute with WiUKW_i^{UK}! Leaving RoPE on the compressed key would force a different absorbed query (WiUK)⊤Rs⊤Rtqt(W_i^{UK})^\top \mathcal{R}_s^\top \mathcal{R}_t q_t for every single past position ss. Decoupling content (512512) from position (6464) 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!).

Comparison of per-token KV cache elements across GQA-8 (2,048), GQA-4 (1,024), MLA (576), and MQA (256), alongside naive expansion versus matrix-absorbed MLA decode paths reaching 398.0423.
MLA caches 512 latent + 64 RoPE floats per token (576 total) vs. 2,048 for GQA-8, absorbing WUKW^{UK} into the query during decode for exact numerical parity.
mla-absorption-and-rope-decoupling.py
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))
Output
expanded score=17.0, absorbed score=17.0
same absorbed query across positions?: False

Serving 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.

A fixed 10 GiB KV cache pool partitioned across 4K-context requests fits 1 MHA request, 8 GQA-8 requests, or 64 MQA requests.
Inside a 10 GiB KV budget at 4K context, GQA-8 holds 8x as many concurrent sequences as MHA, unlocking batching headroom.

Three runtime implementation details separate fast, bug-free GQA serving from silent corruption or OOMs:

  1. Never materialize repeat_interleave in production: Expanding HkvH_{kv} heads to HqH_q heads allocates temporary MHA-sized copies in VRAM. Use native grouped kernels such as FlashAttention (flash_attn_with_kvcache) or FlashInfer.[17][18]
  2. Track per-request cursors and RoPE positions: Rotate new QQ and KK at logical position tt, write only the HkvH_{kv} compact heads into persistent cache, and track separate cursors per sequence in ragged batches.
  3. Watch non-square causal masks: PyTorch's F.scaled_dot_product_attention(..., is_causal=True) aligns the triangle upper-left, hiding cached keys k1, k2 from a single latest query (output = 1.0 instead of 4.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.
GQA incremental decode step writes only two KV heads at slot t=1 and keeps temporary eight-head expansion strictly ephemeral during compute. Top pipeline shows Project (8Q, 2KV), RoPE (Q, K at t=1), Append (slot t=1), and Attend (keys 0..1). Bottom left shows the persistent 2-head KV cache across 4 slots (t=0,1 filled; t=2,3 free). Bottom right shows the transient broadcast view expanding the 2 stored KV heads across 8 query heads without duplicating cache memory.
Incremental GQA decode rotates Q and K at logical cursor t=1t=1 and writes only the 2 compact KV heads to persistent cache.
Visibility matrices for latest-token decode: upper-left causal masking hides k1 and k2 (mean 1.0), explicit full-prefix visibility recovers 4.0, and a two-query chunk requires per-row cutoffs so q3 never attends to k4.
Upper-left `is_causal=True` blinds a single decode query to keys k1–k2; multi-token chunks need row-specific causal cutoffs.

Let's verify grouped attention + RoPE + incremental single-step and two-token chunk decoding against full-prefix recomputation in PyTorch:

gqa-cached-decode-parity.py
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))
Output
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 GB to 57 GB (~1.12x faster at batch 1) until larger batches shift the bottleneck onto KV.
  • Expecting GQA to speed up pretraining: Every query head still computes QK⊤QK^\top and αV\alpha V; 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.
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 10 answered
1.A decoder keeps 60 query heads and 10 key/value heads. Which sharing pattern follows?
2.A decode layer has 24 query heads, 6 KV heads and 1 byte per cached value. Count only QK and AV products and one distinct K/V read. What ideal intensity follows?
3.A decoder has 36 identical full-attention layers, each with 24 query heads and 6 KV heads. Each key and each value has 64 elements at 2 bytes per element. The decoder caches 4,096 positions separately for each of 4 requests. What is the total raw K/V payload in decimal GB, rounded to three decimal places?
4.A read-only timing model moves 56 GB of weights and 8 GB of K/V per step over 1 TB/s. A GQA change reduces only K/V bytes eightfold. What lower bounds and speed ratio follow before other work?
5.For an MLA content term, W has rows [2,−1] and [1,3], query q=[1,2], and cached latent c=[3,1]. Which absorbed query can be reused across history, and what score does it give for c?
6.Keep W rows [2,−1],[1,3], current rotated query [1,0] and latent [3,1]. One cached position uses identity key rotation; another rotates the expanded key 90° counterclockwise. Which absorbed-query and score pairs follow?
7.An older MHA checkpoint has 40 K/V heads. You want to convert it to a GQA model with 5 K/V heads without training from scratch. What plan matches the uptraining recipe?
8.In the illustrated vLLM Llama layout, 96 query heads and 6 KV heads run at TP=12. Which physical count follows?
9.One decode layer has 24 query heads and 6 KV heads. Its compact cache holds 1,024 positions for each of 2 requests. Keys and values each have width 64 and use 2 bytes per element. The compact cache stays live while the layer holds separate copies of both arrays expanded to 24 heads. How much memory do these K/V arrays occupy at peak?
10.One latest query at position 2 has zero scores and valid cached values 2,4,12 at positions 0,1,2. Which position-aware visibility and output are correct?

10 questions remaining.

References

Fast Transformer Decoding: One Write-Head is All You Need.

Shazeer, N. · 2019 · arXiv preprint

https://arxiv.org/abs/1911.02150

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

Ainslie, J., et al. · 2023 · EMNLP 2023

https://arxiv.org/abs/2305.13245

DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model

DeepSeek-AI · 2024

https://arxiv.org/abs/2405.04434

Attention Is All You Need.

Vaswani, A., et al. · 2017

https://arxiv.org/abs/1706.03762

Efficiently Scaling Transformer Inference

Pope, R., et al. · 2023 · MLSys 2023

https://proceedings.mlsys.org/paper_files/paper/2023/hash/c4be71ab8d24cdfb45e3d06dbfca2780-Abstract-mlsys2023.html

H100 GPU

NVIDIA · 2026

https://www.nvidia.com/en-us/data-center/h100/

NVIDIA Hopper Architecture In-Depth

NVIDIA · 2022

https://developer.nvidia.com/blog/nvidia-hopper-architecture-in-depth/

The Llama 3 Herd of Models.

Dubey, A., et al. · 2024 · arXiv preprint

https://arxiv.org/abs/2407.21783

Llama 2: Open Foundation and Fine-Tuned Chat Models.

Touvron, H., et al. · 2023 · arXiv preprint

https://arxiv.org/abs/2307.09288

Qwen2.5-72B-Instruct model card and configuration

Qwen Team · 2024

https://huggingface.co/Qwen/Qwen2.5-72B-Instruct

Mistral 7B.

Jiang, A. Q., et al. · 2023

https://arxiv.org/abs/2310.06825

Mistral-7B-v0.3 configuration

Mistral AI · 2024

https://huggingface.co/mistralai/Mistral-7B-v0.3/blob/main/config.json

Gemma 2: Improving Open Language Models at a Practical Size

Gemma Team, Google DeepMind · 2024

https://storage.googleapis.com/deepmind-media/gemma/gemma-2-report.pdf

Qwen3.6-27B

Qwen Team · 2026

https://huggingface.co/Qwen/Qwen3.6-27B

vLLM Llama attention implementation

vLLM Contributors · 2026

https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/models/llama.py

DeepSeek-V3 Technical Report.

DeepSeek-AI · 2024 · arXiv preprint

https://arxiv.org/abs/2412.19437

FlashAttention

Dao-AILab · 2026

https://github.com/Dao-AILab/flash-attention

FlashInfer: Efficient and Customizable Attention Engine for LLM Inference Serving.

Ye, Z., et al. · 2025

https://arxiv.org/abs/2501.01005

torch.nn.functional.scaled_dot_product_attention

PyTorch Contributors · 2026

https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.