← Inference From First Principles

Multi-Head and Multi-Latent Attention

How many keys and values a model keeps decides its cache, its decode bandwidth and how many requests fit: real cache sizes from cached models, why a naive grouped-query kernel saves nothing, what converting a multi-head model costs, and a latent-attention layer built from the paper and measured.

Llama-3.2-3B stores 112 KiB (114,688 bytes) of key/value tensors for each cached token across its 28 transformer layers when the cache uses fp16. It has 24 query heads but only 8 key/value (KV) heads; an otherwise identically shaped full multi-head design would store 336 KiB per token. Under an illustrative KV-only budget on a 12 GiB GPU, the arithmetic permits 11 versus 3 fully allocated 4,096-token sequences. Those are capacity estimates, not measured concurrent requests: weights, workspace, memory fragmentation, batching policy, and serving overhead decide what fits in practice.

An architecture can reduce the stored KV cache yet a decode implementation can give back much of the bandwidth saving. The chapter’s naive repeat_interleave path materialises copies of shared KV heads before attention, so its scratch traffic resembles MHA even though the persistent cache is smaller. With 32 query heads, batch 16 and 8,192 cached positions in a synthetic kernel benchmark, the repeat path stayed near 29–31 ms from 32 KV heads down to one. A different grouped SDPA formulation reached 1.85 ms at 8 KV heads, compared with about 30 ms for repetition at that setting. This is a 32-query-head kernel experiment, not an end-to-end measurement of the 24-query-head Llama-3.2-3B model.

This chapter compares multi-head attention (MHA), multi-query attention (MQA), grouped-query attention (GQA), and multi-head latent attention (MLA) in three distinct ways. First, it calculates ideal fp16 KV storage from configurations and checks three actual caches. Second, it benchmarks attention-only decode kernels on synthetic tensors, distinguishing persistent cache capacity from temporary memory traffic. Third, it mean-pools GPT-2’s KV projections and briefly retrains the converted checkpoints, then implements a smaller, randomly initialised MLA reference to check its algebra and timing. Together those experiments explain the mechanisms; they do not benchmark a production serving engine or establish the quality of a trained MLA model.

Where this sits

Chapter 10 established how KV-cache bytes accumulate with sequence length; Chapters 14–16 examined allocating and sharing that storage. Chapters 9 and 11 separated host launch, memory-bandwidth, and arithmetic ceilings. This chapter changes the amount of per-token KV state demanded by the architecture and asks whether the runtime preserves the potential bandwidth saving. The distinction matters: a smaller allocated cache does not by itself prove a faster decoder. Chapter 22 adds a separate lever—restricting the history that an attention layer retains or attends to—so that head sharing and context-window policy can be combined.

The Inference Lab contribution is a config-driven KV calculator, three measurements of real cache tensors, four synthetic decode formulations, a GPT-2 MHA-to-GQA converter with a calibration-selected training control, and an MLA reference in expanded and absorbed forms. These are separate experiments with different validity limits. For the Pi series, bytes per token belongs in the versioned model manifest along with attention head counts, head widths, cache dtype, and any windowing or latent-cache policy. A converted checkpoint must have its own manifest: pooling KV projections changes its function even before any subsequent training.

What the cache holds

Multi-head, grouped-query, and multi-query attention

For conventional attention with \(L\) layers, \(h_{kv}\) cached KV heads per layer, and head dimension \(d\), each cached token contributes one key and one value for each KV head. If those dimensions and the cache dtype are uniform across layers, the total is:

