Chapter 8 of 40 · ~22 min read & lab+80 XP
Chapter 8 · Generative AI

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

What Is It?

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.

Why Is It Required?

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.

Everyday Analogy: Four analysts (Query heads) sharing one reference binder (KV head) instead of printing four identical binders.
Why ML Engineers & Data Scientists Actually Need This

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!

ML / AI Engineer

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.

Data Scientist

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.

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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%+
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
Hq,HkvH_q, H_{kv}Say aloud:“query heads & KV heads”
Plain-English Meaning
Number of Query attention heads vs. stored Key/Value heads
Everyday Example
LLaMA-3-70B: H_q = 64, H_kv = 8
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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 HkvH_{\text{kv}} clean groups.

Sharing Keys & Values Across Query Heads: MHA → GQA → MQAMHA (1:1)4 Query Heads (Q)4 K/V HeadsMax quality, huge KV-CacheGQA (Groups of 2) ✓4 Query Heads (Q)2 K/V HeadsLLaMA 3 / Gemma 2 sweet spot!MQA (All → 1)4 Query Heads (Q)1 K/V HeadSmallest KV, slight quality dip
MHA gives every Query head its own K/V head; MQA shares 1 single K/V head across all queries; GQA (LLaMA 3, Gemma 2, Mistral) groups G Query heads per K/V head — hitting the exact quality/speed sweet spot!

Three Regimes Defined by One Parameter: HkvH_{\text{kv}}

  • MHA (Multi-Head Attention, Hkv=HqH_{\text{kv}} = H_q): Maximum expressivity, worst KV-Cache memory & decode speed. Used in GPT-3 and LLaMA-1.
  • MQA (Multi-Query Attention, Hkv=1H_{\text{kv}} = 1): Maximum KV-Cache reduction (Hq×H_q\times), fastest decoding, but can cause slight training instability and small quality drops on complex reasoning. Used in PaLM and Falcon.
  • GQA (Grouped-Query Attention, 1<Hkv<Hq1 < H_{\text{kv}} < H_q): Group size G=Hq/HkvG = H_q / H_{\text{kv}} (typically G=4G = 4 or 88). Matches MHA quality while cutting KV-Cache by 4×4\times–8×8\times. Standard in LLaMA 3, Gemma 2, Mistral, and Qwen 2.5!

PyTorch GQA Broadcast Trick

In code, KK and VV have shape (B,Hkv,T,dk)(B, H_{\text{kv}}, T, d_k). During attention, each KV head is simply broadcast (via repeat_interleave(G, dim=1) or zero-copy strided FlashAttention kernels) to match QQ's shape (B,Hq,T,dk)(B, H_q, T, d_k) — without duplicating KV-Cache in HBM!

2. Live KV-Cache Savings & Decode Bandwidth Impact

Everyday Story First (Zero Math Yet!)

Slide the number of KV heads HkvH_{\text{kv}} in the mini-lab below to see how switching from MHA (64 KV heads) to GQA-8 (8 KV heads) transforms 32K-context VRAM!

KV-Cache Footprint for 70B Model at 32K Context (FP16)MHA (64 KV)83.9 GB (OOM on 1×H100!)GQA-8 (8 KV)10.5 GB (8× smaller ✓)MQA (1 KV)1.3 GB (64× smaller)
Switching a 70B model from MHA (64 KV heads) to GQA-8 (8 KV heads) slashes KV-Cache VRAM and decode HBM traffic by 8× with virtually zero perplexity loss!

Why Shrinking WK,WVW_K, W_V Doesn't Shrink Total Model Capacity

Under GQA-8, WKW_K and WVW_V shrink from (D×D)(D \times D) to (D×D/8)(D \times D/8). Rather than leaving the model smaller, modern LLM architects reallocate those saved parameters into a wider SwiGLU FFN — giving you both an 8×8\times smaller KV-Cache and more factual knowledge capacity at the exact same total parameter count!

Formula Anatomy · Click Any Colored Piece to Decode It
Anatomy of GQA Compression & Parameter Reallocation

