MHA vs. MQA vs. GQA (Grouped-Query Attention) & MLA Explained
How sharing Key/Value heads across groups of Query heads slashes KV-Cache VRAM and decode bandwidth by 4×–8× with near-zero quality loss — plus DeepSeek's Multi-Head Latent Attention (MLA).
Grouped-Query Attention (GQA) shares each Key/Value head across a group of Query heads (sitting between full MHA and single-head MQA) to shrink KV-Cache memory dramatically.
At long contexts and high batch sizes, KV-Cache VRAM—not model weights—becomes the GPU bottleneck; GQA cuts KV memory 4×–8× with almost zero quality loss.
Without GQA (or MLA), serving 128K-context LLaMA 3 70B or DeepSeek-V3 in production would require 8× more GPUs just to hold the KV-Cache!
Knowing how repeat_interleave(H_q // H_kv) maps KV heads to Query heads in PyTorch lets you implement modern attention blocks and accurately size vLLM GPU clusters.
Understanding the quality-vs-bandwidth Pareto frontier from MHA → GQA → MQA → MLA helps you evaluate model cards and pick the fastest high-context open-weights LLM.
Favorite modern LLM design question: 'Why did LLaMA 3 70B choose 64 Query heads and 8 KV heads instead of 64 KV heads or 1 KV head, and how does DeepSeek MLA go even further?'
If you switch a 70B Transformer from MHA (64 Q heads, 64 KV heads) to GQA-8 (64 Q heads, 8 KV heads), by what factor does the KV-Cache VRAM shrink?
- Differentiate Multi-Head Attention (H_kv = H_q), Multi-Query Attention (H_kv = 1), and Grouped-Query Attention (1 < H_kv < H_q)
- Compute the exact KV-Cache compression ratio G = H_q / H_kv and verify how W_K and W_V projection shapes shrink
- Explain why GQA is the universal default in LLaMA 3, Gemma 2, Mistral, and Qwen while MQA suffers subtle quality degradation
- Trace how DeepSeek's Multi-Head Latent Attention (MLA) caches a tiny joint low-rank latent vector c_KV to cut KV-Cache by 93%+
Think of a research team of 64 analysts (Query heads) asking different questions about a 100-page report. In classic MHA, all 64 analysts maintain 64 separate photocopies of the entire report (huge memory!). In MQA, all 64 share 1 single summary (super cheap, but loses nuance). Grouped-Query Attention (GQA) divides the 64 analysts into 8 specialist teams of 8 — each team shares 1 rich indexed copy, slashing memory by 8× while keeping nearly 100% of MHA's accuracy!
1. The Attention Sharing Spectrum: MHA → GQA → MQA
Compare the wiring diagram below: MHA has 1-to-1 Query-to-KV pairing, MQA collapses all queries onto 1 KV head, and GQA partitions queries into clean groups.
Three Regimes Defined by One Parameter:
- MHA (Multi-Head Attention, ): Maximum expressivity, worst KV-Cache memory & decode speed. Used in GPT-3 and LLaMA-1.
- MQA (Multi-Query Attention, ): Maximum KV-Cache reduction (), fastest decoding, but can cause slight training instability and small quality drops on complex reasoning. Used in PaLM and Falcon.
- GQA (Grouped-Query Attention, ): Group size (typically or ). Matches MHA quality while cutting KV-Cache by –. Standard in LLaMA 3, Gemma 2, Mistral, and Qwen 2.5!
PyTorch GQA Broadcast Trick
In code, and have shape . During attention, each KV head is simply broadcast (via repeat_interleave(G, dim=1) or zero-copy strided FlashAttention kernels) to match 's shape — without duplicating KV-Cache in HBM!
2. Live KV-Cache Savings & Decode Bandwidth Impact
Slide the number of KV heads in the mini-lab below to see how switching from MHA (64 KV heads) to GQA-8 (8 KV heads) transforms 32K-context VRAM!
Why Shrinking Doesn't Shrink Total Model Capacity
Under GQA-8, and shrink from to . Rather than leaving the model smaller, modern LLM architects reallocate those saved parameters into a wider SwiGLU FFN — giving you both an smaller KV-Cache and more factual knowledge capacity at the exact same total parameter count!
KV_GQA = KV_MHA / G, where G = H_q / H_kv
All 64 Query heads still ask 64 distinct semantic questions per token.
70B KV-Cache VRAM Calculator (MHA → GQA → MQA)
3. Beyond GQA: DeepSeek's Multi-Head Latent Attention (MLA)
Can we compress KV-Cache by 93%+ (even smaller than MQA) while actually beating MHA quality? DeepSeek-V2 and V3 solved this with low-rank matrix absorption!
How MLA Achieves 93% KV-Cache Compression
Instead of caching separate and tensors across heads, MLA projects the hidden state down into a single tiny compressed latent vector: During inference, ONLY (plus a tiny 64-dim decoupled RoPE key ) is stored in the KV-Cache!
- The Matrix-Absorption Magic: When computing , associative matrix multiplication lets us fold directly into (
(q_t^T W^{UK}) c_j^{KV}) — so we never even decompress and back to full size in VRAM!
Worked Example: Comparing MHA vs. GQA-8 vs. MLA per Token
A 64-head model (d_k = 128, so H_q·d_k = 8,192) in FP16 (2 bytes/elem), single layer.
Stores elements/token (32 KB/layer/token).
In Grouped-Query Attention with H_q = 32 Query heads and H_kv = 8 KV heads, how many Query heads share each Key/Value head?
Can you convert an already-pretrained MHA checkpoint into a GQA model without training from scratch?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because all Query heads still compute dot products against their assigned KV head! GQA primarily saves VRAM capacity and HBM memory bandwidth — which is exactly what bottlenecks Decode!
Interactive MHA vs. GQA vs. MQA Head-Mapping Studio
Switch between MHA (8 KV), GQA (2 KV), and MQA (1 KV) to watch how 8 Query heads share Key/Value caches while preserving expressiveness.
LLaMA 3, Mistral & Qwen 2.5 Serving
Use GQA (4× to 8× compression) so 70B models serve 128K context windows on single 8×H100 nodes.
DeepSeek-V2 / V3 Ultra-Low-Cost APIs
MLA's 93%+ KV-Cache compression allows dramatically larger concurrent decode batches per GPU, directly lowering $/1M token inference cost.
import torch
import torch.nn.functional as F
# Grouped-Query Attention (GQA): H_q query heads share H_kv < H_q key/value heads
def gqa_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
# q: [B, H_q, T, D], k/v: [B, H_kv, T, D]
H_q, H_kv = q.size(1), k.size(1)
assert H_q % H_kv == 0
group_size = H_q // H_kv
# Zero-copy broadcast of each KV head across its query group
k_rep = k.repeat_interleave(group_size, dim=1)
v_rep = v.repeat_interleave(group_size, dim=1)
return F.scaled_dot_product_attention(q, k_rep, v_rep, is_causal=True)
q = torch.randn(2, 32, 16, 64) # 32 query heads (Llama-3 style)
k = torch.randn(2, 8, 16, 64) # 8 KV heads -> 4x smaller KV cache!
v = torch.randn(2, 8, 16, 64)
out = gqa_attention(q, k, v)
print("GQA output shape:", tuple(out.shape), "| KV cache reduction: 4x")
K.repeat_interleave(G, dim=1) inside the KV-Cache buffer itself.(B, H_kv, T, d_k) and let FlashAttention/PagedAttention broadcast KV heads on-the-fly inside SRAM registers.TP=8), MQA with H_kv=1 forces you to duplicate that 1 KV head onto all 8 GPUs (wasting 8× memory!), whereas GQA-8 shards cleanly with exactly 1 KV head per GPU!