Unit 4 of 7 · about 4 hours · derive, implement
MQA and GQA: sharing keys and values
Sharing and changes both the learned projections and the state kept during decoding. Counting query heads as KV heads gives the wrong memory estimate.
You'll be able to
- Derive MHA, MQA and GQA projection shapes and bias-free parameter counts at matched model and head widths.
- Implement causal grouped attention with an explicit query-to-KV-head mapping and differential tests.
- Explain KV-memory savings without claiming an equal reduction in attention work or unchanged expressivity.
Covers
Read
In this order, only the parts listed
0 of 2 done
- MHA, MQA and grouped-query implementationModern LLM Notebook - decoder construction path
Multi-Head Attention: MHA and GQA, the MHA vs GQA vs MQA KV Cache hand calculation comparison, and GQA implementation
Stop before QK-Norm. Skip MLA and the architecture survey. Read Exercise 3, How much KV Cache does GQA save, for practice.
- Contiguous grouped-head referencePyTorch scaled dot product attention reference
Equivalent Python implementation:
enable_gqaandrepeat_interleave; GQA constraints note; Parameters and Shape legendUse the head mapping and functional contract after your explicit grouped oracle passes. Skip backend and kernel tuning.
Focus on
- Let and divide . is ; unexpanded and are . MHA has ; MQA has .
- In PyTorch weight layout, and are , while and are . The bias-free total is .
- SDPA maps query head to KV head . The notebook's expand-then-reshape instead interleaves KV heads; choose one convention and make weight ordering and the oracle agree.
- Optional comparison: allocate unexpanded and at the same , , and dtype for MHA and GQA, then compare
numel()*element_size(). Do not count expanded temporary tensors as compact cache storage.
Common mistakes · 3
- Using
repeatrather thanrepeat_interleavewhile assuming contiguous groups. Shapes match, but queries read the wrong KV head. - Storing expanded K and V as the cache. That loses the compact representation's memory saving.
- Expecting independently initialized MHA and GQA to produce equal outputs. Sharing restricts projections; equality needs a deliberately expanded shared-weight MHA reference.
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.With and under contiguous grouping, which query heads share KV head 1?Answer
Zero-based query heads 4, 5, 6 and 7. Each group contains query heads.
2.For , and , what are the weight shape and total projection parameters?Answer
, so is . The four bias-free projections total 2,621,440 parameters, versus MHA's 4,194,304.
3.Does four times fewer KV heads imply four times less attention work?Answer
No. Every query head still computes scores and a weighted value sum. KV projection and compact storage costs shrink; the number of query-head score matrices stays the same.
4.For , , and two-byte elements, what does changing 32 KV heads to 4 save per layer?Answer
plus fall from 33,554,432 bytes to 4,194,304 bytes: 32 MiB to 4 MiB, an 87.5% reduction.
Practice
- Modern LLM Notebook: Exercise 3, How much KV Cache does GQA save
Exercises: Exercise 3, How much KV Cache does GQA save; complete the three quantities and pass its assertions
Extend the exercise in your own repository with the reproduce task. Compare outputs and shared-KV gradients against a head loop for , and an intermediate group count. Reject invalid divisibility.
You're done when
The named exercise passes, your grouped outputs and gradients match the explicit loop for all three head structures, and you derive compact KV bytes and projection counts without notes.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 4 more in the section
- Modern LLM Notebook - decoder construction pathWalking Labs · primary
Work through English notebooks 03-embedding, 04-position-encoding, 05-transformer-block, 06-mini-gpt and the selected normalization, RoPE, GQA and SwiGLU comparisons in 08-gpt2-to-modern-models. Re-derive shapes and rerun with changed dimensions.
- PyTorch scaled dot product attention referencePyTorch · support
Use the functional contract only after the explicit attention oracle passes. Transfer identical weights and masks, compare outputs and gradients, and explain dtype, causal and dropout behavior from the documented semantics.
Also in this section
- LLMs from Scratch companion - attention and GPT constructionSebastian Raschka · required
Use the ch03 attention notebooks and ch04 model code. Rebuild the model without a high-level Transformer module and compare one forward and backward path with an independent small reference.
- Stanford CS336 Assignment 1 - model contractStanford University · required
Use the named linear, embedding, rmsnorm, positionwise_feedforward, rope, softmax, scaled_dot_product_attention, multihead_self_attention, transformer_block, transformer_lm and transformer_accounting specifications and public tests. Keep implementation independent and respect the course AI and honor-code boundary.
- Deep-ML candidate - three transformer closing drillsDeep-ML · optional
After the platform quality sample passes, attempt at most problems 490, 53 and 904 as changed-prompt drills for attention shapes and multi-head composition. Preserve independent tests; a judge result does not replace the section checkpoint.
- nanoGPT - residual projection initializationAndrej Karpathy · support
Read
model.py:MLP,Block,GPT.__init__'s special scaled initialization ofc_proj.weight, andGPT._init_weights. Contrast the depth-dependent residual initialization with CS336's component initialization; do not adopt the training or generation code.