Attention variants: MHA, MQA, GQA, MLA, sliding window, sparse attention and sinks

What each past token leaves behind in each layer, what the next token reads, and what the model gives up: MHA, MQA, GQA, MLA, windows, NSA, DSA, MoBA, DeepSeek-V4's compressed attention, sinks and gates. Measured on the topic's tiny GPT and SmolLM2-135M (Apple M1 Pro); real configs; published results kept apart. A child of Topic: llm-architecture. Data as of October 2026. Reading: 37 min, plus 28 in closed details.

The idea in one screen

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.

  1. MHA: every head keeps its own key and value. Llama 2 7B: 32 heads of 128, a key (teal) and a value (purple) each, 8,192 numbers per token per layer, and the new query reads all 24 entries. This height is the scale every later step is drawn against (the wireframe).
  2. Smaller entries: share key and value heads (GQA). Llama 3.1 8B keeps 8 KV heads for its 32 query heads: 2,048 numbers, a quarter. Every token is still kept and read. Section 2.
  3. Smaller still: cache a latent (MLA). DeepSeek-V3 caches a 512-number latent (green) and a 64-number RoPE key (teal), 576 numbers, yet every one of its 128 heads keeps its own keys. Section 3.
  4. Fewer kept: a sliding window. Mistral 7B v0.1 keeps only the last W = 4,096 tokens in every layer (6 drawn); older entries are gone (dashed), and what a token reads stops growing. Section 4.
  5. Fewer read: select the top k (DSA). DeepSeek-V3.2 keeps every MLA entry plus a 128-number indexer key (gold), and attention reads only the top 2,048 (5 drawn); the rest stay resident, unread. Section 5.
  6. Fewer stored: merge blocks (V4's CSA). DeepSeek-V4-Pro merges every 4 tokens into one 512-number entry, keeps the last 128 tokens raw, and reads the top 1,024 merged entries plus that window. Section 5.
  7. Where unused weight goes: sinks and gates. Softmax weights sum to 1, so a head with nothing worth reading parks its weight on token 0 (the thick flow) or, with a learned sink logit, sends it nowhere (red), at no cost in cache. Section 6.

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.

KV head
one key and one value projection; MHA has one per query head, GQA one per group of query heads, MQA one in all.
Latent (MLA)
a short vector per token from which every head's key and value are rebuilt; only it is cached.
Absorption
folding the latent's up-projections into the query and output projections, so decode never rebuilds keys.
Decoupled RoPE key
a small extra key that carries position for MLA, because RoPE cannot pass through the absorbed product.
Local, global layer
a layer that attends to the last W tokens (a sliding window) or to all of them.
Indexer, top-k
a cheap scorer that picks which k cached entries the real attention reads (DSA).
Compressed entry
one cache entry that stands for a block of tokens (NSA's summaries, V4's CSA and HCA).
Sink
where a head puts weight it does not want to spend: the first token, a learned logit, or a closed gate.
The variants in one table, with the evidence for each (reference)
DesignEach token stores, per layerTiny GPTReal example (bf16, all layers)Quality evidence
MHA multi-head attentiona key and a value per head: 2 · H · dh512Llama 2 7B: 512 KiB per tokenthe reference
GQA grouped-querya key and a value per KV head: 2 · Hkv · dh128 (2 KV heads)Llama 3.1 8B (8 KV heads): 128 KiBtiny GPT: within seed spread of MHA measured; 7B, 1.33T tokens: MMLU 41.2 vs MHA 45.2 DeepSeek-V2 Table 8
MQA multi-queryone key and one value: 2 · dh64Llama 3.1 8B as MQA: 16 KiB (what-if)tiny GPT: same; 7B: MMLU 37.9 same table
MLA multi-head latenta latent c and a shared RoPE key: dc + dr64 + 16 = 80DeepSeek-V3: 68.6 KiBMoE 16B and 250B: better than MHA DeepSeek-V2 Table 9; tiny GPT: about 0.09 worse measured (section 3)
Sliding window Was MHA/GQA, but only the last W tokens are kept512, for 64 tokensMistral 7B v0.1 (W 4,096): 0.50 GiB at 128K instead of 16 GiBtiny GPT: window 64 within noise of full; smaller windows cost more (section 4)
Local : globallocal layers keep W tokens, global layers keep allmixedGemma 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 kn/aDeepSeek-V3.2: 83.9 KiB held, attention reads 2,048 entriesV3.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 windown/aDeepSeek-V4-Pro: 7.7 KiB of entries plus 1.9 KiB of indexer keys per tokenabout 2% of a GQA-8 cache at 1M tokens DeepSeek
Sink, gateno extra cache: a learned logit per head (gpt-oss), or a sigmoid gate on each head's output (Qwen3-Next)0gpt-oss-120b; Qwen3-Next, Qwen3.5gate: 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.

1. Why the cache is the cost

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.

  1. One token's entry. For each of its 32 layers, a token leaves a key (teal, front) and a value (purple, behind) for each of 8 KV heads of 128 numbers: 2 × 8 × 128 × 32 = 65,536 numbers, 128 KiB in bf16.
  2. Computed once, then only read. Every new token appends its brick and nothing already cached changes: 12 tokens (drawn) hold 1.5 MiB, and a 32,768-token sequence 32,768 × 128 KiB = 4 GiB derived.
  3. Every decoded token reads all of it. The cache sits in HBM; to produce one token, the GPU streams every brick into the die once. Batching does not share this read: each sequence has its own bricks.
  4. Four FLOPs per byte. Each number read serves the 32 / 8 = 4 query heads that share its KV head: about 4 FLOPs per byte (blue) against an H100's balance point of about 295 (989 TFLOPS dense bf16 over 3.35 TB/s, grey). The arithmetic units mostly wait.
  5. Measured: time follows bytes. One layer at this shape, batch 4, 32,768 cached tokens: MHA, GQA-8, absorbed MLA and MQA cache 8,192, 2,048, 576 and 256 numbers per token per layer (teal columns) and took the times in orange: the two rows fall in the same order.

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 and the running example (the symbols used below; the tiny GPT and SmolLM2)

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.

A Tesla P100 package photographed in near infrared: the large GP100 GPU die in the centre, with two HBM2 memory stacks on each side, all on one interposer
Where the cache lives. A Tesla P100 in near infrared: the GP100 die in the centre, two HBM2 memory stacks on each side. Every cached key and value sits in stacks like these, and each decoded token streams all of them into the die once, so the bytes each past token leaves behind set the decode speed. Photo: FritzchensFritz, CC0, Wikimedia Commons.

2. MQA and GQA: share keys and values across heads

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.

  1. MHA: one KV head per query head. The tiny GPT's 8 query heads (orange) each read their own key head (teal) and value head (purple): 2 × 8 × 32 = 512 numbers per token per layer (the column), 6,144 bytes over its 6 layers in bf16.
  2. GQA-4: pairs share. 4 KV heads, each read by 2 query heads: 256 numbers, half the cache.
  3. GQA-2: groups of four. 2 KV heads, each read by 4 query heads, the grouping of Llama 3.1 8B: 128 numbers, a quarter.
  4. MQA: all share one. One key head and one value head for all 8 query heads: 64 numbers, an eighth of MHA.
  5. The cache falls 8 times; the loss does not move. The four trained from scratch, side by side, with each run's held-out loss on 100 windows (a second seed in brackets): every variant lands inside the spread between MHA's two seeds.

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.

At scale the gap appears: published, not run here

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:

A trained MHA cache uses far fewer directions than it stores

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

Converting a trained MHA model: averaging, projection, uptraining (measured; the design angle when you own an MHA checkpoint)

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:

Predict: the tiny MHA's 8 key heads and 8 value heads are averaged into 2 groups (GQA-2), no training. Its held-out loss was 2.137. What is it now?

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)

