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

Multi-query and grouped-query attention shapesMHA, MQA and GQA parameter and KV trade-offsOne small MHA versus GQA memory comparison
1

Read

In this order, only the parts listed

0 of 2 done

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

  2. Contiguous grouped-head referencePyTorch scaled dot product attention reference

    Equivalent Python implementation: enable_gqa and repeat_interleave; GQA constraints note; Parameters and Shape legend

    Use the head mapping and functional contract after your explicit grouped oracle passes. Skip backend and kernel tuning.

2

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 repeat rather than repeat_interleave while 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.
3

Try it yourself

Closed-book, before checking anything

Implement a causal grouped-head loop and batched path for , and , using contiguous groups. Derive 768 projection parameters versus MHA's 1024, and show that compact KV tensors use half the bytes at matched , and dtype.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

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

5

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 of c_proj.weight, and GPT._init_weights. Contrast the depth-dependent residual initialization with CS336's component initialization; do not adopt the training or generation code.