Unit 4 of 11 · about 4 hours · derive, implement
MHA, MQA and GQA trade-offs, and multi-head latent attention
The head layout sets how many bytes each decoded token adds to the cache, so it sets the batch and context your serving budget allows. Your variant choice here also changes parameters, which makes it a common confound in architecture comparisons.
You'll be able to
- Derive KV-cache elements per token for MHA, MQA, GQA and multi-head latent attention (MLA), and say which of them changes memory traffic, which changes FLOPs and which changes neither.
- Implement MLA with decoupled RoPE two ways, with keys and values materialized and with the key and value up-projections absorbed, and show that they agree.
- Explain why converting a multi-head checkpoint to GQA by mean pooling is not function-preserving, while the reverse conversion is exact, and what the GQA paper does about it.
Covers
Read
In this order, only the parts listed
0 of 6 done
- Fast Transformer Decoding: One Write-Head is All You Need (arXiv:1911.02150v1)GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)
Section 2.4.1 (performance analysis of incremental multi-head attention), Section 3 and 3.1 (multi-query attention and its memory-to-compute ratio), Sections 4.2 and 4.3 (quality and speed)
The experiments are 2019 translation and language modeling. Read them for the size of the quality gap, not as a result for modern decoders.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (arXiv:2305.13245v3)GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)
Section 2.1 (uptraining by mean pooling) and 2.2 (grouped heads), Section 3.3 (ablations: Figures 4 to 6), Table 1
- CS336 Spring 2026, Lectures 3 and 4 slidesCS336 2026 - Architectures and Attention Alternatives
Lecture 4 slides 57 to 58 (MLA and the RoPE conflict); also Lecture 3 (https://github.com/stanford-cs336/lectures/blob/main/lecture_03.pdf) slides 57 to 63 (arithmetic intensity of incremental decoding, MQA, GQA, quality)
- DeepSeek-V2 (arXiv:2405.04434)DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)
Sections 2.1.1 to 2.1.4 (Equations 1 to 19, Table 1) and Appendices D.1 and D.2 (their attention ablations)
Skip Section 2.2 onward. Appendix D.1 aligns the MHA, GQA and MQA models at about 7B parameters by changing the number of layers, so depth differs between the arms.
- Build a Large Language Model (From Scratch), companion bonus codeBuild a Large Language Model (From Scratch), Chapters 3 and 4
ch04/04_gqa: README andmemory_estimator_gqa.py;ch04/05_mla: README andgpt_with_kv_mla.pyThe MLA code caches the latent and up-projects it at every step, with no decoupled RoPE and no absorption. It shows the cache saving, not the compute path.
- Modern LLM Notebook: KV Cache and Its Architectural EvolutionModern LLM Notebook - Architecture Frontiers
Sections 1 to 5 and the exercises. Do not use Section 6's cache count (see the traps)
Focus on
- KV elements per token per layer: MHA , GQA with groups , MQA , MLA . For DeepSeek-V2 (128 heads, , , , 60 layers) that is 1,966,080 against 34,560 elements per token, a ratio of 56.9, equal to GQA with 2.25 groups (Table 1).
- MQA and GQA reduce the bytes loaded per decoded token. The attention multiply-adds are unchanged, because every query head still attends over every cached position. Shazeer's ratio of memory access to arithmetic drops from to , and only the term shrinks, by a factor .
- RoPE sits between the query projection and the key up-projection, so cannot be absorbed into the query projection. DeepSeek-V2 carries position in extra query heads and one shared rotated key of size that is also cached. That shared key is why the cache is , not .
- Conversion direction matters. Replicating each GQA key and value head into a full MHA gives an identical model. Mean pooling the heads of an MHA checkpoint into groups does not, which is why the GQA paper uptrains (5% of the original compute for T5 XXL) and finds mean pooling beats taking the first head or random initialization (Figure 4).
Common mistakes · 3
- The Modern LLM Notebook (Section 6, commit 979eecf) counts the decoupled RoPE key as elements per token per layer and prints MLA as 8704 elements (3.8 times smaller than MHA), while saying the RoPE side path is 'only a small portion'. DeepSeek-V2 Equation 15 defines one key shared by all heads, so the cache is elements.
- Trusting a shape-only exercise. Notebook Exercise 3 passes if the output has the right shape and is finite, and its
SimpleMLAhas no causal mask. Add the absorbed-path equality test and a future-token test before you call the layer correct. - Reading the quality results as portable. MQA reports a small loss in 2019 translation and language modeling. GQA reports T5 encoder-decoder summarization, translation and question answering. DeepSeek-V2's Appendix D.1 matches parameters by changing depth, and its claim that MLA beats MHA comes from the authors' own models. None is a decoder ablation at your scale.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.A decoder has 32 layers, 8 KV heads of size 128 and bfloat16 caches. How many bytes does each token add, and what would 32 KV heads cost? What is the cache of one 4096-token sequence in each case?Answer
bytes per token with 8 KV heads and 524,288 with 32. For 4096 tokens that is 512 MiB and 2 GiB.
2.Does GQA reduce attention FLOPs during decoding? What does it reduce?Answer
No. Each query head still computes scores against every cached position, so the multiply-adds are unchanged. It reduces the keys and values stored and loaded per step, which shrinks the memory-to-compute term in decoding.
3.Which conversion is exact: GQA to MHA by copying each group's key and value weights to all its query heads, or MHA to GQA by averaging the heads in a group? Why does the other one need training?Answer
Copying is exact, because attention with replicated keys and values is what GQA computes. Averaging keys and values changes every head's attention scores and values, so the converted model computes a different function. Uptraining lets the model adapt.
4.Why does MLA cache rather than ?Answer
Applying RoPE to the up-projected keys would put a position-dependent rotation between the query projection and , blocking the absorption and forcing recomputation of all prefix keys. DeepSeek-V2 therefore uses extra query heads and one shared rotated key of size for position, and that key must be cached as well.
5.In absorbed MLA decoding with , roughly how does the number of multiply-adds per head per cached position compare with materialized keys and values, ignoring the RoPE part?Answer
About four times larger: scores and the weighted sum run in the latent dimension instead of . MLA trades extra arithmetic for a much smaller cache, so it moves decoding toward compute-bound.
Practice
- TensorTonic: Causal Grouped-Query Attention
Free problem
cs336-l03-causal-grouped-query-attention, functioncausal_gqa(q, k, v), without repeating key or value headsThe three public cases check single-head causal attention, multi-query attention with two query heads, and two key-value heads with four query heads, on tiny tensors. They do not check gradients, odd group sizes or float16. Add your own test against a version that repeats the heads.
- Modern LLM Notebook 11: Exercises 1 to 3, then your own MLA test
Exercises 1 to 3 at the end of the notebook; then extend
SimpleMLAwith a causal mask, decoupled RoPE and the absorbed path, and test both paths against each otherExercises 1 and 2 are cache arithmetic; Exercise 3 fills in three lines. The absorbed-path test is the part that checks your understanding. Use a float64 tolerance.
You're done when
Your two MLA paths agree to float64 tolerance under a causal mask and nonzero positions, and you can state the cache elements per token for all four layouts for a configuration you choose.
Only when you can do this without notes.
Leads to
- Weight transfer and differential tests between overlapping architecture variantsTurn the exact and inexact conversions into weight-transfer and differential tests.
- Matched-parameter, matched-token and matched-compute comparisons and the decisive mechanism-risk experimentCompare head layouts under a matched-parameter contract without confounding depth.
- Per-layer KV layouts and the cache consequences of attention variantsFollow the KV bytes into cache layouts and serving cost.
Notes
Resources · 5 for this unit, 13 more in the section
- CS336 2026 - Architectures and Attention AlternativesStanford University · primary
Study the Lecture 3 slides (
lecture_03.pdf, architectures and hyperparameters) and Lecture 4 slides (lecture_04.pdf, attention alternatives and mixture of experts) instanford-cs336/lectures, then implement the Assignment 1 Section 3.3 to 3.5 pieces (RMSNorm, SwiGLU, RoPE, causal attention, the pre-norm block) against its tests. Reconstruct every parameter and state equation before you change one mechanism. Keep GPUs, kernels and parallelism (Lectures 5 to 8) for their own tracks. - Build a Large Language Model (From Scratch), Chapters 3 and 4Sebastian Raschka / Manning · support
Use Chapter 3 (causal multi-head attention, pp. 50-91) and Chapter 4 (the GPT model, pp. 92-127) as the smallest runnable decoder, then the companion bonus folders
ch04/04_gqaandch04/07_moefor one bounded variant. The printed chapters use GPT-2 parts (LayerNorm, GELU, absolute positions); the modern pieces live only in the bonus folders. - GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023) with Fast Transformer Decoding: One Write-Head is All You Need (Shazeer, 2019)Google Research · support
Read MQA Sections 2 and 3 (one shared key and value head to cut decoding memory traffic), then GQA Section 2 (grouped heads as the interpolation, mean-pooled uptraining with 5% of pretraining compute) and Table 1. Both report encoder-decoder results. MQA is at https://arxiv.org/abs/1911.02150.
- Modern LLM Notebook - Architecture FrontiersWalking Labs · support
Use
notebooks-en/part2-training/08-gpt2-to-modern-models.ipynb,11-mla-kv-cache.ipynband13-moe.ipynb, andnotebooks-en/part4-frontiers/27-long-context.ipynband30-efficient-attention.ipynb. Implement only the one variant selected for the checkpoint. - DeepSeek-V2, Section 2.1 (Multi-head Latent Attention)DeepSeek-AI · optional
Read Sections 2.1.1 to 2.1.4: low-rank joint key-value compression, decoupled RoPE and the cache comparison. The 93.3% cache reduction is against their own 67B model, not a portable ratio.
Also in this section
- OLMo 2 Open Model and Training RecipeAllen Institute for AI · required
Read Section 2.1 (architecture), Section 3.2 (initialization) and Sections 3.3.1 to 3.3.3 (non-parametric norm to RMSNorm, reordered norm with QK-norm, z-loss) and Table 1, then find the same settings in a released configuration. The changes were adopted as a package, so the report cannot attribute stability to any single one.
- On Layer Normalization in the Transformer Architecture (Xiong et al., 2020)Microsoft Research Asia · support
Read Figure 1 and Sections 3 and 4: why Post-LN gradients near the output are large at initialization and need warmup, and why Pre-LN does not. The analysis holds at initialization only and assumes uniform attention weights and Gaussian inputs there.
- GLU Variants Improve Transformer (Shazeer, 2020)Google · support
Read Section 2 (the GLU family and SwiGLU) and Section 3.1 (hidden width cut from 3072 to 2048 so parameters match), then Table 1, where GEGLU edges out SwiGLU on the longest run. Check the matching arithmetic yourself.
- RoFormer: Enhanced Transformer with Rotary Position Embedding (Su et al., 2021)Zhuiyi Technology · required
Read Section 3: the rotation-matrix form of RoPE, why the attention score depends only on relative position, and the long-distance decay property. Base 10000 is the original choice; later models raise it.
- Extending Context Window of Large Language Models via Positional Interpolation (Chen et al., 2023) and YaRN (Peng et al., 2023)Meta AI; Nous Research · support
Read Position Interpolation Sections 2 and 3 (scale positions by the length ratio instead of extrapolating), then YaRN Section 3 (frequency-dependent interpolation and the attention temperature). Both still fine-tune. YaRN is at https://arxiv.org/abs/2309.00071.
- Small-Scale Proxies for Large-Scale Transformer Training Instabilities (Wortsman et al., 2023)Google DeepMind · support
Read Section 3.1: attention-logit growth and output-logit divergence reproduced in small models at high learning rates, and the QK-layernorm and z-loss fixes (Figures 1 to 4). It explains two of the OLMo 2 choices; transfer to a specific large run is argued, not proven.
- TensorTonic - Architecture and Attention AlternativesTensorTonic · support
Solve RMSNorm Forward Pass (
cs336-l03-rmsnorm-forward), Parameter-Matched SwiGLU Block (cs336-l03-parameter-matched-swiglu), Rotary Query and Key Embeddings (cs336-l03-rotary-query-key-embeddings), Causal Grouped-Query Attention (cs336-l03-causal-grouped-query-attention), Top-k MoE Router with Load Statistics (cs336-l04-topk-moe-router) and one ofcs336-l04-linear-attention-dualityorcs336-l04-mamba2-gated-state-scan. Add capacity and token-drop cases the router tests lack. Public test cases check the listed edge cases, not gradients or the hidden grader, so keep your own tests beside each solution. - Decoder-Only Transformer StackRoadmap-Final · support
Extend the already-tested decoder with the chosen mechanism. Preserve its slow oracle, causal and position tests, generation behavior and model arithmetic.
- Switch TransformersGoogle Research · depth
Use Equations 4 to 6 (the load-balancing loss), Figure 3 (capacity factors), Table 3 (smaller initialization for stability) and the Appendix F pseudocode as the deeper MoE reference. Reproduce only a tiny router experiment; full sparse pretraining belongs to later systems work.
- ST-MoE: Designing Stable and Transferable Sparse Expert Models (Zoph et al., 2022)Google · depth
Read Section 3 and Appendix B: the router z-loss in Equation 5, its coefficient 0.001 and the load-balance weight in Equation 6, and why update clipping stabilizes runs at a quality cost. Its setting is encoder-decoder T5.
- Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality (Dao and Gu, 2024)Princeton and CMU · optional
Read Section 1 and Sections 5 and 6, including Listing 1 (the
segsumreference), for a state-space alternative. Skip the full duality theory; compare against a linear-attention baseline in your own harness. - Modern LLM Notebook, Appendix B: From Parameters to MemoryWalking Labs · support
Appendix B Section 1 (parameters per block and per model, GQA and SwiGLU) and Section 2 (activation memory). Recount the activation tables with autograd hooks; the notebook lists produced tensors, not saved ones. Pin commit 979eecf.
- Deep Learning Tuning PlaybookGoogle Research · support
Read 'Identifying scientific, nuisance, and fixed hyperparameters' and 'Determining whether to adopt a training pipeline change or hyperparameter configuration' as the protocol for comparing architecture variants (per-arm learning rate, trial variance). Skip the batch-norm material. Last commit 2024; pin commit 7554a51.