3. MLA: cache a latent, rebuild the heads

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.

  1. A token arrives. Token t enters one of V3's 61 attention layers as its hidden state ht: 7,168 numbers, 112 cells. Nothing of it is cached yet.
  2. Compress into the latent. The down-projection WDKV (green glass) maps ht to the latent cKVt of dc = 512 numbers. This one vector stands in for the keys and values of all 128 heads, which is where the saving comes from: 512 instead of 2 × 128 × 128.
  3. Add the decoupled RoPE key. Rotary position embeddings cannot pass through the absorbed product (it would differ for every pair of positions), so a separate key kRt = RoPE(WKRht) carries position: dRh = 64 numbers, one copy shared by all 128 heads.
  4. Write 576 numbers to the cache. Only [cKVt ; kRt], 512 + 64 = 576 numbers, is written to this layer's cache. That is the whole per-token cost of MLA: (dc + dRh) × l = 576 × 61 = 35,136 numbers, 70,272 bytes in BF16.
  5. Prefill: rebuild the heads (MHA mode). In training and prefill attention is compute-bound and many queries run at once, so each head's own slice of WUK and WUV (purple glass) rebuilds its 128-number key and value from the latent, and every key is extended by the shared kR. These 2 × 128 × 128 = 32,768 numbers per token (dashed) are computed, used and discarded: never cached.
  6. Decode: absorb, every head reads one entry (MQA mode). In decode WUKi moves onto the query side, (WUKi)⊤qt,i scored straight against cKVj, and WUVi folds into WO. All 128 query heads (orange) read the same 576-number entry of every earlier token, its first 512 serving as the value: nothing is expanded, so a decoded token reads 576 numbers per earlier token per layer, not 32,768.
  7. Compare with standard MHA. Per token per layer MLA caches 576 numbers where standard MHA with V3's 128 heads of 128 would cache 2 × 128 × 128 = 32,768 (dashed, to the same scale): about 57 times fewer, the size of GQA with only 2.25 groups (V2 paper). Over 61 layers that is 68.6 KiB per token against 3.81 MiB.

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.