\[ \text{cache elements per token} = 2 \cdot L \cdot h_{kv} \cdot d. \]
In MHA, \(h_{kv}=h_q\): each query head has its own key and value. MQA (Shazeer, 2019) sets \(h_{kv}=1\), sharing a single KV head; GQA (Ainslie et al., EMNLP 2023) groups query heads so that \(1The following are nominal fp16 KV bytes per token derived from locally available config.json files. They assume a conventional full-length cache for every listed layer, with no allocator overhead, metadata, padding, or lower-precision KV storage. They do not assert that all model weights are locally installed or that every model uses full-context attention at every layer:

Model Layers Query heads KV heads Head width KV bytes per token Against MHA of the same shape
GPT-2 12 12 12 64 36,864 1×
Phi-3-mini 32 32 32 96 393,216 1×
TinyLlama-1.1B 22 32 4 64 22,528 8× smaller
Llama-3.2-1B 16 32 8 64 32,768 4×
Llama-3.2-3B 28 24 8 128 114,688 3×
Mistral-7B-v0.3 32 32 8 128 131,072 4×
Llama-3.1-8B 32 32 8 128 131,072 4×
Gemma-2-2B 26 8 4 256 106,496 2×

The inspection covered ten local configurations: the eight rows shown, Pythia-160m (the same nominal KV geometry as GPT-2), and Qwen3-1.7B (28 layers, 16 query heads, 8 KV heads, width 128: 114,688 fp16 bytes per cached token). The Qwen3 configuration was present but its weights were not. Gemma-2’s alternating local/global attention and Phi-3’s configured sliding-window field mean that the full-length formula is a useful upper-context reference, not necessarily their actual steady-state cache requirement; Chapter 22 analyses window policy explicitly.

The dimensional calculation is exact for the tensors and dtype specified, not a general statement about an allocator’s occupied memory. For GPT-2, TinyLlama-1.1B, and Llama-3.2-1B, a 256-token fp16 forward pass left respectively 9,437,184, 5,767,168, and 8,388,608 bytes of key/value tensor payload in the library cache—each exactly 256 times the per-token figure. That checks these three payload shapes. It does not validate runtime workspace, paged-block metadata, spare capacity, or cache configurations such as quantisation or sliding windows.

Two comparisons show why parameter count alone is a poor guide to KV pressure. With all 32 layers counted at full length, Phi-3-mini needs a nominal 393,216 fp16 bytes per token, three times Mistral-7B’s 131,072, despite being the smaller model by total parameters. Llama-3.2-3B, with 8 rather than 24 KV heads, retains one third of the KV payload it would require in an otherwise equal-width MHA arrangement. Those statements concern KV payload per cached position; actual per-request residency can be lower with window eviction or higher with padded allocations.

Here is the capacity arithmetic, not a throughput experiment. Llama-3.2-3B’s 3,212,749,824 fp16 parameters occupy about 6.43 decimal GB (5.98 GiB). Reserving 10% of a nominal 12 GiB card before subtracting those weights leaves 4.816 GiB for KV payload. At 114,688 bytes per token, that is 11 complete 4,096-token sequences, or one complete 32,768-token sequence, by floor division. Substituting 24 KV heads triples the per-token payload and gives three 4,096-token sequences, or zero 32,768-token sequences. This estimate omits activations, CUDA/runtime reservations, KV block packing, prompt/decode transients, and the concurrent GPU work needed to serve the sequences. A real scheduler must measure usable capacity after those costs.

Reading less at decode

KV cache size by attention variant

For a single-token decode at sequence length \(S\), ordinary attention generally needs to visit the relevant cached keys and values for that position. The minimum KV payload to fetch is proportional to \(S h_{kv} d\); dividing the payload by an independently measured bandwidth gives an optimistic traffic floor, not a prediction of every kernel’s runtime. Extra reads, temporary copies, softmax, kernel launches, and cache locality can shift the bottleneck. MQA and GQA reduce that lower-bound traffic, but the benchmark below tests whether a particular implementation preserves the reduction.

The GPU microbenchmark uses synthetic fp16 query, key, and value tensors: 32 query heads of width 128, with 32, 8, 4, 2, or 1 KV head. It times one attention-only decode operation, not a complete transformer forward pass or a model’s token latency. Four implementations expose the cost of making shared heads explicit versus keeping them shared:

  • Repeat (attn_decode_repeat): repeat_interleave each KV head to match the query-head count, then perform ordinary attention; this expands temporary K/V tensors but leaves the source cache smaller.
  • Grouped matmul (attn_decode_grouped): reshape queries as \([B,h_{kv},G,d]\), where \(G=h_q/h_{kv}\), and compute attention for each group without physically repeating cached KV heads.
  • PyTorch enable_gqa (attn_decode_sdpa): ask scaled_dot_product_attention to handle unequal head counts through its GQA option; the actual backend is not pinned or profiled in these runs.
  • Grouped queries through SDPA (attn_decode_sdpa_grouped): present the \(G\) query heads as the query-length axis of each shared KV head. At a single decode position all these queries are allowed to attend to the entire supplied history, so no causal mask is needed. This reinterpretation is not a drop-in multi-token prefill method: prefill would require correctly aligned causal masking.

For batch 16 with 8,192 cached positions, the table gives the best of three rounds in milliseconds. Cache values are fp16 key/value payload in decimal MB; the bandwidth floor uses 304 GB/s measured elsewhere on this GPU. Repeating all queries across heads can allocate substantially more temporary storage than the cache column implies:

KV heads Persistent KV payload KV-only bandwidth floor Repeat Grouped matmul enable_gqa Grouped queries via SDPA (backend unverified)
32 (MHA) 2,147 MB 7.06 ms 29.1 ms 12.7 ms 7.2 ms 7.19 ms
8 537 MB 1.77 ms 30.0 ms 3.48 ms 67.4 ms 1.85 ms
4 268 MB 0.88 ms 30.0 ms 2.50 ms 64.3 ms 0.97 ms
2 134 MB 0.44 ms 30.0 ms 0.82 ms 62.8 ms 0.54 ms
1 (MQA) 67 MB 0.22 ms 31.0 ms 0.64 ms 63.9 ms 0.49 ms

At 32 KV heads, enable_gqa is disabled because no grouping is needed; its 7.2 ms entry is ordinary SDPA. Across the measured cases, all four methods produced outputs differing from the explicit repeat reference by at most approximately \(5\times10^{-4}\) in absolute value (fp16), which checks numerical agreement to that tolerance, not bitwise identity. The shorter, 4,096-position runs show a similar ordering, but a different batch or backend can change it.

Three findings.

Explicit repetition erases the expected decode traffic gain, not the persistent cache-size gain. At batch 16 and 8,192 positions, the repeat path stays around 29–31 ms because it creates per-query copies of shared KV heads and then reads those expanded tensors. The original cache still stores only \(h_{kv}\) heads. Thus repeat_interleave does not make GQA architecturally equivalent to MHA, but in this experiment it creates an MHA-sized temporary representation and prevents a faster memory path. Avoiding materialisation is essential if the execution is to benefit from the model’s lower KV head count.

The grouped SDPA formulation approaches the measured-bandwidth lower bound in the largest cases. At 32 KV heads it takes 7.19 ms against a 7.06 ms payload-only floor; at 8 heads it takes 1.85 ms against 1.77 ms. At 4 heads it is 0.97 versus 0.88 ms, and at a single head it is 0.49 versus 0.22 ms. Relative to the 32-head run, elapsed time improves by about 3.9× at 8 heads, 7.4× at 4, and 14.7× at 1, compared with ideal KV-payload ratios of 4×, 8×, and 32× respectively (32-to-1 is 32×, not 16×). The shrinking gap between useful memory work and fixed overhead explains why a 32× smaller cache does not yield a 32× faster attention step here.

enable_gqa performed badly on this specific build and shape. With batch 16 and 8,192 positions, PyTorch 2.6.0 on an RTX 2060 (compute capability 7.5) took about 62–67 ms for 1–8 KV heads with enable_gqa=True, compared with 0.49–1.85 ms for the alternative grouped SDPA formulation. The latter was approximately 36–130× faster in those settings. PyTorch’s documented math GQA path can expand KV heads with repeat_interleave, a plausible explanation for poor performance, but the selected backend was not instrumented in this experiment; do not attribute the result to a particular backend without tracing it. The single-sequence runs had a much smaller spread (roughly 0.22–0.29 ms for the grouped SDPA formulation at 4,096 positions), consistent with fixed overhead being important; they do not prove a launch-bound ceiling without profiling. The lesson is to benchmark the chosen backend, not to conclude that PyTorch GQA is generally slow.

A model choice, not a switch

An MHA checkpoint can be mechanically converted to fewer KV heads by pooling projection weights, but that changes the function. The GQA paper (Ainslie et al., EMNLP 2023) constructs a grouped head by mean-pooling each original group’s key and value projections, then uptrains the converted model with additional training; its reported experiments explore budgets around 5% of original pre-training compute. That is a training recipe and model change, not a lossless serving toggle. The authors found pooling preferable to picking one existing head or random reinitialisation in their setting and reported useful T5-XXL GQA quality after conversion, with further training important especially for MQA. The GPT-2 experiment here tests this procedure at a much smaller scale, not a direct replication of those results.

GPT-2 has 12 query/KV heads, which can be regrouped to 6, 4, 3, 2, or 1 KV head while keeping the query-head count at 12. The lab rewrites the attention projections and mean-pools the original key/value projection matrices and biases. With 12 heads retained, the rewritten float32 model matches Hugging Face GPT-2 logits to a maximum absolute error of roughly \(1.4\times10^{-4}\) in the recorded check. A CPU unit test constructs identical heads within each group and confirms that pooling then preserves its output to tolerance. Neither test says that pooling different trained heads is function-preserving: the quality experiment specifically measures the degradation when they are not identical.

The conversion experiment uses the inference book as a domain-adaptation corpus, tokenised with GPT-2: chapters 1–14 plus code/tests for training (263,365 tokens), chapters 15–16 for checkpoint calibration (40,012), and chapters 17–19 for final reporting (83,621). It uses 256-token, non-overlapping evaluation windows and one training seed, with 400 optimiser steps available to selected head counts. The chapter files and associated code are read live by corpus_split, so the recorded split must be frozen by source commit or content hashes: upgrading earlier chapters changes the experiment’s inputs. The numbers below are test-set bits per token, with the checkpoint step chosen by the lowest calibration loss:

KV heads Nominal fp16 KV payload/token Converted, no uptraining Calibration-selected, up to 400 steps Gap to selected 12-head control
12 (original geometry) 36,864 B 4.762 3.538 (step 300, control) 0
6 18,432 B 8.337 not run —
4 12,288 B 9.087 4.169 (step 400) +0.63
3 9,216 B 10.201 not run —
2 6,144 B 10.753 4.614 (step 400) +1.08
1 3,072 B 11.336 4.916 (step 400) +1.38

Pooling without further training caused a severe degradation in this GPT-2 conversion. At 6 KV heads, test loss rose from 4.762 to 8.337 bits per token—perplexity from about 27 to about 323—and at one head to 11.336 bits. This is substantially worse than the original model on this particular domain. The paper’s T5-XXL conversion results are not a counterexample: architecture, task, evaluation data, and pre-training history differ. The experiment demonstrates why changing KV projection geometry cannot be treated as a quality-preserving serving flag; it does not imply that GQA architectures trained from the start are intrinsically poor.

Uptraining substantially reduced the initial degradation, but it did not close the gap to a similarly adapted control in the available budget. For four KV heads, calibration loss fell from 8.842 before training to 5.45 after 25 steps and to 3.877 at 400. The 12-head control, however, was selected at step 300, with a test loss of 3.538 bits per token; the four-, two-, and one-head checkpoints were selected at step 400 and scored 4.169, 4.614, and 4.916. Their selected-checkpoint gaps were consequently +0.63, +1.08, and +1.38 bits per token. The source records test scores at intermediate checkpoints but uses calibration loss, not test loss, to choose the reported step. A stronger future protocol would evaluate the held-out test once after that choice is locked.

These results establish that mean pooling can substantially damage an existing MHA model and that limited extra training can repair part of that damage. They do not show that the remaining difference is ’nearly all recoverable’: several training curves were still declining at step 400, but their future endpoints are unknown. This is one 124M-parameter GPT-2 checkpoint, one seed, roughly 819,200 training tokens processed over repeated windows from a 263,365-token split, and a corpus far narrower than GPT-2’s original training distribution. The selected 12-head checkpoint’s final training cross-entropy was about 0.85 nats, while its selected test loss was 3.538 bits per token (about 2.45 nats); compare units before declaring overfitting. Neither a GQA model trained from scratch nor the original GQA paper’s much larger uptraining budget was reproduced.

Latent attention

Latent attention: compress, cache, decompress

Multi-head latent attention (MLA), introduced in DeepSeek-V2, reduces cached history differently from GQA. Instead of storing a separate key and value tensor for each head, it stores a per-token compressed KV latent and a small shared positional key. Higher-dimensional content keys and values can be expanded from the latent for a reference calculation—or their projection matrices can be algebraically absorbed so expansion is unnecessary at decode. The lab implements that content/rotary mechanism with random weights at a smaller shape. It omits the paper’s query-side low-rank compression, so it checks the KV idea, not every component of the published architecture. Start with the content-only projections:

\[ c_t = W_{DKV}\, h_t, \qquad k^C_t = W_{UK}\, c_t, \qquad v_t = W_{UV}\, c_t, \]
Here \(c_t\) has dimension \(d_c\), usually much smaller than the combined content-key dimensions \(n_h d_h\). The **content** cache is just \(c_t\), but the total MLA cache is not: rotary positional information requires an additional shared key. Applying RoPE directly to the expanded content key prevents the content-key up-projection from being absorbed into a position-independent query projection. DeepSeek-V2 therefore uses **decoupled rotary**: each query head has a positional component \(q^R\) and every token contributes a shared rotary key \(k^R_t=\operatorname{RoPE}(W_{KR}h_t)\) of width \(d_R\). The score combines content and rotary dot products and is scaled by \(1/\sqrt{d_h+d_R}\). Thus the cache payload per token per layer is \(d_c+d_R\) elements. The paper's chosen ratios, \(d_c=4d_h\) and \(d_R=d_h/2\), yield \(4.5d_h\) elements: the **same number of cache elements as 2.25 ordinary GQA KV heads**, not a claim that fractional heads can be implemented.

For a concrete numerical check, the reduced lab uses 16 query heads with content-head width 128, latent width \(d_c=512\), and shared rotary-key width \(d_R=64\). The following table counts per-token, per-layer KV payload elements at a common dtype; it is not a full-model comparison or a measurement of temporary projection workspace:

Elements Against MHA
MHA (16 key/value heads) 4,096 1×
GQA, 4 heads 1,024 4× smaller
GQA, 2 heads 512 8×
MLA 576 7.1×
MQA 256 16×

The 576-element MLA cache is 7.11× smaller than this 16-head MHA cache, but larger than the 512-element GQA-2 cache. Its 2.25-head equivalence is an accounting analogy: one ordinary KV head at width 128 stores \(2\times128=256\) elements, while MLA stores 512 latent plus 64 rotary elements. Using a smaller cache than MHA does not establish lower runtime than every GQA configuration.

Absorption, checked

Absorption is an algebraic identity under the stated projections, not a claim of bitwise identical floating-point execution. In the content scores, \(q_t^{C\top}k_j^C=q_t^{C\top}W_{UK}c_j=(W_{UK}^{\top}q_t^C)^{\top}c_j\): map the query into latent space and compare it directly against cached latents. After softmax, linearity also gives \(\sum_j a_j W_{UV}c_j=W_{UV}(\sum_j a_j c_j)\), allowing the value up-projection to run after the weighted sum (or be folded into the output projection). The separate rotary term is retained in both paths. On the reduced random-weight implementation, expanded and absorbed decode outputs differed from a full-sequence causal computation by at most \(5.2\times10^{-8}\) and \(8.2\times10^{-8}\) in float32, respectively, at tested positions. A small float64 CPU test agreed to \(10^{-10}\); causality and relative-position tests also passed. These are numerical validations of this reference model and finite cases, not proof of every kernel implementation or trained-model equivalence.

What it costs to read

The GPU timing experiment uses randomly initialised single layers with synthetic fp16 input and previously filled cache tensors; it is not full autoregressive generation. Projection and attention calculations are timed, but persistent cache updates are not. In particular, the baseline MHA/GQA/MQA step computes the new token’s K/V projections and discards them, whereas the timed MLA absorbed/expanded steps do not compute the new token’s latent and rotary-key writes. Thus the following best-of-three-round results compare indicative attention-read paths, not precisely identical amounts of per-token work. Times are milliseconds; cache sizes are KV payload in decimal MB:

Batch, context MLA absorbed MLA expanded MHA GQA-4 MQA Cache: MLA / MHA / GQA-4
16, 1,024 1.08 5.35 0.72 0.49 0.41 19 / 134 / 34 MB
16, 4,096 1.53 19.5 3.50 1.15 0.53 76 / 537 / 134 MB
16, 8,192 2.17 not run 6.75 1.98 0.76 151 / 1,074 / 268 MB
1, 8,192 0.60 2.36 0.65 0.68 0.40 9 / 67 / 17 MB

The contrast between MLA forms is large: at batch 16 and context 4,096, the expanded implementation takes 19.5 ms against 1.53 ms for the absorbed one, about 12.8× slower. Expanded attention repeatedly reconstructs high-dimensional keys and values from every cached latent; absorption avoids this work. In the same synthetic comparison, absorbed MLA is about 3.1× faster than the MHA reference at 8,192 positions (2.17 versus 6.75 ms), with about 7.1× less KV payload. It is not faster than GQA-4 at that point (2.17 versus 1.98 ms), despite its smaller cache. Extra latent-space dot products, separate rotary work, and unfused operations could explain the result, but no kernel profile was recorded. At batch 1, the MLA absorbed best sample was 0.60 ms while the median across samples was 1.38 ms, so that single favourable value should not be presented as a stable typical latency or as proof of a launch ceiling. Remember also the mismatched per-token cache-projection work disclosed above.

The experiment does not measure MLA language-model quality: its weights are random, and its correctness check concerns algebra and numeric execution, not prediction performance. DeepSeek-V2’s reported quality and its 93.3% KV-cache reduction relative to DeepSeek 67B are the authors’ findings in a different whole-model comparison, not local reproductions. The reduced layer here stores 576 elements rather than MHA’s 4,096 (an 85.9% payload reduction under equal dtype). That local result supports the cache-size calculation; the measured attention timings support only this unfused, partially asymmetric harness. A trained-model quality claim or a production speed-up would require substantially different experiments.

What the numbers do not show

  • Attention-only synthetic timings: cache payloads and selected kernel paths were benchmarked on random tensors, without a full transformer, sampling, paging, scheduler, network, or end-to-end request throughput. The reference attention operators may read a cache more than once.
  • One GPU and library version: PyTorch 2.6.0+cu124 on an RTX 2060 (compute capability 7.5). The enable_gqa backend was not traced; the 62–67 ms result cannot be generalised to every PyTorch/GQA configuration.
  • Unequal MLA work at decode: the standard-attention baselines calculate new-token K/V projections, while MLA timings omit computing and writing their new latent/rotary cache entries. All timed variants omit actual cache writes. Re-run with symmetric cache maintenance before claiming an end-to-end speed advantage.
  • Random, unfused MLA: the lab omits query compression and uses randomly initialised parameters. Numerical agreement and the expected KV elements do not establish quality, a trained DeepSeek-V2 replica, or production kernel performance.
  • Limited GPT-2 conversion study: one seed, domain-shifted book data, 400 maximum training steps, calibration-selected checkpoints, and different head-count checkpoints selected at different steps. The corpus includes mutable source files and must be frozen for reproducibility.
  • Architecture and storage matter separately: fewer KV heads shrink projections and stored KV elements, while full-context versus windowed attention, quantisation, batch, and allocator policies determine actual storage and latency. No trained-from-scratch GQA/MLA quality evaluation was run.

Inference Lab increment

The Lab now has:

  • kv_elements_per_token, mla_elements_per_token, equivalent_gqa_groups, sequences_that_fit, kv_spec_from_config: nominal payload and config parsing; three real fp16 cache tensors checked, not allocator-wide residency.
  • attn_decode_repeat, attn_decode_grouped, attn_decode_sdpa, attn_decode_sdpa_grouped: four synthetic single-token attention paths; their grouping semantics were unit-tested, and their runtimes vary greatly with the backend and shape.
  • build_mla: reduced, randomly initialised content/rotary MLA with full-sequence, expanded, and absorbed paths; query compression and production caching are not implemented.
  • build_gpt2_grouped, uptrain, bits_per_token: mean-pooling converter and controlled domain-adaptation experiment, with checkpoints selected by calibration loss.
  • kvspec, decode, mla, quality: reproducible entry points provided the original source corpus and software environment are frozen.

The rule this chapter adds is: model architecture determines nominal cache payload, but the runtime determines whether that saving survives into memory traffic and latency. KV-head counts, widths, dtype, attention-window policy, and MLA latent dimensions belong in the model identity. Converting an MHA checkpoint changes that identity and can substantially change output quality; uptraining is a possible remedy, not proof of equivalence. Runtime implementations should avoid unnecessary KV expansion, and every speed claim needs a clearly stated level of measurement: tensor payload, attention kernel, full-model decode, or request throughput.

What you should now be able to do

  • Calculate nominal KV bytes per token and memory-budget concurrency under stated dtype and full-context assumptions, and identify overhead the estimate omits.
  • Explain why GQA/MQA can reduce persistent KV storage without proportionally reducing attention-only or whole-model latency.
  • Implement shared-head attention without materialising a copy per query head, and test its output and selected backend against a reference.
  • Convert KV projections by mean-pooling, distinguish conversion-only loss from calibration-selected uptraining and a same-domain control, and freeze the corpus for replication.
  • Derive MLA’s latent-plus-rotary cache and the algebra behind absorbing key/value projections; distinguish exact algebra from numerical tolerance.
  • State which Chapter 21 results were directly measured (three cache tensors, synthetic kernel timings, one GPT-2 conversion, random-weight MLA) and which remain unmeasured (trained-MLA quality, production kernels, end-to-end serving).

Key terms

  • MHA (multi-head attention): one KV head per query head, in the conventional arrangement.
  • MQA (multi-query attention): one shared KV head for all query heads.
  • GQA (grouped-query attention): several shared KV heads, each used by a group of query heads.
  • MLA (multi-head latent attention): KV information compressed into a latent and a shared rotary key, with algebraically absorbable content projections.
  • Persistent cache payload: tensor elements held for previous tokens; excludes allocator reservations, metadata, and temporary expanded copies.
  • KV traffic lower bound: nominal bytes to fetch from memory at a given batch/context, divided by measured bandwidth; not automatically actual traffic or latency.
  • Uptraining: continued training after changing a checkpoint’s attention geometry.
  • Decoupled rotary key: shared position-carrying key cached separately from MLA’s content latent.
  • Absorption: moving linear key/value up-projections across attention’s dot products and weighted sums without materialising expanded per-position keys/values.
  • Calibration-selected checkpoint: the trained step chosen from held-out calibration loss before reporting a test-set score.

Reader exercises

  1. Replace the full-length KV calculation with a per-layer window policy for Gemma-2 and Phi-3. Compare bytes at 4,096 and 32,768 generated positions, documenting which layers are windowed.
  2. Force and record SDPA backend selection (sdpa_kernel), then compare enable_gqa with grouped queries on the same hardware. Does a traced backend explain the 62–67 ms anomaly?
  3. Quantise the GQA cache to eight bits and measure both payload and actual decode latency; does dequantisation change the inferred traffic floor?
  4. Repeat the GPT-2 GQA uptraining on a larger frozen, hashed corpus at multiple seeds. Select checkpoints on calibration only; how does the +1.38-bit one-head gap change?
  5. Compare mean-pooled and first-head-in-group conversion, holding training and evaluation budgets constant.
  6. Benchmark MLA, MHA, and GQA with all new-token KV/latent/rotary projections and cache writes included; then fuse the MLA path. Do the conclusions at 16 × 8,192 hold?
  7. Add query compression to build_mla, and verify the full-sequence/absorbed equivalence over multiple positions and dtypes. What additional work or state changes?
  8. Compute nominal KV elements for DeepSeek-V2’s actual head count under MHA, GQA-8, and the published MLA parameters; distinguish the local 85.9% saving from the paper’s whole-model 93.3% comparison.

References

Evidence in this chapter

Claim Evidence status and scope
MQA/GQA share KV heads; GQA conversion uses mean pooling and uptraining Established research: Shazeer (2019); Ainslie et al. (EMNLP 2023)
MLA stores a KV latent plus a shared rotary key and permits absorption Established algebra/paper design (DeepSeek-V2); checked numerically in a reduced random-weight lab
Nominal KV payloads for ten configs Book calculation from local config files, including Qwen config without weights and ignoring window/padding details
Exact payload agreement for three real 256-token fp16 caches Book measurements: GPT-2, TinyLlama, Llama-3.2-1B; does not measure allocator reservations
11 versus 3 Llama-3.2-3B 4,096-token sequences KV-only floor-division projection with 4.816 GiB budget; not a serving concurrency measurement
Repeat path ~29–31 ms; grouped SDPA 1.85 ms at 8 KV heads Book synthetic attention-only timing, 32 query heads, batch 16, 8,192 positions, fp16
PyTorch enable_gqa 62–67 ms in grouped cases Book timing for a specific Torch 2.6/sm75 setup; backend selection not verified
GPT-2 converted checkpoints initially lose quality Book test bits/token, one seed and book-text domain; no trained-from-scratch GQA comparison
Selected uptraining gaps +0.63/+1.08/+1.38 bits/token Book results relative to a step-300 uptrained 12-head control; others selected at step 400
MLA absorbed agrees with expanded/full-sequence on sampled positions Numerical tests, float32 error ≤8.2e-8 and float64 unit-test tolerance 1e-10, not bitwise identity
Absorbed MLA faster than expanded path on tested contexts Book synthetic, random-weight kernel-level comparison; new-token MLA cache projections/writes excluded
Trained MLA quality, end-to-end serving speed, SDPA backend cause Not measured; DeepSeek-V2’s quality/cache comparisons are authors’ findings