Decoding reads every cached key and value once per new token, so the bytes each past token leaves behind are decode time. Every attention variant changes one factor: how big each entry is (MHA, GQA, MQA, MLA), how many entries are kept (sliding windows, V4's compression), or how many are read (NSA, DSA); sinks and gates change where attention goes when nothing is worth reading.
Fig. 1: what one past token leaves behind in one layer, and what the next token reads. Each column is one of 24 past tokens, its height the numbers its entry holds in one layer, to one scale throughout (bf16 configs as section 7 reads them); lit columns are read by the new token's query, faded ones are stored but not read, dashed ones are not stored. The window, the top-k picks, the merged blocks chosen and the sink step are illustrative.
You need: what attention and a KV cache are (The transformer from zero: one head by hand in section 3, why the cache exists in section 9; or the root's attention section, section 4) and RoPE (Positional Encodings), which MLA's decoupled key works around. Whole-model cache sizes at a context length (bytes per sequence, what fits on a GPU) are on Long context; this page is the mechanism.
| Design | Each token stores, per layer | Tiny GPT | Real example (bf16, all layers) | Quality evidence |
|---|---|---|---|---|
| MHA multi-head attention | a key and a value per head: 2 · H · dh | 512 | Llama 2 7B: 512 KiB per token | the reference |
| GQA grouped-query | a key and a value per KV head: 2 · Hkv · dh | 128 (2 KV heads) | Llama 3.1 8B (8 KV heads): 128 KiB | tiny GPT: within seed spread of MHA measured; 7B, 1.33T tokens: MMLU 41.2 vs MHA 45.2 DeepSeek-V2 Table 8 |
| MQA multi-query | one key and one value: 2 · dh | 64 | Llama 3.1 8B as MQA: 16 KiB (what-if) | tiny GPT: same; 7B: MMLU 37.9 same table |
| MLA multi-head latent | a latent c and a shared RoPE key: dc + dr | 64 + 16 = 80 | DeepSeek-V3: 68.6 KiB | MoE 16B and 250B: better than MHA DeepSeek-V2 Table 9; tiny GPT: about 0.09 worse measured (section 3) |
| Sliding window W | as MHA/GQA, but only the last W tokens are kept | 512, for 64 tokens | Mistral 7B v0.1 (W 4,096): 0.50 GiB at 128K instead of 16 GiB | tiny GPT: window 64 within noise of full; smaller windows cost more (section 4) |
| Local : global | local layers keep W tokens, global layers keep all | mixed | Gemma 3 27B (5 : 1, W 1,024); gpt-oss (1 : 1, W 128) | Gemma 3: "minimal impact on perplexity" report |
| Sparse (NSA, DSA) | everything kept (plus an indexer key for DSA); each step reads the top k | n/a | DeepSeek-V3.2: 83.9 KiB held, attention reads 2,048 entries | V3.2 at parity with V3.1-Terminus DeepSeek; NSA above full attention on its benchmarks authors |
| Compressed (V4 CSA, HCA) | one 512-number entry per 4 or 128 tokens, plus a 128-token window | n/a | DeepSeek-V4-Pro: 7.7 KiB of entries plus 1.9 KiB of indexer keys per token | about 2% of a GQA-8 cache at 1M tokens DeepSeek |
| Sink, gate | no extra cache: a learned logit per head (gpt-oss), or a sigmoid gate on each head's output (Qwen3-Next) | 0 | gpt-oss-120b; Qwen3-Next, Qwen3.5 | gate: 15B MoE perplexity 6.026 to 5.761, first-token attention 46.7% to 4.8% Qwen team |
Real-model columns are calculations from each config.json with the root Config calculator's formulas (bf16, windows credited). Whole-model sizing at a context length is owned by Long context.
Concrete. Llama 3.1 8B keeps, for every past token, a key and a value for each of its 8 KV heads of 128 numbers in each of its 32 layers: 128 KiB per token in bf16. A past token's keys and values never change in a causal decoder, so they are computed once and kept; generating one token reads all of it once. Each number read is used by the query heads that share it, one multiply-add for the score and one for the weighted value, so decode attention does about (query heads / KV heads) FLOPs per byte, 1 for MHA and 4 for Llama 3.1 8B, where an H100 can do about 295: the step waits on memory, and batching does not help because every sequence reads its own cache. Cache bytes are decode time.
Measured. One attention layer at Llama 3.1 8B's shape, batch 4, 32,768 cached tokens, fp16 on the M1 Pro's GPU (run for the root's former Attention lab, now carried by this page): MHA 17.49 ms, GQA-8 5.97 ms, absorbed MLA 3.43 ms, MQA 1.54 ms, the order of bytes cached, not of heads or FLOPs (step 5). measured on Apple M1 Pro (MPS)
Where those bytes live. The cache is held in the HBM stacks beside the GPU die (photo), not on the die: what decode attention costs is the time to move each past token's entry across that short distance, once per generated token.
Notation. One layer, input xt, H query heads of size dh: qht = WQh xt, khj = WKh xj, vhj = WVh xj, weights ahtj = softmaxj(qht · khj / √dh) over j ≤ t, output Σj ahtj vhj per head, concatenated and multiplied by WO. RoPE rotates q and k by their positions so the score depends on j − t.
The running example. The topic's tiny GPT (6 layers, dmodel 256, 8 heads of 32, context 256, RoPE), trained on TinyStories for 1,500 steps of 8,192 tokens with the same seed and batches for every variant, so two runs differ only in their attention. The root's Attention lab trained MHA, GQA-4, GQA-2, MQA, MLA, a 64-token window and a 2 local : 1 global interleave; this page adds eight runs. Held-out loss differences under about 0.016 are inside the spread between two seeds (MHA 2.160 and 2.175 on 100 windows). Real-model behaviour comes from SmolLM2-135M (30 layers, 9 query heads and 3 KV heads of 64), inference only.

Concrete. Llama 3.1 8B has 32 query heads but 8 KV heads: each key and value head is read by a group of 4 query heads, so a layer stores 2 × 8 × 128 = 2,048 numbers per token instead of MHA's 8,192. MQA (Shazeer 2019, arXiv 1911.02150) is the limit, one KV head for all; GQA (Ainslie et al. 2023, arXiv 2305.13245) is anything in between. The cache shrinks by H / Hkv; the queries keep full resolution.
Trained from scratch, sharing is free here: GQA-4, GQA-2 and MQA land at 2.185, 2.182 and 2.177 (seed 1: 2.185) against MHA's 2.160 (seed 1: 2.175) on 100 windows, inside the seed spread.
DeepSeek-V2's Appendix D.1 (Table 8, arXiv 2405.04434; DeepSeek's own runs) trained 7B dense models on 1.33T tokens with parameters aligned by layer count: MMLU MHA 45.2, GQA-8 41.2, MQA 37.9; BBH 37.0 / 35.6 / 33.2. The GQA paper (Table 1, T5-XXL uptrained, Google): MHA 47.2 average at 1.51 s per sample, GQA-8 47.1 at 0.28 s, MQA 46.6 at 0.24 s; its authors converted MHA checkpoints with "5% of original pre-training compute" and report that "uptrained GQA achieves quality close to multi-head attention with comparable speed to MQA". Sharing also removes parameters from WK and WV, which comparisons at equal size give back to the FFN or depth. Both results fit the derivation: a model with enough data to use more key directions than the shared heads provide pays for sharing; the tiny GPT (12.3M tokens) is limited by data, not by key directions.
Why sharing costs little. Head h's score is a bilinear form, qht · khj = xtT (WQh)T WKh xj. Under MQA every head uses the same WK: the heads still ask different questions (their query maps differ), but must find the answers in the same dh numbers per token; values likewise. So sharing is cheap exactly when the keys and values the heads need live in a subspace much smaller than H · dh. That is measurable:
Keys and values together span 512 numbers per token per layer, yet the top 64 directions hold 94.2% to 99.6% of their variance and the top 128 hold 99.3% to 99.98%; keys alone, 32 directions (what MQA keeps) hold 84% to 94%. Variance is not loss: the closed block below tests it.
measured on Apple M1 Pro (CPU): the Attention lab's at_mha checkpoint (held-out 2.1374 on its 20 fixed windows, reproduced), 8,192 held-out tokens, keys before RoPE and values of all 8 heads per layer (512 numbers together). Curves: share of variance captured by the top r principal directions, per layer.
Cost, when, how to check. 4x fewer bytes made the decode step 2.9x faster above (17.49 to 5.97 ms). Under tensor parallelism MQA's single KV head is replicated on every GPU, so the per-GPU saving shrinks; GQA needs no new kernels and, with 4 to 16 KV heads, is the default of almost every 2024 to 2026 open model without MLA (Llama 3, Qwen3, Gemma 3, gpt-oss; MQA in PaLM and Gemma 3 270M). Check num_key_value_heads: per layer the cache is 2 · num_key_value_heads · head_dim numbers per token. Head dimension, the other factor, is not only a cache cost: at a fixed parameter budget wider heads improved long-context retrieval while barely moving pretraining loss (Long context, section 8). The trap is in the kernel: an eager path that copies K and V up to all 32 heads first (transformers' repeat_kv) took 38.13 ms in the same measurement, slower than MHA. measured
The GQA paper converts a trained MHA checkpoint by mean-pooling the key and value projections of the heads in each group ("works better than selecting a single key and value head or randomly initializing"), then uptrains for 5% of the original steps (α = 0.05). Averaging keeps only the subspace the heads have in common; projecting onto the directions they actually use is the alternative. Both, with no training, on the same checkpoint and the same 20 held-out windows:
Measured: averaging the tiny MHA's 8 KV heads into 2 took held-out loss from 2.137 to 4.276; 5% uptraining brought it back to 2.481 and 10% to 2.317, while a GQA-2 trained from the start reached 2.160 (20 windows). Projecting jointly onto 64 directions cost 0.093 and onto 128 directions 0.009, with no training: an SVD-style conversion to an MLA-like latent keeps far more of the model, but needs MLA kernels to pay off. The no-retraining alternative for a 2x to 4x smaller cache is FP8 or INT4 KV quantisation (Long context). The GQA paper reports that GQA "already achieves reasonable performance after conversion while MQA requires uptraining to be useful" at T5-XXL scale; here it does not, so this small model's heads are more specialised. measured on Apple M1 Pro (CPU)
Concrete. DeepSeek-V3 has 128 heads of 128. MHA would cache 2 × 128 × 128 = 32,768 numbers per token per layer; multi-head latent attention (DeepSeek-V2, arXiv 2405.04434) caches a 512-number latent plus a 64-number RoPE key, 576: about 57 times fewer, the size of GQA with 2.25 groups (576 = 2 × 2.25 × 128), yet every head keeps its own keys. Over 61 layers in bf16: 70,272 bytes (68.6 KiB) per token against 3,997,696 (3.81 MiB) for MHA and 249,856 (244 KiB) for GQA-8, which MLA beats by 3.6x.
Dimensions: hidden size 7,168, 61 layers, nh = 128 heads of dh = 128, dc = 512, dRh = 64 (V3 report). Projections, absorption and the decoupled RoPE key: V2 paper, section 2.1; the MHA and MQA modes: V3.2 paper, appendix A. Counts are elements; bytes assume bf16; one cell = 64 numbers; six earlier tokens drawn. Built for the DeepSeek page, now owned here.
The formula, same names as Fig. 4.
As a factorisation. MHA's stacked [WK; WV] becomes WU WDKV, rank at most dc: the trained version of section 2's projection (64 directions cost the tiny MHA 0.093, 128 cost 0.009). GQA forces heads to share the same key; MLA gives every head its own key, built from a shared, smaller summary.
Absorption: why decode never rebuilds the keys. Matrix products associate, so the key up-projection moves onto the query side and the value up-projection into the output projection:
So the same layer runs in two modes. In training and prefill, where many queries run at once and attention is compute-bound, it rebuilds per-head keys and values and runs as ordinary MHA ("MHA mode"); the rebuilt keys are used and discarded, never cached. In decode it runs absorbed ("MQA mode"): all 128 heads read the same 576-number entry of every earlier token, whose first 512 numbers also serve as the value (V3.2 paper, appendix A). In decode MLA is multi-query attention over one wide entry, with per-head projections on either side that GQA does not have; that is why its quality holds where MQA's does not. DeepSeek's inference code uses this form (attn_impl "absorb" in inference/model.py).
Why RoPE needs a separate key. With RoPE on the whole key the score is qh · Rj−t WUKh cj: the matrix between query and latent depends on the distance, so no single matrix can be folded into the query, and every prefix key would have to be rebuilt at every step. MLA keeps the content path free of position and adds a decoupled RoPE key kRj = RoPEj(WKR xj) of dr = 64 numbers, shared by all heads and cached beside the latent, with a per-head RoPE query: score = q̃h · cj + qh,R · kRj, scaled by 1/√(dh + dr). MLA also compresses the queries through a second latent (d′c = 1,536 in V2 and V3), which saves activation memory in training and does not change the cache.
Evidence. DeepSeek-V2's Table 9 (DeepSeek): MLA beats MHA at two MoE scales, MMLU 50.0 against 48.7 with a 15.6K against 110.6K element cache, and 59.0 against 57.5 at about 250B parameters. Against its earlier dense DeepSeek 67B, V2 reported a 93.3% smaller cache and 5.76 times the maximum generation throughput, over 50K tokens per second on one 8-GPU H800 node, with the cache quantised to about 6 bits per element (vendor; the model changed too, so not MLA alone). On the tiny GPT MLA trails MHA by about 0.09 (closed block below).
Cost, when, how to check. MLA trades bytes for FLOPs: at DeepSeek-V3's shape and 32,768 tokens, absorbed decode reads 57x fewer bytes than an expanded cache but does about 3.7x the arithmetic (every head dots its query with the whole 576-number entry, not a 192-number key), landing near an H100's balance point (section 7). It pays for large models at long context and large batch. It needs its own kernels (FlashMLA; support in serving stacks lags GQA's), and the latent, shared by all heads, cannot be split by head under tensor parallelism. Check kv_lora_rank (dc) and qk_rope_head_dim (dr): the cache per token per layer is dc + dr, whatever num_key_value_heads says (DeepSeek-V3's says 128).
Kimi K2 copies V3's MLA with 64 heads; GLM-5 moved from GQA to MLA (64 heads, 512 + 64). Kimi Linear and Kimi K3 run their MLA layers with no positional encoding (mla_use_nope): with no rotation there is nothing to decouple, the layers run as plain multi-query attention at inference, and K3 extrapolates to 1M tokens "without any positional-encoding modification" (K3 report, §3.4; the Kimi page); K3 also gates their output ("Gated MLA", section 6). Kimi K2's QK-Clip shows the shared RoPE key's other consequence: it rescales each head's own query and key parts and must leave the shared rotary key alone.
measured on Apple M1 Pro (CPU): the Attention lab's trained at_mla (dc 64, dr 16, 8 heads of 32), the last token of the running sequence attending to all 256 positions, every layer; src/mla/mla_absorb.py. "Naive" expands every cached latent into per-head keys and values; "absorbed" folds WUK into the query and WUV into WO. The last column applies RoPE to the whole key and folds with the position-0 rotation, the shortcut that does not exist.
The absorbed form equals the naive one to 1.3e-15 in float64 and 9.5e-7 in float32 on at_mla; folding while RoPE rotates the whole key moves attention weights by up to 0.40.
calculation in src/mla/mla_absorb.py: multiply-adds counted as 2 FLOPs, the attention core only, bf16 cache. Tiny GPT at 256 cached tokens; DeepSeek-V3's shape (128 heads, dh 128, dc 512, dr 64) at 32,768.
At DeepSeek-V3's shape and 32,768 tokens, per layer per decoded token: absorbed 9.85 GFLOP over 37.7 MB (260.9 FLOPs per byte, including the query and output folds); expanded cache 2.68 GFLOP over 2.15 GB; re-expanding every step 1.10 TFLOP.
The root's Attention lab measured MLA (dc 64, dr 16) at 2.255 held-out (seed 1: 2.248) against MHA's 2.160: about 0.09 worse, and 10% slower to train, while DeepSeek reports MLA beating MHA. Three hypotheses, each testable cheaply: the latent is too small; the shared RoPE key is too narrow (positions matter a lot to this model: NoPE costs 0.23, per the Positional Encodings child); or MLA simply trains slower at this budget. Same seed, batches and 1,500 steps for every run (100 windows):
MLA runs on 100 windows: at_mla 2.2554, latent 128 2.2205, RoPE key 32 2.2239. measured on Apple M1 Pro (MPS training, CPU evaluation)
In short: doubling the latent or the RoPE key each recovers part of the gap, so less than half of it is cache size; every MLA run is behind from the first evaluations, which points to slower optimisation at this budget (not settled: a longer run or an MLA learning-rate sweep was not run).
Concrete. Mistral 7B v0.1 lets every layer attend only to the last W = 4,096 tokens. The cache becomes a ring buffer of W entries per layer: "the keys and values for the timestep i are stored in position i mod W of the cache", which its paper says "reduces the cache memory usage by 8x" at 32K (Mistral 7B, section 2, vendor). Each entry is unchanged; what a layer keeps, and what a decoded token reads, stops growing at W.
Reach grows with depth (Fig. 5): after L local layers the last token can be influenced by the previous L · (W − 1) tokens. Mistral's paper says "hi can access tokens from the input layer at a distance of up to W × k tokens", about 131K for 32 layers of 4,096, a "theoretical attention span".
swa64_g3 pattern; Gemma 3 uses five then one).Fig. 5 is a calculation of reachability (which positions can influence the query through some path), not of attention weights.
Interleaves. Most models that use windows keep some global layers. Gemma 3 uses "a pattern of 5 local layers for every global layer" with a span of "only 1024 tokens", introduced because of "the memory explosion of the KV cache" at 128K (Gemma 3 report, vendor); with a global layer after every five, information never travels more than five layers before it can reach the whole context. gpt-oss alternates "banded window and fully dense patterns, where the bandwidth is 128 tokens" (model card). Gemma 3's report measured the trade (section 5.2): ratio and window changes have "minimal impact on perplexity", and the cache overhead at 32K falls from 60% of model memory with global-only attention to under 15% with 1 : 3 and W 1,024 (figures as the Long context child quotes them).
Gemma 2 alternates 1 : 1 with W 4,096 (context 8,192). Gemma 3 uses RoPE base 10K on local layers and 1M on global ones. Gemma 4 keeps 5 : 1 with W 1,024 (50 and 10 layers in the 31B config). Llama 4 uses chunked attention instead: 36 of Maverick's 48 layers attend only within fixed 8,192-token chunks (attention_chunk_size), a window that resets at each chunk boundary, and 12 are global (its config, as the LLM Architecture Gallery child reads it).
Cost, when, how to check. A local layer forgets everything older than W unless another layer carried it; interleaving brings back one full cache per global layer, so the long-context saving is set by the share of global layers (5 : 1 keeps about a sixth of the full cache). Kernels must handle the window (FlashAttention's window_size) and the cache must be a ring buffer or a paged cache that frees old blocks. It matters at contexts several times W; below W the window changes nothing. Check sliding_window and layer_types (Gemma 3: sliding_window_pattern, every 6th layer global). In transformers 5.20.1 a window keeps keys with kv_idx > q_idx - sliding_window, W keys including the query. Whole-model memory with windows credited, and what windows do to recall at 128K, are on Long context.
measured on Apple M1 Pro (MPS training, CPU evaluation): the tiny GPT trained with every layer local at W = 16, 32, 64 (the lab's run) and 128, against full attention (W = 256, the training length), plus two interleaves (layers 3 and 6 global); and the full-attention model served with a window it was never trained with. Held-out loss on the lab's 192 fixed validation windows, and by position.
The lab's W 64 interleave also beat full attention: 2.154 against 2.160 on 100 windows.
The problem. Windows bound what is kept by distance, and the global layers still read everything. Sparse attention bounds what is read by relevance: every entry stays in memory, and each query attends to the k entries most likely to matter. That works only if attention really is concentrated on a few keys, and if those keys can be found without computing full attention.
The premise, measured. In SmolLM2-135M on 1,024 tokens, a query's own top 16 keys (of at least 257) hold 75% to 94% of its attention in layers 13 to 30, while the last 64 keys plus position 0 hold only 46% to 76%: concentrated, and not on the most recent tokens, so NSA and DSA select by score, not distance. These are oracle top-k, an upper bound for any selector; Which keys are read shows any query and layer. measured on Apple M1 Pro (CPU)
measured on Apple M1 Pro (CPU): SmolLM2-135M revision 93efa2f0 on 1,024 tokens of TinyStories validation text, queries at positions 256 to 1,023, averaged over heads and queries; and the Attention lab's tiny GPT (at_mha) on the 256-token running sequence, queries 64 to 255. Share of each query's attention captured by its own top k keys (oracle), with and without position 0, by the top 4 blocks, by the last 64 keys, and by the last 64 plus position 0.
Concrete. Native Sparse Attention (Yuan et al., DeepSeek-AI and Peking University, arXiv 2502.11089) computes three attentions per query, "compressed coarse-grained tokens, selectively retained fine-grained tokens, and sliding windows for local contextual information", and adds them with gates (each in [0, 1], from an MLP and a sigmoid on the query token). Its settings (section 4.1): a summary per block of l = 32 tokens with stride d = 16; the n = 16 selected blocks of l′ = 64 tokens "including the 1 initial block and 2 local blocks"; a window of w = 512.
It is trained with the sparsity in place ("native"), not applied after training, and the paper reports it above full attention on its own benchmarks and up to 11.6x fewer memory accesses per decoded token at 64K.
authors' results (section 4.1, Tables 1, 2, 4): a 27B-total, 3B-active MoE (30 layers, hidden 2,560, 64 heads in GQA groups of 4) pretrained on 270B tokens at 8K (section 1 says 260B; the paper disagrees with itself), then extended to 32K with YaRN. General benchmarks average 0.456 against full attention's 0.443; LongBench 0.469 against 0.437; at 64K up to 9.0x forward and 6.0x backward speedup in training. Table 4 counts what one decode step must load: 2,048 equivalent tokens against 8,192 at 8K (4x), 2,560 at 16K (6.4x), 3,584 at 32K (9.1x), 5,632 against 65,536 at 64K (11.6x), an expected speedup, a calculation. Not run here: it needs Triton kernels on CUDA and contexts long enough to have blocks to skip.
One query over 64 earlier tokens, blocks of 8 and 4 selected blocks illustrative. Selection reuses the compressed scores, so finding blocks is cheap, and whole blocks keep the kernel's reads contiguous.
Concrete. DeepSeek Sparse Attention (V3.2-Exp, shipped 29 September 2025; V3.2 technical report, arXiv 2512.02556) is simpler. A lightning indexer with a few small heads scores every cached token for the current query, and MLA's attention then runs over the top k only. V3.2's config: index_n_heads 64, index_head_dim 128, index_topk 2048. GLM-5 (February 2026) has the same three fields (32 indexer heads of 128, top 2,048) on an MLA backbone.
Fig. 6: one square per cached token of the running sequence (226 tokens), k = 16 (V3.2: 2,048). Scores: SmolLM2-135M's real attention from the last token, layer 18, mean of 9 heads, standing in for the indexer: an oracle, the best any indexer could do. measured on Apple M1 Pro (CPU)
ReLU instead of a softmax, and FP8 (the indexer "can be implemented in FP8"), make each score cheap, but every token is scored: DSA "reduces the core attention complexity of the main model from O(L2) to O(Lk)", while "the lightning indexer still has a complexity of O(L2)" (DeepSeek). DSA sits on MLA's MQA mode because a selected entry must be shared by all heads for the kernel to be efficient. Memory goes up: 68.6 + 15.25 = 83.9 KiB per token in bf16 with the indexer keys. Unlike MLA, exact up to its low-rank bottleneck, DSA is an approximation, trained in: DeepSeek "deliberately aligned the training configurations of DeepSeek-V3.2-Exp with V3.1-Terminus" and reports "performance on par with V3.1-Terminus" (model card, vendor).
When it matters, how to check. Only past k: below 2,048 tokens DSA reads everything. And the indexer's read grows with the context: at 131,072 tokens it reads 14x more numbers than attention does, so a decoded token reads about 24% of what V3 reads, not 2,048 / 131,072 = 1.6% (bf16, calculation; FP8 indexer keys halve that part). Check index_topk and index_head_dim (transformers 5.20.1: F.relu(scores), then index_scores.topk(topk, dim=-1)), and judge quality with long-context retrieval rather than perplexity: a selector that misses the one needed token barely moves average loss (Long-context and multimodal benchmarks).
64 tokens; CSA at its real 4 tokens per entry (top-3, 8-token window); HCA at 16 per entry instead of 128 illustrative. Real numbers at 1M tokens in the last step.
Concrete. V4 (April 2026, DeepSeek-V4 report) changes what is stored, with two layer types interleaved. CSA (Compressed Sparse Attention) merges every m = 4 tokens into one 512-number entry, with overlapping blocks (each entry built from 2m = 8 tokens through two weight series), then applies DSA to the merged entries: an indexer of 64 heads of 128, in FP4, picks the top 1,024 (V4-Pro) or 512 (V4-Flash). HCA (Heavily Compressed Attention) merges every 128 tokens, without overlap, and reads all of them. In V4-Pro's config 30 layers are CSA and 31 HCA (compress_ratios, read 2026-10-18).
The stepper beside follows one decode step; switch the layer type above it.
Both layer types keep a window of 128 uncompressed recent tokens (a query may attend only to completed blocks, so without it its own unfinished block, usually the most relevant, would be invisible) and use each entry as key and value for every query head, MLA's decode shape.
Shared-KV multi-query attention: each entry is key and value for every query head, 64 in Flash and 128 in Pro. Low-rank queries and a grouped output projection: queries come from a latent (1,024 in Flash, 1,536 in Pro), MLA's query trick; head outputs are projected in 8 or 16 groups to 1,024 each before the final projection, because c · nh is large. Partial RoPE and a sink: RoPE on the last 64 dimensions; because an entry is also a value, the output is rotated back by the query's position so it carries relative position; a learned sink logit per head (section 6). Layout: V4-Flash has 43 layers, the first two pure sliding window, the rest alternating CSA and HCA; V4-Pro 61, the first two HCA, the rest alternating. Storage: entries in FP8 except the 64 RoPE dimensions, which stay BF16, nearly halving the cache against pure BF16.
DeepSeek's figures: against BF16 GQA-8 with head dimension 128, the V4 cache is about 2% at 1M tokens; against V3.2 at 1M, V4-Pro needs 27% of the single-token FLOPs and 10% of the cache, V4-Flash 10% and 7%. The GQA-8 baseline is already 16 times smaller than MHA with 128 heads of the same size, so "2% of a vanilla transformer" overstates it. It is built for million-token contexts and long agent loops, at the price of lossy summaries and a more complex stack. In the bf16 convention of section 7, V4-Pro holds 7.7 KiB per token of entries plus 1.9 KiB of indexer keys.
The inputs: V4-Pro's split of its 59 alternating layers (30 CSA and 29 HCA, so 31 HCA with the first two, confirmed by compress_ratios) and the precision of the indexer keys (FP4, half a byte per dimension, an assumption).
FP8 indexer keys give 2.17% and none 1.78%, so the reported "about 2%" is robust to that assumption. The 128-token windows add a fixed 128 × 576 × 61 = 4.5 MB per sequence. derived
| Per layer | Stored | Read per decoded token | At 1M tokens: stored / read | How keys are chosen | Exact? |
|---|---|---|---|---|---|
| Dense (MHA, GQA, MLA) | every token | every token | 1,000,000 / 1,000,000 | all | yes (MLA up to its low-rank bottleneck) |
| Sliding window | last W | last W | W / W | by distance | no: older tokens are gone |
| NSA | every token (+ block summaries) | summaries + 16 blocks + window | see Table 4 | compressed-branch scores, by block | no: selection, trained in |
| DSA (V3.2) | every token + indexer key | top 2,048, the indexer scores all | 1,000,000 / 2,048 | a separate indexer, by token | no: selection, trained in |
| MoBA (Kimi, Llama-8B-1M-MoBA) | every token (block means of keys) | top 12 blocks of 4,096, the current block always among them | 1,000,000 / 49,152 | query against each block's mean-pooled keys, no learned gate | no: selection, trained in |
| QSA (Qwen3.8-Flash-Next) | every token + pooled indexer keys | top 512 blocks of 4 (2,048 tokens) + the unfinished block | 1,000,000 / 2,048 | an indexer on micro-blocks of 4 | no: selection, trained in |
| MSA (MiniMax-M3) | every token + index key | top 16 blocks of 128 per GQA group | 1,000,000 / 2,048 per group | index branch, a block scores its best token | no: selection, trained in |
| CSA (V4-Pro) | 1 entry per 4 tokens + window | top 1,024 + window | 250,000 + 128 / 1,024 + 128 | indexer on merged entries | no: compression and selection |
| HCA (V4) | 1 entry per 128 tokens + window | all entries + window | 7,813 + 128 / all 7,941 | none: reads all | no: heavy compression |
Selection still needs the whole cache resident so that something can be selected; compression shrinks what is resident. HCA reads every one of its entries yet reads fewer than DSA stores by two orders of magnitude; running CSA and HCA together gives a cache that is precise nearby (the window, CSA's selected entries) and cheap far away (HCA's coarse summaries of everything).
The same idea at other labs, each taught on its lab's page. MoBA (Mixture of Block Attention, Moonshot AI, February 2025) is the plainest block selector: split the context into blocks, score each block by the query's inner product with the mean of its keys, attend to the top k blocks; future blocks are masked and the query's own block is always selected, with a causal mask inside it. The gate adds no parameters, so a layer can switch between MoBA and full attention; Llama-8B-1M-MoBA keeps its last three layers full and runs the other 29 with blocks of 4,096 and top 12 (95.31% sparse at 1M tokens), with prefill up to 6.5 times faster at 1M tokens, and the paper says MoBA "has already been deployed to support Kimi's long-context requests" (Lu et al., arXiv 2502.13189, section 2 and 3). QSA (Qwen Sparse Attention) scores micro-blocks of 4 tokens, keys average-pooled, instead of single tokens, which cuts the indexer's quadratic work by about four; attention then reads the top 512 blocks, a budget of 2,048 tokens. At 1M tokens its attention module measured 7.6 times faster in prefill and 4.9 times in decode, not the 488 times the token count suggests, because the indexer still scans every block (Alibaba: Qwen). MSA (MiniMax Sparse Attention, M3) scores blocks of 128 keys by their best token, lets each GQA group keep its own top 16 blocks, and trains the index branch with a KL loss towards the main attention: selection coarser than DSA's per-token choice (MiniMax). And DSA in a sliding-window hybrid: Naive-N0.5-Flash replaced the nine global layers of its MiMo-V2.5 base with DSA (top 2,048) beside 39 sliding-window layers of 128 tokens, so no layer reads the whole context, while the full cache is still kept (Other notable providers).
Concrete. Softmax weights must sum to 1, so a head with nothing useful to read for this token still has to put its weight somewhere. Trained LLMs park it on a token whose value contributes little, nearly always the first: an attention sink (Xiao et al. 2023, StreamingLLM, arXiv 2309.17453). In SmolLM2-135M the root's Inside lab found it switching on at layer 12 (Fig. 7, steps 1 to 3), together with a massive activation (dimension 507 of token 0's residual reaching 20,155 against a median 1.56), and found the sink to be a cache problem: evicting token 0 from a sliding cache breaks the model, and keeping the first four tokens instead of one also gives 1.81. StreamingLLM keeps the first four tokens beside the window and runs on streams of "up to 4 million tokens".
sink preset, gpt-oss style; layer 4, head 5, its most sink-heavy head, at the last position): 97% of this head's weight goes to the sink (red), a score with no value, so the real tokens get the 3% the head chose to spend.Three fixes that remove the need for a real token.
attn_output_gate: true); Kimi K3 gates its MLA layers.Cost, when, how to check. A sink logit is H parameters per layer and one more softmax column (transformers 5.20.1 concatenates it in the eager path and drops it after the softmax); the gate is a dmodel by H · dh matrix per layer (Qwen3-Next fuses it into the query projection), about 7% more parameters for the tiny GPT. They matter when serving with windows or evicted caches, for quantisation (massive activations are what break low-bit formats) and for stability at high learning rates. Check sinks in gpt-oss's weights and attn_output_gate in Qwen's configs; otherwise measure the weight on token 0 by layer with eager attention (SDPA returns no weights).
StreamingLLM, Table 5 (authors): ARC-Easy questions streamed with a 1,024-token cache, Llama-2-7B-Chat scores 3.58 with a plain window against 71.34 with the sinks kept (one-shot 71.25); 13B 0.25 against 80.89; 70B 0.12 against 91.37. Qiu et al.'s setup: a 15B MoE (15A2B, 128 experts, top 8) and a 1.7B dense model, up to 3.5T tokens; their best gate is G1, elementwise after the attention output (a headwise gate: perplexity 5.792, MMLU 60.05); the 48-layer gated model reached perplexity 7.078 on 1T tokens where the baseline diverged.
measured on Apple M1 Pro (MPS training, CPU evaluation): three tiny GPTs with RoPE, same seed and batches: plain MHA (the lab's at_mha), MHA with a learned sink logit per head (the topic's sink preset, gpt-oss style), and MHA with an elementwise sigmoid output gate (added by this page's src/runs/av_model.py without editing the shared model, Qwen3-Next style). Attention statistics on the running sequence; losses on the lab's 192 fixed validation windows.
The tiny GPT forms no token sink (at most a few percent of a layer's weight on position 0 in every variant the lab trained), so it barely notices a sliding cache that evicts token 0; a real pretrained model does (SmolLM2 above).
The comparison that ties the sections together. For one layer of each real design, what one decoded token reads at a given context, and how much arithmetic it does per byte read. A step whose FLOPs per byte are below the GPU's balance point (an H100: 989 TFLOPS dense bf16 over 3.35 TB/s, about 295) waits on memory; above it, on arithmetic. Predict before you drag: which layers stop growing as the context passes 8K, and which one sits near the balance point?
At 131,072 tokens one layer reads 2 GiB under MHA (Llama 2 7B), 512 MiB under GQA-8, 144 MiB under MLA, 64 MiB under MQA and 16 MiB with a 4,096-token window. Every grouped-query layer does (query heads / KV heads) FLOPs per byte, 4 or 8 for these models, at every length: memory-bound, so its bytes are its time, and batching does not change that because each sequence has its own cache. Absorbed MLA makes 128 heads reuse one 576-number entry, about 242 FLOPs per byte (260.9 counting the query and output folds): near the H100's balance point, which is why DeepSeek can afford 128 heads. Windowed layers stop growing at their window. DSA's layer reads the indexer keys of every token plus 2,048 entries, so its read keeps growing with the context, at about a quarter of V3's at 131,072 tokens. V4's CSA and HCA layers read the least of the long-context designs.
Real deployments store some caches in FP8 or FP4 (V4 keeps entries in FP8 with the 64 RoPE dimensions in BF16; DeepSeek runs indexers in FP8 or FP4); the bf16 convention keeps the rows comparable. Paged allocation and batch sizing belong to Batching, KV cache and scheduling.
calculation from each config.json (the root's src/data/configs and the map's inputs; read 2026-10-18), bf16 for every cached number (indexer keys too), one sequence, the attention core only (scores and weighted sum, a multiply-add counted as 2 FLOPs). MLA is counted in its absorbed decode form; the DSA and CSA rows include the indexer reading every key. Gated DeltaNet layers read a fixed state (fp32) whatever the context; their FLOPs are left out (owned by Beyond attention). This arithmetic equals the root Config calculator's CC.cache on every design it handles (src/ladder/check_ladder.mjs). Whole-model totals at a context length are on Long context.
Optional. None of this is needed to follow sections 1 to 7; each block is self-contained.
The problem it targets. A softmax over thousands of keys gives every irrelevant key a small positive weight, and together they can outweigh the few relevant ones: the DIFF Transformer paper calls this attention noise. How it works (Ye et al., Microsoft Research and Tsinghua, arXiv 2410.05258): split each head's query and key into two halves, compute two attention maps, and subtract one from the other:
Noise common to both maps cancels, like a differential amplifier; the weights can now be negative. authors' results: "Diff Transformer requires only about 65% of model size or training tokens" to match a Transformer (a 6.8B DIFF matches an 11B Transformer; 160B tokens match 251B); 3B models on 350B tokens average 56.2 against 55.4 zero-shot and 58.0 against 56.4 five-shot (Table 8); multi-needle retrieval at 4K with 6 needles 0.85 against 0.55 (Table 2); attention on the answer span 0.27 against 0.03, on noise 0.01 against 0.51 (Table 3); largest attention logit 38.8 against 318.0 (Table 5). The cost: two softmaxes per head over half-size queries and keys, the same cache per token as the MHA it replaces (keys of both halves are stored), and a kernel that FlashAttention does not provide in one call. Adoption: transformers 5.20.1 ships a DiffLlama implementation (models/diffllama), but none of the 2026 open-weight configs this topic reads uses it; the variant that spread is the much cheaper gate of section 6. Not run here: the paper's gains appear at billions of parameters and hundreds of billions of tokens, and the tiny GPT has no long-range noise to cancel (its attention is mostly local: the closed table in section 5).
Read from the configs in the root's data (dates: release, as the Architecture gallery child lists them). The full per-layer strips are on the LLM Architecture Gallery page and the lineage on the root's Architecture map; this table is only the attention choice.
| Model (release) | Query : KV heads, head dim | Windows | Other |
|---|---|---|---|
| Mistral 7B v0.1 (2023-09) | 32 : 8, 128 | 4,096 in every layer | later Mistral models dropped the window: Mistral Small 3.1's config has sliding_window: null |
| Llama 3.1 8B / 70B (2024-07) | 32 : 8 / 64 : 8, 128 | none | GQA-8 at every size |
| Gemma 2 9B (2024-06) | 16 : 8, 256 | 4,096, alternating 1 : 1 | attention logits soft-capped at 50 (attn_logit_softcapping) |
| DeepSeek-V3 (2024-12) | 128 heads, MLA latent 512 + RoPE 64 | none | Kimi K2 copies it with 64 heads |
| Gemma 3 27B (2025-03) | 32 : 16, 128 | 1,024, 5 local : 1 global | QK-norm; RoPE base 10K local, 1M global |
| gpt-oss-120b (2025-08) | 64 : 8, 64 | 128, alternating 1 : 1 | a learned sink logit per head |
| Qwen3-Next-80B-A3B (2025-09) | 16 : 2, 256 (1 layer in 4) | none | 3 Gated DeltaNet layers per attention layer; output gate on attention |
| DeepSeek-V3.2 (2025-12) | MLA as V3 | none | DSA, top 2,048 |
| GLM-5 (2026-02) | 64 heads, MLA latent 512 + RoPE 64 | none | DSA, top 2,048 |
| Gemma 4 31B (2026-04) | 32 : 16, 256 local; 512 on global layers | 1,024, 5 local : 1 global (50 + 10) | attention_k_eq_v: global layers use one tensor for keys and values |
| DeepSeek-V4-Pro (2026-04) | 128 heads on shared 512-number entries | 128 uncompressed | CSA and HCA, sink logits |
| Qwen3.5-397B-A17B (2026-02) | 32 : 2, 256 (1 layer in 4) | none | attn_output_gate: true, 45 linear + 15 full layers |
| Mistral Large 4 (2026-10) | 64 heads, MLA latent 512 + RoPE 64 | none stated | DSA, top 2,048; every 4th layer NoPE; nine NoPE layers (39, 43, ..., 71) read layer 35's latent cache instead of writing their own, so 63 of 72 layers hold a cache |
Config fields: num_attention_heads, num_key_value_heads, head_dim, sliding_window, layer_types or sliding_window_pattern, kv_lora_rank, qk_rope_head_dim, index_topk, compress_ratios, attn_output_gate, read 2026-10-18 from the files in the root's src/data/configs and src/map/inputs/configs; Mistral Large 4's row is from vLLM's 29 October 2026 blog, not a saved config. Gemma 4's global head dimension 512 is how transformers 5.20.1 builds those layers (global_head_dim), found by the gallery child. The pattern of three years: fewer KV heads everywhere; windows for most layers in Google's and OpenAI's models; a latent in DeepSeek's line and its followers; and from late 2025, selection (DSA) and compression (V4) on top of the latent, and linear layers with a few gated full-attention layers in Qwen's line (Beyond attention owns the linear layers).
Every quote below is located by pattern in the source by src/code/extract_code.py, so the file and line are checked, not typed: transformers v5.20.1 (the topic's pinned clone) and the topic's tiny GPT.
repeat instead of repeat_interleaverepeat (0, 1, 0, 1, ...) instead of repeat_interleave (0, 0, 0, 0, 1, ...) runs without error and wires every head to the wrong keys: the trained GQA-2 went from 2.1025 to 2.9907 held-out (the root's Attention lab). Without the expansion, or enable_gqa=True, SDPA fails loudly instead: "The size of tensor a (8) must match the size of tensor b (2)". measuredkv_lora_rank 512 like DeepSeek, but its released modeling_motif.py caches the expanded keys (16 heads × 192) and values (16 × 128): 530 KiB per token, not the 59.6 KiB a latent cache would hold (found by the LLM Architecture Gallery child). Whether a model caches the latent is a property of its code, not its config.num_key_value_heads to size an MLA cachenum_key_value_heads: 128; the cache is kv_lora_rank + qk_rope_head_dim = 576 numbers per layer, 68.6 KiB per token, not the 3.81 MiB that 128 heads of 128 keys and values would give (the root's Config calculator handles this; a hand calculation from the head count is 57x too big).kv_idx > q_idx - sliding_window: W keys including the query, not W previous tokens plus the query. Gemma 3's sliding_window_pattern: 6 makes layers 6, 12, ... global ((i + 1) % 6), not layers 1, 7, ...; gpt-oss starts with a local layer. Checking the mask with a probe sequence (one token per position, read the attention weights with eager attention) catches both.sdpa "does not support output_attentions=True" and returns an empty tuple (the root's Inside lab); load the model with attn_implementation="eager", as this page's SmolLM2 probe does.Seven questions of the kind asked in model design reviews and interviews. Each reveal does the arithmetic with this page's code (the same formulas as the root's Config calculator) or shows the measured or published result.
Sliding window or sparse attention for long context? A window caps memory and reads but forgets: anything older than the window must be relayed through layers, which models often fail to learn, so designs keep some global layers (Gemma 3 1 in 6, gpt-oss 1 in 2). Sparse attention keeps everything and reads a learned subset, so it can still retrieve one old token, but the cache is as large as before and the selector costs something at every step. Windows when memory is the limit, sparse attention when reads and long-range recall both matter, and often both together with GQA or MLA underneath.
Built 2026-10-19, rebuilt 2026-10-23 to the teaching contract and on 2026-11-09 to the split layout with seven 3D figures, in the knowledge base repository (src/README.md says how). Measured results: Apple M1 Pro, the topic's tiny GPT (MPS training, CPU evaluation) and SmolLM2-135M (CPU inference). What transfers to a datacenter GPU: which variant wins, the ratios of bytes and FLOPs, the shape of the curves; what does not: absolute speeds, and any quality gap that depends on scale (sections 2 and 3 say where the published large-scale results disagree with the toy).
The text is the topic's running sequence (Roxy and the icy hill) as SmolLM2-135M tokenizes it. Pick a query token and a layer: the shading is SmolLM2's real attention from that query, and the underline marks what each variant lets the query read. The counters say how much of the real attention the variant keeps.
measured on Apple M1 Pro (CPU): SmolLM2-135M revision 93efa2f0, fp32, eager attention, 226 tokens, no BOS (its tokenizer adds none). Weights are stored at 64 levels of each row's maximum. The sparse rows use the real weights to choose what to keep, an oracle: a real indexer (DSA) or compressed-branch score (NSA) only approximates that choice, so the "kept" numbers are an upper bound for those methods. SmolLM2 was trained with full attention; nothing here is SmolLM2 running a variant, only which of its own weights a variant would let through.
Stacked-window reach is drawn in Reading section 4, and the per-layer top-k table is in section 5.
Links checked 2026-10-19; the DeepSeek-V3.2 arXiv and V4 report links were added 2026-10-23 from the DeepSeek page, where they are cited. Times for outside sources are rough reading times; times for knowledge-base pages are the ones their headers state, where they state one. "maker" marks a source written by the lab that built the method; "third-party" everything else.