cj = WDKV xj    khj = WUKh cj    vhj = WUVh cj
cj
the latent, dc numbers per token per layer (normalised by an RMSNorm): the only content that is cached (DeepSeek-V3 dc = 512; tiny GPT 64)
WDKV
down-projection dmodel to dc, shared by keys, values and all heads
WUKh, WUVh
head h's own slices of the up-projections, dc to dh: nothing is shared between heads; the per-head structure is stored compressed

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:

qh · khj = qh · (WUKh cj) = ((WUKh)T qh) · cj = q̃h · cj
output = Σh WOh WUVh ( Σj ahj cj )
q̃h
the query moved into latent space: dc numbers, once per step per head
WOh WUVh
folded once, offline (the V2 paper: absorb WUK into WQ and WUV into WO)

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

MLA beyond DeepSeek: Kimi K2, GLM-5, NoPE and gated MLA, QK-Clip (variants in released models)

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.

Checked: the absorbed form equals the naive one on a trained model, and the RoPE trap (measured)

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.

Three ways to decode MLA: bytes, FLOPs and FLOPs per byte, per layer (calculation)

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.

Predict: DeepSeek-V3 decodes one token at 32K context. Per layer, which costs more arithmetic: the absorbed form, or keeping a full MHA-style expanded cache?
Why MLA trails MHA on the tiny GPT: three runs (measured investigation)

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