KV_GQA = KV_MHA / G, where G = H_q / H_kv

Full Query Diversity

All 64 Query heads still ask 64 distinct semantic questions per token.

In our example: 64 Q heads preserved
Put it together with real numbers: On an 80 GB GPU with 20 GB left for KV-Cache, switching from MHA to GQA-8 lets you serve 8× more concurrent users at the same context length!
Animated Mini-Lab • 2.2

70B KV-Cache VRAM Calculator (MHA → GQA → MQA)

KV-Cache: 10.0 GB

3. Beyond GQA: DeepSeek's Multi-Head Latent Attention (MLA)

Everyday Story First (Zero Math Yet!)

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!

Beyond GQA: DeepSeek Multi-Head Latent Attention (MLA)Token h_tdim = 5,120Cache ONLY Latent c_KVdim = 512 (93% smaller!)Up-Project K, VAbsorbed into W_Q/W_O!Low-rank KV compression achieves better quality than GQA at a fraction of the VRAM!
DeepSeek's Multi-Head Latent Attention (MLA) compresses K & V jointly into a tiny low-rank latent vector c_KV, shrinking KV-Cache by 93%+!

How MLA Achieves 93% KV-Cache Compression

Instead of caching separate KK and VV tensors across heads, MLA projects the hidden state hth_t down into a single tiny compressed latent vector: ctKV=WDKVht∈Rdc(dc=512≪Hqdk=16,384)c_t^{KV} = W^{DKV} h_t \in \mathbb{R}^{d_c} \quad (d_c = 512 \ll H_q d_k = 16,384) During inference, ONLY ctKVc_t^{KV} (plus a tiny 64-dim decoupled RoPE key ktRk_t^R) is stored in the KV-Cache!

  • The Matrix-Absorption Magic: When computing qt⊤(WUKcjKV)q_t^\top (W^{UK} c_j^{KV}), associative matrix multiplication lets us fold WUKW^{UK} directly into WQW_Q ((q_t^T W^{UK}) c_j^{KV}) — so we never even decompress KK and VV back to full size in VRAM!
Walk Through With Me · Interactive Worked Example

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.

11. Classic MHA (H_kv = 64)Step 1 / 3

Stores 2×64×128=16,3842 \times 64 \times 128 = 16,384 elements/token (32 KB/layer/token).

Teacher's Note: Baseline 1×.
Pause & Check · Quick Intuition Pulse

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?

Try It YourselfStandard

Can you convert an already-pretrained MHA checkpoint into a GQA model without training from scratch?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Because all HqH_q 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 Visual Lab
Lab Challenge: Switch between MHA, GQA-8, and MQA in the 60 FPS GQA Studio and observe the KV-Cache head-sharing wires and memory bar.
Interactive Animation • 2.2 Deep Lab

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.

Q1
Q2
Q3
Q4
Q5
Q6
Q7
Q8
KV Head #1
KV Head #2
0%
Q_head #1 → KV_head #1 (4× KV savings)
Intuition Takeaway: GQA shares each KV head across G=Hq/HkvG = H_q / H_{\text{kv}} Query heads to slash KV-Cache VRAM and decode bandwidth by 4×4\times–8×8\times at MHA quality, while DeepSeek MLA caches a compressed latent ctKVc_t^{KV} for 93%+93\%+ savings.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Materializing K.repeat_interleave(G, dim=1) inside the KV-Cache buffer itself.
Best Practice: NEVER store repeated KV heads in the cache! Store only (B, H_kv, T, d_k) and let FlashAttention/PagedAttention broadcast KV heads on-the-fly inside SRAM registers.
Trap #2: Assuming MQA always beats GQA in production.
Best Practice: When running Tensor Parallelism across 8 GPUs (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!
Chapter Mastery Check (+80 XP)
Score: 0 / 2
1Why does GQA-8 shard more cleanly than MQA (H_kv=1) across an 8-GPU Tensor-Parallel (TP=8) node?
2In DeepSeek's Multi-Head Latent Attention (MLA), what is stored in the KV-Cache?

Apply What You Learned — Solve Matching Coding Problems