Share keys and values without confusing query-head identity
Derive GQA head mapping, cache payload, shared gradients, and its distinction from changing a kernel schedule.
On this page
The question for today
What you’ll understand
- Map query heads to their shared KV heads.
- Calculate logical KV-cache payload for MHA, GQA, and MQA.
- Distinguish model architecture changes from exact execution changes.
Multi-head attention gives each query head its own keys and values. Multi-query attention shares one KV head across all query heads, while grouped-query attention uses an intermediate number of KV heads. This can reduce cached state and memory reads during decoding, but the query heads still produce different score rows. Unlike tiling an unchanged dense operator, replacing a trained multi-head architecture with shared KV projections changes the model unless a conversion and training procedure establishes acceptable quality. Separate the architecture’s representation budget from the kernel’s ability to reuse that representation efficiently.
Define the head grouping explicitly
For a regular grouping, let Hq be divisible by Hkv and assign consecutive groups of Hq/Hkv query heads to each KV head. Each query head keeps its own Q projection and output, but uses the K and V tensors selected by that mapping. MHA is the endpoint Hkv=Hq; MQA is Hkv=1. The exact group ordering belongs to the model and API contract, not merely to the shapes of two head axes.
FlashAttention 2.8.3 documents this consecutive grouping for its fewer-KV-head interface. For example, six query heads and two KV heads assign query heads zero through two to KV head zero, and three through five to KV head one. A kernel should reuse the shared data where possible rather than physically repeating it into independent buffers. An implementation that expands K and V can preserve arithmetic results while losing much of the storage or bandwidth advantage.
Count cache state before claiming a speedup
A logical KV cache contains both keys and values for each stored token, KV head, and head coordinate. With equal key/value width d and s bytes per element, its payload scales with Hkv rather than Hq. Multiply by batch size and layer count when counting a full model. Allocator rounding, page tables, unused capacity, quantization scales, and temporary expanded tensors are additional storage. State whether a number describes live token payload or total reserved memory.
Sharing KV heads does not necessarily reduce leading query-key and probability-value multiply work by the same factor: each query head still forms its own attention distribution and output. Fewer KV projections and better cache reuse can help, especially in incremental decoding where cache reads matter. Actual speedup depends on the implementation, batch, sequence lengths, and hardware. A cache payload ratio is a memory statement, not a measured latency ratio.
Sharing also changes the gradient and quality contract
During training, a shared key or value tensor receives gradient contributions from every query head in its group. A reference can explicitly repeat K and V along the query-head axis and let differentiation sum back to the original tensors. A fused implementation should agree with that reference within declared numerical tolerances. Incorrect head mapping or failure to accumulate group contributions can pass a forward test with identical heads while failing on deliberately distinct inputs.
The original MQA and GQA papers study the quality and efficiency consequences of shared projections, including conversion or uptraining procedures. Those empirical outcomes do not prove that every existing MHA checkpoint can be changed at inference with identical outputs. Evaluate model quality separately from kernel equivalence. For a fixed GQA model, the fused and expanded implementations target the same operator; converting the model’s projection structure is another experiment with its own validation requirements.
Work it through
Six query heads share two cached KV heads
For one sequence and one layer, take Hq=6, Hkv=2, N=4 cached tokens, key/value width d=2, and s=2 bytes per element. Use consecutive grouping. Compare logical cache payload with MHA and MQA at the same other dimensions.
Group size is 6/2=3, so query heads 0,1,2 use KV head 0 and query heads 3,4,5 use KV head 1. All six query heads remain present; only their key/value source heads are shared.
GQA payload is 2×4×2×2×2=64 bytes. MHA uses Hkv=6 and payload 192 bytes; MQA uses Hkv=1 and payload 32 bytes. These are live K/V element payloads, excluding every surrounding allocation or metadata cost.
The GQA-to-MHA ratio is 64/192=1/3. Nevertheless, for a full four-token noncausal forward pass, leading two-product work remains approximately 4×6×4²×2=768 FLOPs because six query heads each attend to four keys.
The example cuts logical KV cache payload by a factor of three relative to MHA, without claiming a threefold arithmetic or measured runtime reduction.
The living notebook
Explore the model
Interactive lab · roofline
Reuse can change an intensity bound
Reset, set Operational intensity I to 4 FLOP/byte and Memory bandwidth B to 100 GB/s. Predict a 400 GFLOP/s ceiling before Step. Reset, set I to 8 and B to 100, predict 800 GFLOP/s before Step. The fixed synthetic compute ceiling is 1000 GFLOP/s. Playback traces the roof only; this is neither an actual GQA kernel nor an NVIDIA specification.
- Attainable ceiling
- 640 GFLOP/s
- Ridge intensity
- 12.5 FLOP/byte
- Ceiling regime
- Memory-bound ceiling
Synthetic roofline ceiling min(1000, B·I), in GFLOP/s, with B in decimal GB/s and I in FLOP/byte. Playback traces the roof without changing the selected kernel. This upper-bound model is not a measured throughput prediction, hardware comparison or price model. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.
Look forLess traffic can raise operational intensity, but a ceiling calculation alone does not measure a cache-sharing speedup.
Pause & reason
Check your understanding
Your turn
Try it yourself
For N=3, Hq=8, Hkv=2, d=4, and s=2 bytes, calculate one-layer, one-sequence logical GQA and MHA KV payloads. State the grouping and the reduction factor.
Take a moment to make a prediction or work it out on paper. Open a hint when you need one.
Give me a hint
Count both K and V, then substitute Hkv=Hq for the MHA comparison.
Compare with the solution
GQA uses 2×3×2×4×2=96 bytes. MHA uses 2×3×8×4×2=384 bytes, so GQA has one quarter the logical payload, a fourfold reduction. Group size is 4, assigning query heads 0–3 to KV 0 and 4–7 to KV 1. The count excludes batch/layer multiplication, page metadata, and unused allocated slots.
Keep the idea
Take it with you
- GQA shares KV heads while retaining distinct query-head outputs.
- Cache savings scale with KV-head count, not necessarily runtime or dense pair FLOPs.
- Shared-head gradients and model-quality changes need separate validation.
Read further
Original sources and deeper explanations to follow at your own pace.
Optional progress, saved in this browser when available. Revisit any lesson at any time.
Lesson not marked complete.