4. Sliding windows and local : global layers

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

  1. One local layer. The last token of the 226-token running sequence (orange) reads only the last W = 16 tokens of layer 1 (lit); everything older is out of reach.
  2. Layer 2 relays. Each of those tokens had already mixed its own window in layer 1, so after two layers the last token can be influenced by the previous 2 × (W − 1) = 30 tokens: the reach climbs one window per layer.
  3. Six local layers. After all 6 layers the reach is 6 × (W − 1) = 90 tokens; Mistral 7B v0.1's 32 layers of 4,096 give the "about 131K" its paper calls a theoretical span.
  4. 2 local : 1 global. The front stack makes layers 3 and 6 global: after layer 3 every token reaches the last one directly, whatever W is (the tiny GPT's swa64_g3 pattern; Gemma 3 uses five then one).
  5. Theoretical, not guaranteed. In the all-local stack a far token must be relayed through every layer, one window per hop (back); through a global layer it arrives in one (front). Nothing guarantees a model learns the relay, which is why most window designs keep global layers.

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

Interleaves in other released models: Gemma 2 and 4, Llama 4's chunks (configs)

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: how small can the window be on the tiny GPT? (window sweep, interleaves, serving with an untrained window)

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.

Predict: the tiny GPT trained with every layer limited to a 16-token window, then the same with layers 3 and 6 made global (2 local : 1 global). How much of the gap to full attention does the interleave close?

The lab's W 64 interleave also beat full attention: 2.154 against 2.160 on 100 windows.

5. Sparse attention: keep everything, read a few

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)

The premise, layer by layer: top-k, block and window mass in SmolLM2 and the tiny GPT (measured table)

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.

NSA: three branches and a learned mix

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.

ot = gtcmp Attn(qt, K̃cmp, Ṽcmp) + gtslc Attn(qt, K̃slc, Ṽslc) + gtwin Attn(qt, K̃win, Ṽwin)
cmp, slc, win
the three branches above: block summaries, the selected blocks' tokens, the last w tokens
gt
gates in [0, 1] from the query token

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.

NSA's reported results (authors' runs; not run here)

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.

NSA reads a summary of everything, a few whole blocks, and the recent window, then mixes them

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.

DSA: a lightning indexer picks the top 2,048 tokens

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.

  1. The cache: every entry stays resident. Each of the 226 earlier tokens of the running sequence keeps its MLA entry (576 numbers, green) and a 128-number indexer key (the gold top). Nothing is evicted: any entry may be selected later. That is why DSA stores more than MLA alone: 83.9 KiB per token against V3's 68.6 in bf16.
  2. The lightning indexer scores every entry. For the new token, a few small indexer heads compute It,s = Σj wt,j ReLU(qt,j · ks) against every cached indexer key (height: the score). ReLU instead of a softmax and FP8 make each score cheap, but every token is scored: the indexer is still O(L2) over a sequence.
  3. Keep the top k. Only the k highest-scoring entries (blue) go to the real attention: k = 16 here, 2,048 in V3.2. Here the scores are the model's real attention, so these are the best 16 any indexer could pick; the tallest is position 0, the sink of section 6.
  4. MLA attention reads only the selected entries. The 128 query heads, in MLA's absorbed (MQA) mode, read the 16 selected 576-number entries and nothing else (the streams, denser for larger weights): 16 of 226 entries, holding 97% of this query's real attention. A selected entry must be shared by all heads for the kernel to be efficient, which is why DSA sits on MLA.
  5. What one decoded token reads at V3.2's scale. At 131,072 cached tokens, per layer: the indexer reads 131,072 keys of 128 numbers (16.8M numbers) and attention reads 2,048 entries of 576 (1.18M). Together about 24% of what dense V3 reads (75.5M), not 2,048 / 131,072 = 1.6%: the indexer's read grows with the context. Below 2,048 tokens DSA reads everything.
  6. How it learned to choose: two training stages. V3.2 continued from V3.1-Terminus. Stage 1, dense warm-up: the model frozen, only the indexer trained, for 1,000 steps (2.1B tokens), to match the main attention distribution (scores summed over heads and normalised) with a KL-divergence loss. Stage 2, sparse: 943.7B tokens in which the whole model adapts to top-2,048 selection, while the indexer, detached from the main graph, keeps fitting the attention over the selected set (columns to scale). DSA is an approximation trained in, not applied afterwards.

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)

It,s = Σj=1HI wIt,j · ReLU(qIt,j · kIs)     ut = Attn(ht, { cs : It,s ∈ Top-k(It,:) })
It,s
the index score of earlier token s for query token t
HI
the (small) number of indexer heads, with query qI and weight wI from the query token
kIs
a 128-number indexer key cached for every token, beside its MLA entry cs

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

One decode step under V4: merge blocks into entries, keep a raw window, then select (CSA) or read all (HCA)

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.

DeepSeek-V4: compress what is stored, then select

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.

  1. Tokens arrive. Each token gets a 512-number entry Cj (key and value at once) and a compression logit Zj. Nothing is cached per token yet, except in the window.
  2. Every 4 tokens merge into one entry. A block's entries are averaged channel by channel with learned weights, softmax over the block of Z + B. CSA's blocks overlap: each entry is built from 8 tokens (the bracket) through two weight series. The cache keeps one entry per 4 tokens.
  3. Keep the last 128 tokens raw. A query may attend only to completed blocks, so without a window it could not see its own unfinished block, usually the most relevant tokens. V4 keeps the last 128 tokens uncompressed (8 drawn).
  4. The indexer picks the top-k entries; attention reads them and the window. A DSA indexer (64 heads of 128, FP4) scores every merged entry and the query reads the top 1,024 (V4-Pro; 512 in Flash; 3 drawn) plus the window, with each entry serving as key and value for all 128 heads.
  5. At 1M tokens, per CSA layer. Stored: 250,000 merged entries + 128 in the window. Read per decoded token: 1,024 + 128. The indexer still scores all 250,000, a quarter of what DSA's indexer scores on raw tokens.
CCompi = Σj ∈ block i Sj ⊙ Cj     Sblock i = Softmaxrow(Zblock i + B)
Cj, Zj
token j's 512-number entry and its learned compression logits (Zj = WZ hj)
B
a learned per-position bias; the softmax runs across the block, per channel

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.

The rest of V4's attention layer: queries, output groups, partial RoPE, sink, layout, storage (report)

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.

Reproducing the reported 2% from the config (derived, two stated inputs)

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

  1. One stored entry: 448 FP8 dimensions at 1 byte plus 64 BF16 RoPE dimensions at 2 bytes = 576 bytes.
  2. A CSA layer stores one entry per 4 tokens, 576 / 4 = 144 bytes per token, plus one 128-dimension indexer key per 4 tokens, 128 × 0.5 / 4 = 16 bytes: 160 bytes per token.
  3. An HCA layer stores 576 / 128 = 4.5 bytes per token.
  4. V4-Pro: 30 × 160 + 31 × 4.5 = 4,939.5 bytes per token.
  5. GQA-8 in BF16 over the same 61 layers: 2 × 8 × 128 × 2 = 4,096 bytes per layer, 249,856 bytes per token. Ratio: 1.98%.

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 layerStoredRead per decoded tokenAt 1M tokens: stored / readHow keys are chosenExact?
Dense (MHA, GQA, MLA)every tokenevery token1,000,000 / 1,000,000allyes (MLA up to its low-rank bottleneck)
Sliding windowlast Wlast WW / Wby distanceno: older tokens are gone
NSAevery token (+ block summaries)summaries + 16 blocks + windowsee Table 4compressed-branch scores, by blockno: selection, trained in
DSA (V3.2)every token + indexer keytop 2,048, the indexer scores all1,000,000 / 2,048a separate indexer, by tokenno: 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 them1,000,000 / 49,152query against each block's mean-pooled keys, no learned gateno: selection, trained in
QSA (Qwen3.8-Flash-Next)every token + pooled indexer keystop 512 blocks of 4 (2,048 tokens) + the unfinished block1,000,000 / 2,048an indexer on micro-blocks of 4no: selection, trained in
MSA (MiniMax-M3)every token + index keytop 16 blocks of 128 per GQA group1,000,000 / 2,048 per groupindex branch, a block scores its best tokenno: selection, trained in
CSA (V4-Pro)1 entry per 4 tokens + windowtop 1,024 + window250,000 + 128 / 1,024 + 128indexer on merged entriesno: compression and selection
HCA (V4)1 entry per 128 tokens + windowall entries + window7,813 + 128 / all 7,941none: reads allno: 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).

6. Sinks and gates: where unused attention goes

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

  1. The sink switches on at layer 12. SmolLM2-135M's weight on token 0 in each of its 30 layers (counted from 0, as the root's Inside lab does): at most 0.085 in layers 0 to 11, then 0.31 to 0.74 (red) from layer 12 on.
  2. Where the last token's weight goes. The last token of the running sequence in six layers (1, 6, 12, 18, 24, 30 counted from 1; mean of 9 heads; the rest binned by 9 positions): in the deep layers one column, token 0, outweighs whole stretches of real text.
  3. Evict token 0 and the model breaks. A 64-token sliding cache (lit) that drops token 0 (dashed) takes SmolLM2's loss on 1,024-token stories from 1.62 to 3.36; keeping token 0 as well gives 1.81.
  4. A learned sink logit sends weight nowhere. The tiny GPT trained with a sink logit per head (the topic's 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.
  5. Remove the sink, renormalise. The same scores forced to sum to 1 over real tokens: weight the head wanted to discard lands on tokens it did not choose, and held-out loss rises from 2.074 to 2.175 (192 windows).
  6. Or close a gate. With a sigmoid gate on each head's output a head with nothing to say closes it instead of finding a sink: in the gated-attention paper's 15B MoE, attention on the first token falls from 46.7% to 4.8% (authors' runs).

Three fixes that remove the need for a real token.

  • A learned sink logit per head: an extra score column with no value, so a head can send weight "nowhere" and the real weights sum to less than 1. gpt-oss: "each attention head has a learned bias in the denominator of the softmax ... which enables the attention mechanism to pay no attention to any tokens" (model card, arXiv 2508.10925); DeepSeek-V4 uses one too. StreamingLLM's pretraining test (Table 10, 160M models, PG19): with one learned sink token the model reaches 18.01 perplexity with a 1 + 1,023 cache, against 18.49 for the vanilla model keeping one real token and 27.87 keeping none.
  • An output gate: multiply each head's attention output by a sigmoid of the token's own input, elementwise, before the output projection; a head with nothing to say closes its gate instead of finding a sink. Qiu et al. (Qwen team, arXiv 2505.06708, authors' runs) found this position and form best: on a 15B MoE, perplexity 6.026 to 5.761 and MMLU 58.79 to 60.82; attention on the first token 46.7% to 4.8%; the largest hidden activation 1,053 to 94; mean gate 0.116 (mostly closed); and a 48-layer model that diverged at a learning rate of 8e-3 trained with it. Qwen3-Next and Qwen3.5 ship it (attn_output_gate: true); Kimi K3 gates its MLA layers.
  • Softmax with an extra 1 in the denominator: Evan Miller's "Attention Is Off By One" (2023-07-24), exp(xi) / (1 + Σj exp(xj)), is a sink logit fixed at 0; a learned logit generalises it.

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

The published details: StreamingLLM on ARC, the gated-attention study's setup (authors' runs)

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: a sink and gate ablation on the tiny GPT (three trained models, served with windows)

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

7. Decode cost per layer: bytes read and FLOPs per byte

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?

What it shows

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.

What one decoded token reads in one layer, by design, as the context grows

How the rows are computed (provenance)

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.

8. Depth: reference material, closed

Optional. None of this is needed to follow sections 1 to 7; each block is self-contained.

Differential attention: subtract the noise (a variant that has not spread)

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:

DiffAttn(X) = ( softmax(Q1K1T/√d) − λ · softmax(Q2K2T/√d) ) V
λ
learned per layer: exp(λq1 · λk1) − exp(λq2 · λk2) + λinit, with λinit = 0.8 − 0.6 exp(−0.3 (l − 1))
after
a per-head RMSNorm ("GroupNorm applies normalization to each head independently") times (1 − λinit)

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

What production models chose, 2023 to 2026 (per-model config table)

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 dimWindowsOther
Mistral 7B v0.1 (2023-09)32 : 8, 1284,096 in every layerlater 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, 128noneGQA-8 at every size
Gemma 2 9B (2024-06)16 : 8, 2564,096, alternating 1 : 1attention logits soft-capped at 50 (attn_logit_softcapping)
DeepSeek-V3 (2024-12)128 heads, MLA latent 512 + RoPE 64noneKimi K2 copies it with 64 heads
Gemma 3 27B (2025-03)32 : 16, 1281,024, 5 local : 1 globalQK-norm; RoPE base 10K local, 1M global
gpt-oss-120b (2025-08)64 : 8, 64128, alternating 1 : 1a learned sink logit per head
Qwen3-Next-80B-A3B (2025-09)16 : 2, 256 (1 layer in 4)none3 Gated DeltaNet layers per attention layer; output gate on attention
DeepSeek-V3.2 (2025-12)MLA as V3noneDSA, top 2,048
GLM-5 (2026-02)64 heads, MLA latent 512 + RoPE 64noneDSA, top 2,048
Gemma 4 31B (2026-04)32 : 16, 256 local; 512 on global layers1,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 entries128 uncompressedCSA and HCA, sink logits
Qwen3.5-397B-A17B (2026-02)32 : 2, 256 (1 layer in 4)noneattn_output_gate: true, 45 linear + 15 full layers
Mistral Large 4 (2026-10)64 heads, MLA latent 512 + RoPE 64none statedDSA, 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).

The code, at pinned versions (transformers v5.20.1 and the tiny GPT)

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.

Common mistakes, with the real numbers
Converting MHA to GQA by averaging heads, and shipping it
No error, and the model is broken: averaging the tiny MHA's 8 KV heads into 2 took held-out loss from 2.137 to 4.276 (section 2). Averaging is a starting point for uptraining (the GQA paper's 5%), not a conversion. measured
Folding WUK into the query when RoPE rotates the whole key
The algebra looks the same and nothing errors, but the score depends on the distance through the rotation: on the trained at_mla, folding with one matrix moves attention weights by up to 0.40 (section 3). MLA works only because its content path carries no position; the position goes through the separate RoPE key. measured
Mapping query heads to KV heads with repeat instead of repeat_interleave
GQA's query head h reads KV head h // (H / Hkv): heads 0 to 3 share KV head 0. Expanding the KV heads with repeat (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)". measured
Reading a field name as a cache design (Motif 3)
Motif 3 has kv_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.
"MLA is a kind of GQA"
GQA shares identical keys and values between heads. MLA shares a latent from which every head reads its own keys and values through its own projections; only in decode, after absorption, does it take the multi-query shape, and then over a 576-number entry with per-head projections either side.
"HCA is sparse attention"
HCA attends densely to all of its compressed entries; CSA is the one that also selects.
Reading num_key_value_heads to size an MLA cache
DeepSeek-V3's config says num_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).
Expecting DSA to save memory
It adds memory: every token keeps its MLA entry and a 128-number indexer key (V3.2: 83.9 KiB per token against V3's 68.6, bf16). It saves reads and arithmetic past 2,048 tokens, and its indexer still reads a key for every token (section 5). calculation
Serving a full-attention model with a plain sliding cache
Evicting the first token removes the sink the model relies on: SmolLM2-135M with a 64-token window, loss 3.36 against 1.62 with the full cache, and 1.81 if position 0 is kept (the root's Inside lab; section 6). The tiny GPT has no sink, so it barely notices (the root's Attention lab); a real pretrained model does. measured
Off-by-one windows and which layers are global
In transformers 5.20.1 a window W keeps keys with 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.
The DSA indexer's RoPE layout
DeepSeek's V3.2-Exp model card added a note on 2025-11-17: the indexer's RoPE needs the non-interleaved layout while MLA's RoPE is interleaved, and the earlier demo code had them wrong (the root's Attention lab notes). Two RoPE conventions in one layer is a real trap when porting; the Positional Encodings child measured interleaved instead of split-half RoPE on the tiny GPT: held-out 1.961 to 3.606, no error.
Using SDPA and asking for attention weights to look for sinks
transformers 5.20.1 warns that 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.
Design questions, with the arithmetic (commit to an answer, then reveal)

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