Long context: KV cache growth and compression, local and global attention, effective context

What every token of context costs in memory and compute, how to size the KV cache of any model, the levers that shrink it (smaller entries, fewer entries, local layers) and what each costs in quality, and why the context a model accepts is not the context it uses. Reading: 28 min, plus 13 in closed details. Data as of October 2026.
The idea in one sentenceEvery token a transformer has read leaves a key and a value in every attention layer, so the KV cache grows in a straight line with the context at a rate the architecture fixes; long context is the craft of lowering that rate (or the number of tokens kept), and then proving the model still uses what it kept.

Fig. 1: One 128K-token request to Llama 3.1 8B holds as much memory as the whole model. The cache of one sequence as a block that grows along the context axis (left to right, 0 to 131,072 tokens), its cross-section the entry one token leaves in all 32 layers; the weights are drawn behind it at the same cross-section, and the glass column on the right is one 80 GB GPU, to scale. derived from config.json with the KV-cache calculator's engine, which does this for 48 models.

  1. One token, one slice. Llama 3.1 8B has 32 layers, each with 8 KV heads of 128 numbers (its 32 query heads share them). One token therefore stores 2 (K and V) × 32 × 8 × 128 = 65,536 numbers, 2 × 32 × 8 × 128 × 2 = 131,072 bytes in bf16: 128 KiB per token. How that entry is laid out by layer and head, and why decode reads all of it, is Fig. 2 of Attention variants.
  2. A straight line in the context. Every new token appends the same slice and nothing already cached changes, so the block grows linearly: 1 GiB at 8,192 tokens, 4 GiB (4.29 GB) at 32,768. The GPU column fills from the bottom: weights first, then the cache.
  3. At 131,072 tokens, as big as the model. At its advertised 131,072 tokens one sequence holds 16 GiB (17.18 GB), as much as its 16.06 GB of bf16 weights: drawn at the cache's cross-section, the weights are the length of 122,532 tokens, and the cache passes them. Llama 3.1 70B (80 layers, same heads) needs 320 KiB per token, 40 GiB per 128K sequence.
  4. Three requests fill the GPU. With 92% of 80 GB usable (vLLM's default), one 80 GB GPU holds three such sequences after the weights, thirteen at 32K; a fourth 128K request does not fit (dashed).
  5. MHA would fill it alone. The same model with one KV head per query head (MHA, as Llama 2 was built) stores 4 times the slice, 512 KiB per token, grows four times as fast and runs out of the GPU at 109,748 tokens, before 110K: one request, nothing else.

You need: attention and why a KV cache exists (The transformer from zero section 3 for attention, section 9 for the recompute-against-keep stepper; Attention variants for how GQA, MQA, MLA and sparse attention work, and for their cache entries drawn per token). The calculator tab is a tool, not a read.

KV cache: the keys and values of every earlier token, per layer, kept so decoding does not recompute them.
Prefill / decode: reading the prompt in one pass / generating one token at a time against the cache.
Local (sliding-window) layer: attends to the last W tokens only, so its cache stops at W entries; a global layer keeps all.
Eviction: dropping cached entries by a score; attention sink: the first tokens, which soak up attention and must be kept.
Position wall: the loss rising past the trained length, where RoPE angles were never seen.
Effective context: the longest input at which the model still does a given task well; measured, never read from a config.

Every lever on a long context: what it shrinks and what it costs

LeverShrinksQuality cost (evidence on this page)Needs training?Section
Fewer KV heads (GQA, MQA)cache, decode readssmall when trained (GQA paper)yes (or uptraining)3
Latent cache (MLA)cache, decode readsnone: DeepSeek-V2's ablation has MLA above MHA (its Table 9)yes3
Quantised cache (fp8, int4)cache, decode readsint8 none, int4 small, int2 large (measured)no3
Eviction (StreamingLLM, H2O, SnapKV)cache (not the prefill peak)invisible in perplexity, large on retrieval and copying unless the question is known (measured)no4
Local and global layerscache and prefill FLOPssmall when trained (Gemma reports); large when imposed on a trained model (measured)yes5
FlashAttention, chunked prefill, context parallelismprefill memory, stalls, memory per GPUnone (exact)no6
RoPE scaling plus training at lengththe position wallscaling alone helps partly and costs short-range quality (measured)yes, for good results7
Recurrent or sparse mixerscache to a constant, prefill FLOPsweaker exact recall (owned by Beyond attention)yes5

1. What one token costs

Fig. 1 walks one model through the arithmetic; the rule for any model sums the entry each layer keeps per token (its size by design is drawn per token in Fig. 1 of Attention variants: MHA, GQA-8 and MQA at Llama 3.1 8B's shape, MLA's 512-number latent plus 64-number RoPE key at DeepSeek-V3's, DSA's added 128-number indexer key; a sliding-window layer stores the same entry as its full twin but only for the last W tokens; a recurrent layer stores nothing per token and keeps a fixed state instead):

cache of one sequence = Σlayers entryℓ × bytes × min(T, Wℓ)  +  Σrecurrent layers stateℓ
entry
2 × KV heads × head dim for MHA, GQA and MQA (count num_key_value_heads, never num_attention_heads); kv_lora_rank + qk_rope_head_dim for MLA (576 in DeepSeek-V3, Kimi K2, Mistral Large 3; 320 in Mistral Small 4), plus the indexer key for DSA
bytes
2 in bf16, 1 in fp8, about 0.56 in int4 with per-group scales
W
the window of a local layer (no cap for a global one); T is the context
passes
a looped model runs its stack several times per token, and each pass sees different hidden states, so "layers" means layers × passes: Nanbeige4.2-3B's 22 blocks run twice keep 176 KiB per token, twice the 88 KiB of one pass (22.0 GiB at 128K), the same as an unlooped 44-block model; looping saves weights, not cache, and sharing one cache across passes halved it but cost Nanbeige quality (GPT-6 Astra and looped transformers)
state
a recurrent layer's fixed memory, the same at 1K and 1M tokens (Qwen3-Next's 36 DeltaNet layers hold 36 × 32 × 128 × 128 numbers: 36 MiB at 16 bits, 72 MiB in FP32, 75 MiB with the small convolution state the root counts)

Across real models the per-token rate spans two orders of magnitude, and the design, not the parameter count, sets it. One sequence at 131,072 tokens, bf16, windows credited derived:

ModelDesignPer tokenAt 131,072
Llama 2 7BMHA, 32 KV heads512 KiB64 GiB
Llama 3.1 8B / 70BGQA, 8 KV heads128 / 320 KiB16 / 40 GiB
Gemma 3 27B5 local (W 1,024) : 1 global496 KiB if all global10.41 GiB (62.00 if all global)
gpt-oss-120b1 local (W 128) : 1 global72 KiB4.50 GiB (9.00)
DeepSeek-V3, Kimi K2MLA, 61 layers68.6 KiB8.58 GiB
DeepSeek-V3.2MLA + DSA indexer keys83.9 KiB10.48 GiB
Qwen3-Next-80B-A3B12 attention of 48 layers24 KiB3.07 GiB incl. state
DeepSeek-V4-Procompressed sparse attention, FP8/FP44,939.5 bytes0.61 GiB

All 48 presets, with sources and twelve published figures recomputed, are in the KV-cache calculator. A mixture-of-experts model moves the weight bar, not the cache: Qwen3-235B-A22B (94 layers, 4 KV heads) keeps 188 KiB per token, 47 GiB at 262,144 tokens, less than the dense Qwen3-32B's 64 GiB.

The mistake worth one line: sizing with query heads

With num_attention_heads Llama 3.1 70B comes out at 2,560 KiB per token instead of 320 KiB, eight times too much (1 sequence at 128K on eight 80 GB GPUs instead of 10). For MLA, the same slip gives 3.81 MiB per token for DeepSeek-V3 instead of 68.6 KiB.

How to check. Read num_hidden_layers, num_key_value_heads, head_dim from config.json, then the fields that change the sum: sliding_window with layer_types or sliding_window_pattern, MLA's kv_lora_rank, an indexer's head dim, linear-attention layers. vLLM prints the cache it allocated at start-up, and its metric vllm:kv_cache_usage_perc shows how full it is (Batching, KV cache and scheduling).

Why two pages can give two cache sizes for the same model (accounting conventions)
  • Windows credited or not. The "card" convention (Raschka's gallery: "the logical cache added by one token for one sequence") counts every layer at full cost, so Gemma 3 27B is 496 KiB per token; what one 128K request actually holds, windows credited, is 10.41 GiB, not 62 GiB.
  • DSA indexer keys counted or not. DeepSeek-V3.2 is 68.6 KiB per token for its MLA latents alone and 83.9 KiB with its 128-number indexer keys in bf16; in its released FP8 decode layout the DeepSeek page reports 48,068 bytes per token (FlashMLA). GLM-5 likewise: 87.75 KiB of latents, 107.3 KiB with indexer keys.
  • Published mixed layouts. DeepSeek-V4 stores FP8 entries with bf16 RoPE dimensions and an FP4 indexer: 4,939.5 bytes per token for V4-Pro on the DeepSeek page, against about 9.7 KiB if everything were bf16 (the attention-variants convention).
  • Recurrent state dtype. FP32 here and in the root calculator (Qwen3.5 and 3.8 configs say mamba_ssm_dtype: float32); 16-bit on the Qwen, GLM and Memory technology pages, which halves every state figure. How serving engines store it varies.
  • "1M". 1,048,576 tokens here and on Attention variants; 1,000,000 on the DeepSeek page. Ratios do not change; absolute figures differ by 4.9%.
  • Units. KiB and GiB are powers of 2; GB is 109 bytes: 16 GiB is 17.18 GB.
Family by family: the sizing facts gathered from the provider and neighbour pages
  • Llama and MHA. Llama 2 7B (32 KV heads) needs 512 KiB per token: 4.29 GB at 8K, 17.18 GB at 32K, more than its 13.48 GB of fp16 weights. A Llama 3.1 8B conversation of 32,768 tokens holds 4.29 GB, a quarter of the weights, so 4 such conversations hold more than the weights. Llama 3.1 70B at 32,768 tokens: 10.74 GB per sequence; on eight 80 GB H100s at 92% that leaves room for 41 of them.
  • Mistral. Mistral 7B: 2 × 32 × 8 × 128 × 2 = 131,072 bytes, 128 KiB per token; 32,768 tokens would need 4 GiB, the 4,096-token rolling buffer (slot i mod W) keeps it at 512 MiB; full MHA would need 16 GiB, more than the model's own weights (about 14.5 GB at 16 bits). Mixtral 8x7B has the same 128 KiB per token without the window; Mixtral 8x22B 224 KiB; Ministral 3 3B, 8B and 14B 104, 136 and 160 KiB; Mistral Medium 3.5 and Devstral 2 352 KiB over 88 layers; the latent models Mistral Small 4 (256 + 64) and Mistral Large 3 (512 + 64) 22.5 KiB and 68.6 KiB. One sequence at 256K: 5.6 GiB on Small 4, 17.2 GiB on Large 3 and 88 GiB on Medium 3.5 (Mistral AI page).
  • Qwen. Only full-attention layers grow. Qwen3-235B-A22B: 94 × 2 × 4 × 128 × 2 = 192,512 bytes, 188 KiB per token, 47 GiB at 262,144 tokens; Qwen3-32B 64 GiB. Hybrids stay under 25 GiB including their DeltaNet states: Qwen3-Next 24 KiB per token, about 6 GiB at 262,144; Qwen3.5-397B-A17B 30 KiB; Qwen3.8-27B 64 KiB; Qwen3.8-2.4T-A95B 92 KiB, 23.3 GiB, half of Qwen3-235B's cache. A DeltaNet state beats the cache it replaces after 512 tokens in Qwen3-Next and 768 in Qwen3.8-Flash-Next (786,432 / 1,024 numbers); Flash-Next's QSA indexer keys are not counted (Qwen page; QSA cuts reads and arithmetic, not storage).
  • GLM. GLM-4.5: 92 × 4,096 = 376,832 bytes, 368 KiB per token, 46 GiB at 128K. GLM-5 and 5.1: 78 × (576 + 128) numbers, 107.3 KiB; GLM-5.2 and 5.3 share indexer keys (21 of 78 layers): 47,616 numbers, 93 KiB, 93 GiB at 1M, and the vendor says IndexShare "does not proportionally reduce per-token KV-cache size". GLM-5.3-Flash: 11 sparse layers × (512 + 128/4) = 5,984 numbers, about 11.7 KiB per token plus 68 MiB of KDA state at 16 bits; 8.0 times less than GLM-5.3 per token, 4.59 times per layer against the published 4.44 (layer mix 4.09 × rotary key 1.125 × IndexPool 1.18; 3.9 without pooling). DSA saves reading, not storing.
  • DeepSeek. DeepSeek LLM 67B: 389,120 bytes per token (95 layers, 8 KV heads). V2: 69,120; V3 and V3.2's latents: 70,272; V4-Pro 4,939.5 (an FP4 indexer assumed; FP8 indexer keys give 2.17% of GQA-8 and none 1.78%); V4-Flash 3,514 reported; V4.1-Flash 890 reported, 528 bytes per entry in FP8 or 288 in FP4. At 1M tokens: MHA at V3's shape about 3.6 TiB per sequence, GQA-8 233 GiB, MLA 65 GiB, V4-Pro 4.6 GiB, V4.1-Flash under 1 GiB (DeepSeek page, 1M = 1,000,000).
  • Vision-language decoders. Image tokens cost cache like text tokens: SmolVLM-500M keeps 2 × 32 × 5 × 64 × 2 = 40,960 bytes per token (the measured slope is exactly the config arithmetic); LLaVA-1.5-7B 524,288, so one 576-token image holds 302 MB; Qwen3.5-0.8B 12,288 bytes from its 6 attention layers of 24 plus a fixed 19,759,104-byte FP32 state, worth about 1,608 tokens. How many tokens an image becomes is on Vision-language models.
  • Not yet presets (the root calculator refuses their configs): Gemma 4 31B, 840 KiB per token by the card convention but about 5.8 GiB per 128K request with windows credited (against 105 GiB); Kimi Linear 8,064 bytes per token; Nemotron 3 Super 8 KiB per token, 1.16 GiB at 131K; OLMo 3 32B 256 KiB per token, 70 KiB credited (root Architecture map and gallery).

2. Slow, not only big: decode reads it, prefill squares it

Decode is bandwidth, prefill is compute. Every generated token reads the whole cache once: each cached number feeds two multiply-adds (one score, one weighted sum), far too little arithmetic per byte to keep a GPU busy, so decode speed is set by memory bandwidth (about 1 FLOP per byte for MHA in bf16 against an H100's balance of about 295; Performance math has the roofline). Cache bytes are decode time. Reading a prompt is the other wall: every token's attention over all earlier ones, so a prompt's attention FLOPs grow with the square of its length while its weight FLOPs grow linearly. Memory and compute are different walls, moved by different levers.

Fig. 2: rows are queries, columns are keys, so one cell is one query-key pair of one head in one layer; 12 tokens are drawn (illustrative), and the shares quoted are Llama 3.1 8B's at real lengths derived with the root's calc.py.

  1. Prefill: a triangle of pairs. Reading a prompt, each token's query meets the key of itself and every earlier token: the causal triangle holds T(T+1)/2 pairs, about 8.6 billion per head per layer at 131,072 tokens. All rows are computed in one parallel pass, so prefill is limited by arithmetic, not memory.
  2. A line against a square. Each token also passes once through the weights (the bar beside its row, the same for every token). Weight FLOPs grow with T, attention FLOPs with T²: attention is 7% of a 4,096-token prefill of Llama 3.1 8B and 70% of a 131,072-token one.
  3. Decode: one new row, the whole cache read. A generated token adds one row: its query reads every cached key and value once (the stream from every column) and the weights once more (the plate). At 128K tokens Llama 3.1 8B reads 16 GiB of cache per sequence per step on top of its 16 GB of weights.
  4. Each row is one longer. The context grows by one with every decoded token, so every step reads one more entry while the weight read stays flat: attention's share of decode FLOPs passes half at about 28,600 tokens and is 82% at 131,072.
  5. Batching shares the weights, never the cache. Four sequences decode together: one read of the weights serves all four, but each reads its own cache, so at long context the cache read sets the step time and batching stops helping.

The two walls cross at different lengths: the chart beside gives attention's share of the FLOPs per token for both phases. In decode the cache read already costs more bytes than the weights before 128K; in prefill the square wins later, because the average prompt token reads only about half the prompt.

Predict. Llama 3.1 70B goes from 8 KV heads to MQA (one KV head). At 128K tokens on eight 80 GB GPUs, how many more sequences fit, and how much faster does a 128K prefill get?
The cache shrinks by the KV heads removed (8 to 1), so about eight times the sequences fit once the weights are paid (10 at 128K as configured). Prefill FLOPs barely move: attention FLOPs are set by the 64 query heads and the positions each reads, not by how many distinct keys are stored. Fewer KV heads, fewer bits and eviction cut memory and decode reads; only windows, sparsity or a different mixer cut prefill compute.

Attention overtakes the weights at about 28,600 tokens in decode, and takes 70% of a 128K prefill

Llama 3.1 8B: share of FLOPs per token spent in attention, against context. Decode: one new token over a cache of T. Prefill: the average token of a T-token prompt, which reads about half the prompt, so prefill crosses later. Weight FLOPs are flat; attention FLOPs grow with every position read. derived with the root's calc.py.

3. Smaller entries: fewer KV heads, a latent, fewer bits

Three levers shrink each token's entry and keep every token.

Fewer KV heads (GQA, MQA): query heads share keys and values. Llama 3.1's 8 KV heads for 32 (8B) or 64 (70B) query heads already cut the cache 4 or 8 times against MHA; MQA goes to one. Small quality cost when done in training or uptraining (GQA paper).

A compressed latent (MLA): DeepSeek-V3 caches 576 numbers per layer whatever its 128 heads, 68.6 KiB per token over 61 layers in bf16, against 3.81 MiB for MHA at the same shape: about 57 times fewer, the size of GQA with only 2.25 groups. Both mechanisms are drawn in 3D on Attention variants (Figs. 3 and 4; the MLA before and after was first built for the DeepSeek page): it animates the mechanism, this page sizes it.

Fewer bits per number (KV quantisation): keys and values in 8, 4 or 2 bits with a scale per group of numbers. It needs no retraining, which is why engines ship it (FP8 in vLLM and SGLang; q8_0 and q4_0 in llama.cpp, measured on Qwen3-1.7B on Batching, KV cache and scheduling section 8). It halves (fp8) or quarters (4-bit) memory and decode reads at once, and composes with every other lever.

The chart beside is KIVI's finding: "the key cache should be quantized per-channel" and "the value cache should be quantized per-token" (Liu et al. 2024). Measured here on SmolLM2-135M (section 4's pass-key test): 8 bits are free (97% against 97% full), 4 bits nearly free (KIVI layout 93%), and 2 bits need keys per channel (50% against 7% per token) and still lose half. measured Check retrieval at your length, not perplexity, and the key statistics beside on your model.

All the quantisation numbers, KIVI's claims, and the MLA headline reconciled

KIVI makes 2-bit caches workable (Liu et al. 2024; the authors report "2.6× less peak memory (including model weight)", up to 4 times larger batches and 2.35 to 3.47 times the throughput; authors' claims, not run here). Measured here on SmolLM2-135M at 4,096 tokens, 30 pass-key prompts (section 4 has the test): full cache 97%; int8 per token 97%, int4 87% (KIVI layout 93%), int2 7% per token against 50% with keys per channel (and the new-story loss rises to 2.45 per token against 2.22). 8 bits are free, 4 bits nearly free, 2 bits need the per-channel layout and still lose half. measured How to check: retrieval at your length, not perplexity, plus the key statistics above on your model.

MLA at DeepSeek-V3's shape against 8-group GQA: 244 KiB per token. Per sequence at 131,072 tokens: 8.58 GiB, where MHA would need 488 GiB. DeepSeek-V2's headline, that MLA "reduces the KV cache by 93.3%" against its 67B dense predecessor (vendor), reproduces only with V2's cache quantised to about 6 bits: in bf16 the arithmetic gives 82.2% (69,120 against 389,120 bytes per token).

Keys have outlier channels, values do not: why 2-bit keys must be grouped per channel

SmolLM2-135M, all 90 caches (30 layers x 3 KV heads), one 4,096-token prompt: the largest channel's mean magnitude over the median channel's. Keys: median 9.4 times; values 2.7 times. A per-token group of keys spends its range on the few large channels and rounds the rest to almost nothing. measured on Apple M1 Pro (CPU) (src/kv/key_channels.py)

4. Fewer entries: eviction

Most cached tokens get little attention most of the time; eviction scores each entry and keeps the best within a budget. StreamingLLM keeps the first few tokens (the attention sinks) plus a recent window: fluent forever, but nothing that left the window is remembered (Xiao et al. 2023). H2O keeps the "heavy hitters", tokens that "contribute most of the value when computing attention scores", plus recent ones (Zhang et al. 2023). SnapKV keeps what the last prompt tokens, usually the question, attend to (Li et al. 2024).

The test here: SmolLM2-135M, one 4,096-token prompt of TinyStories with a planted sentence ("The secret number is 66226. Remember it.") and a question at the end; prefill with the full cache, compress, then score the continuation against what survived (prefill-then-compress, SnapKV's setting). Each policy keeps the same share in every one of the 90 caches. measured on Apple M1 Pro (CPU), fp32, 4 threads, deterministic.

Fig. 3: Before and after: what each policy keeps of the same prompt. Rows are the 30 layers (layer 0 at the back), each the average of its 3 KV heads; columns are 128 tokens each, oldest left. A column's height is the share of its entries kept, and evicted entries lift out as the step changes. The planted number is the orange plate (needle at 50% depth, seed 0); the question sits at the right end, and dots stream from the number to the answer only from the caches that kept it whole. Step 1 is the full cache; each later step applies one policy to the same prefilled cache, at the budget chosen here:

  1. Full cache. Every key and value of all 4,096 prompt tokens in all 90 caches: 4,096 × 23,040 bytes = 90 MiB in bf16 for this small model. The model answers 66226.
  2. Recent only. A window applied after training: everything older than the window is gone, including the first tokens where SmolLM2 parks its attention (its attention sink switches on at layer 12, Inside a real model on the root).
  3. Sink + recent (StreamingLLM). The first 4 tokens stay as sinks, so the model stays fluent, but the window still forgets the needle unless it is recent.
  4. Random, the control. A random choice per head, keeping the sinks and the question. A five-token number survives intact in almost no head.
  5. H2O. Accumulated attention favours tokens many queries looked at: early tokens, sinks, punctuation. A number read once in passing is not a heavy hitter.
  6. SnapKV. Scored by the question itself (it sits in the 32-token observation window), each head keeps what the question looks at: the number survives where it matters.
  7. SnapKV, before the question. The same method, but scored before the question arrived. The selection is made for the document's last sentences, and the number is dropped.
  8. Local + global, imposed. Five global layers keep everything (the full rows); the other 25 keep sinks and a short window. The model was trained with every layer global, so the five cannot carry the answer alone. It cannot reach 12.5% (its five global layers alone are a sixth of the cache), so it is shown at 25% under both budgets.

Predict. At 12.5% of the cache, which policy answers the pass-key question most often: H2O (keep what has been attended most), SnapKV (keep what the question attends to), or local + global (keep everything in 5 layers)?

What the runs show. Only a question-aware policy survives: SnapKV keeps 97% at a quarter of the cache, but 0% when it scored the cache before the question arrived. Every eviction policy loses copying already at half the cache, while int4 at 31% of the bytes keeps it. Perplexity sees none of this: H2O at 12.5% moves the new-story loss from 2.07 to 2.10 while answering 0% of pass-key questions. And keep the first tokens: a recent window without sinks sends the new-story loss to 4.02; with 4 sinks, 2.08.

Two lessons a paper's headline will not give you

An eviction method is only as good as the test: perplexity or summarisation can stay flat while retrieval of a single fact goes to zero. And question-aware methods need the question at compression time; in a multi-turn chat, an agent loop or a shared prefix cache the document is compressed before anyone asks, and the method becomes another heuristic.

Cost, and how to check. Scoring needs attention weights that fused kernels never materialise; the prefill peak is untouched; per-head selections free no paged blocks (Batching, KV cache and scheduling, section 8, measured 0% of 16-token blocks freed; a selection shared by every head, SnapKV's, left 51% of blocks freeable in place). Test retrieval and copying at the budget, with the question where your application puts it, and measure memory the engine actually frees. (The root's Inside a real model tab finds SmolLM2's sink switching on at layer 12.)

The protocol, all nine policies, every result, which heads must keep the fact, and what transfers

Every result. At a quarter of the cache SnapKV still answers 97% and at 12.5% 87%; scored before the question arrived it answers 0% at a quarter (30% at half); H2O answers 17% even at half the cache, sink plus recent 10% at 12.5%. Re-reading an earlier story, every eviction policy loses most of the benefit already at half the cache (copy loss 0.61 full, 1.42 for the best policy at 50%), while KIVI int4 at 31% of the bytes keeps it (0.66). On an unseen story, the perplexity-style test, all of them look fine: H2O at 12.5% moves the loss from 2.07 to 2.10 while answering 0% of pass-key questions. And never drop the first tokens: a plain recent window at half the cache sends the new-story loss to 4.02; keeping 4 sink tokens brings it back to 2.08.

What transfers from a 135M model at 4,096 tokens: the ranking of policies per task, the perplexity gap, the role of the question and of sinks, the per-channel effect at 2 bits. What does not: absolute percentages (a 70B model at 128K has a larger, more redundant cache); 30 prompts resolve about 3 points. H2O's authors report up to 29 times the throughput of DeepSpeed Zero-Inference and Hugging Face Accelerate with 20% heavy hitters (authors' claims, not run here).

Three tasks. Pass-key (30 prompts: needle depths 10%, 30%, 50%, 70%, 90%, 6 seeds; correct means all five digits right under greedy decoding). Copy (6 prompts: one story planted at a depth, then repeated after the prompt; the loss on its first 128 tokens is low only if the earlier copy can still be read by the induction heads). New story (6 prompts: an unseen continuation, what perplexity evaluations measure). Prompts: TinyStories validation (CDLA-Sharing-1.0) concatenated to 4,096 SmolLM2 tokens, half its 8,192 maximum.

PolicyKeepsSource
recentthe most recent tokens only: a sliding window applied to a model trained without onebaseline
sink + recentthe first 4 tokens plus the most recentStreamingLLM
randoma random subset per head, plus the first 4 tokens and the question: the cheap controlcontrol
H2Ohalf the budget for the most accumulated attention, half for the most recentH2O
SnapKVper head, the tokens most attended by the last 32 prompt tokens (the question is inside), pooled over 7 positionsSnapKV
SnapKV, before the questionthe same, scored from the 32 tokens before the question: compressed when the document arrived (a second turn, a cached system prompt)this page
local + globalevery sixth layer keeps everything; the other 25 keep the first 4 tokens and a window sized to the budget (Gemma 3's 5:1 layout imposed after training)this page
int8, int4, int2every entry, rounded in groups of 32 numbers per token with an fp16 scale and zero per groupper-token quantisation
KIVI int4, int2the same, but keys grouped per channel over 32 tokens (values per token)KIVI

Which heads keep the fact. For each pass-key prompt, the caches (of 90) that kept all five digit tokens, against whether the answer was right; averages over the 30 prompts.

The code that ran (src/kv/smol.py, lines 102 to 104): SmolLM2's attention written out by hand so eviction is a mask over cached entries per layer and KV head (masking an entry is exactly removing it); continuation tokens attend to the surviving prompt entries and causally to each other.

kp = keep[li].repeat_interleave(g, 0)                       # (nh, T)
mask = torch.cat([kp[:, None, :].expand(nh, n, T), causal[None].expand(nh, n, n)], -1)
o = F.scaled_dot_product_attention(q[None], Kall[None], Vall[None], attn_mask=mask[None])[0]

Check against transformers 5.20.1's own forward on 1,024 tokens (prefill 900, continue 124, full cache): largest logit difference 1.9e-04 on logits up to 41.9 (src/kv/out/check.json). Run: python run_kv.py evict, about 10 minutes on 4 CPU threads. Batching, KV cache and scheduling ran H2O, SnapKV and random eviction on Qwen3-0.6B at about 1,000 tokens with the realisable-saving test; this run goes four times longer, adds architecture-style policies, quantisation on the same axis and the question-timing test.

Fewer bits beat fewer entries at equal memory; perplexity hides the difference

5. Local and global layers: a smaller cache designed in, not cut out

Eviction decides after training which entries to drop, and the model was never trained to cope. A local layer makes the decision part of the architecture: in training and inference each query sees only the last W tokens, so the layer's cache never holds more than W entries. Interleaving local layers with a few global ones keeps a direct path to any old token while most layers stay cheap (the ring-buffer mechanism and the reach of stacked windows: section 4 and Fig. 5 of Attention variants). Predict before you drag the slider beside: at 131,072 tokens, what share of Gemma 3 27B's cache sits in its 52 local layers?.

Model (config read 2026-10-18)LayoutWindowCache at 128K, bf16 derivedIf every layer were global
Mistral 7B v0.1every layer local4,0960.50 GiB16.00 GiB
Gemma 2 9B1 local : 1 global4,096 (global span 8,192)trained and served at 8,192 tokens: "a context length of 8192 tokens" (Gemma 2 report, section 2, vendor)
Gemma 3 27B5 local : 1 global1,02410.41 GiB62.00 GiB
gpt-oss-120b1 local : 1 global1284.50 GiB9.00 GiB

Mistral's paper says the window "reduces the cache memory usage by 8x" at its 32,768-token sequences (32,768 / 4,096, reproduced independently), and stacking 32 windowed layers reaches 32 × 4,096 = 131,072 tokens in theory. Gemma 3 keeps RoPE base 10,000 on local layers and 1,000,000 on global ones (rope_local_base_freq, rope_theta), because only global layers see long distances. On one 80 GB GPU in bf16, Gemma 3 27B as released fits one 128K request (11.17 GB of cache after 54 GB of weights) and, with every layer global, none (66.57 GB for one): the local layers are what make 128K servable at all on one GPU.

Published quality cost: small, when trained in. Google reports for Gemma 3 that changing the local:global ratio has "minimal impact on perplexity", "even with 7-to-1 local to global" (vendor). Two cautions: that is perplexity, which section 4 measured to be the wrong test, and on models trained with their layout.

Measured here: imposing a layout does not work. SmolLM2-135M was trained with full attention in all 30 layers. Making 25 of them local after training (sinks plus a window, every sixth layer global, at the same memory as the other policies; the local_global policy of section 4): result pending. The model never learned to route old information through its global layers; converting a trained model needs continued training with the layout in place.

Other ways to cut the per-token rate, each a training-time design: share keys and values across adjacent layers; replace most layers with a fixed recurrent state (hybrids); or compress and sparsify what is stored and read (DSA saves reading, not storing; DeepSeek-V4 stores about 2% of a GQA-8 cache at 1M tokens). The KV-cache calculator sizes each.

The published evidence in full, and the other per-token levers

Gemma 3 report: the ratio changes have "minimal impact on perplexity", "even with 7-to-1 local to global", and the window "can be reduced significantly without impacting perplexity"; on memory, "global only" gives "a memory overhead of 60%" at 32K, "reduced to less than 15%" with sliding windows of 1,024 (Gemma 3 report, sections 5.1 and 5.2, vendor; the report writes the ratio as "1:3" there and 5:1 elsewhere). Our arithmetic for 27B in bf16 gives 31% and 5.8%: the same fivefold cut, not the same numbers; we did not find which model size and precision the report's figure uses. Gemma 2's Table 10 shrinks the trained 4,096 window at inference to 2,048 and 1,024: validation perplexity 1.63, 1.63, 1.64 (vendor). Databricks' MixAttention study, testing on RULER, found long-context ability needs "at least one standard attention KV cache that is computed in the deeper layers" (Rajput et al. 2024, third-party, building on Character.AI's 2024 blog).

Cross-layer sharing attacks the layer count: adjacent layers reuse one set of keys and values; Cross-Layer Attention reports it can "reduce the size of the KV cache by another 2x" beyond MQA "while maintaining nearly the same accuracy as unmodified MQA", trained from scratch at 1B and 3B (Brandon et al. 2024, third-party). Hybrids keep a fixed recurrent state in most layers: Nemotron-H 8B keeps 4 attention layers of 52 (16 KiB per token plus about 99 MiB of state per sequence), Qwen3-Next one in four (24 KiB per token; its DeltaNet state equals the cache of 512 tokens of the layers it replaces), GLM-5.3-Flash 11 sparse layers of 45 (owned by Beyond attention). Sparse and compressed attention changes what is read or stored: DSA (DeepSeek-V3.2, GLM-5) stores every latent plus an indexer key and reads only the top 2,048, so it saves reading, not storing; MiniMax M3.1 Flash runs sparse attention in every layer, having replaced the three full-attention layers M3 kept, so in production the always-on global path can be a sparse one (model card, vendor); DeepSeek-V4 compresses entries 4 or 128 to one, about 2% of a GQA-8 cache at 1M tokens (mechanisms on Attention variants; sizes in the KV-cache calculator).

When it matters, how to check. Local layers pay off once the context is several times the window; below that they cost and save nothing. Check the layout in config.json (sliding_window with layer_types or sliding_window_pattern, attention_chunk_size), check that your engine frees windowed entries (a cache that allocates every layer at full length gives the quality cost of windows without their memory), then test the long-range path with retrieval at the target length.

Gemma 3 27B: past the window only the 10 global layers keep growing

Each row is one of the 62 layers; its length is the tokens it caches (16 KV heads of 128 per token, 8 KiB in bf16).

6. Long prompts: the compute side

A 128K-token prompt is a 128K-row attention matrix per head per layer, and it costs in four separate ways, each fixed exactly (no quality cost) by a neighbouring page's method: FlashAttention keeps the score matrix out of memory, chunked prefill stops one long prompt stalling everyone else's stream, context parallelism splits one sequence across GPUs, and only windows, trained sparse attention or recurrent layers cut the quadratic FLOPs themselves.

The four costs, their fixes and the pages that own them
CostFixWhat it changesOwned by
Memory for the T × T score matrixFlashAttention: tiles and an online softmax, never storing the matrixmemory linear in T; FLOPs still quadratic (exact)FlashAttention paper page; Writing kernels
One long prompt stalls everyone's streamChunked prefill: the prompt enters in chunks between decode stepslatency for others; the long prompt itself slightly slowerBatching, KV cache and scheduling (section 5, measured)
One sequence's activations exceed a GPU (training at length)Context parallelism: ring attention passes K and V blocks round a ring while computing (Liu et al. 2023); Llama 3 gathers K and V insteadmemory per GPU; adds communication that grows with TDistributed Training, Distributed PyTorch, Llama 3 paper page
The quadratic FLOPs themselvesWindows (section 5), trained sparse attention (NSA, DSA), linear or state-space layerseach query reads fewer positionsAttention variants; Beyond attention

This is why long-context training comes last and short: Llama 3 grew its context from 8K to 128K in six stages over about 800B tokens at the end of pretraining (the Llama 3 paper page, vendor); how such a phase is run is on Data mixing, curricula and continued-pretraining ratios, sections 5 to 7. How long it should run is predictable: an additive power law over model size and the short- and long-context token budgets, fitted on 5 scales and over 100 configurations, predicted a 1.22B model's trajectory out to about 100B long-context tokens with no saturation, and the gains survived extension to 128K and supervised fine-tuning (Don't Stop Long-Context Continual Pre-Training Too Early (arXiv 2610.29352)). To check a serving setup, time a prefill at your target length (time to first token) against section 2's crossover: below about 28,600 tokens for an 8B Llama, weights dominate and attention tricks change little.

7. Past the trained length: the position wall

A model is trained on windows of some length; nothing stops a longer prompt at inference. With RoPE (each query and key rotated by an angle proportional to its position, so their dot product depends on distance), a longer prompt produces angles, in the slowly rotating dimensions, that training never showed; with learned absolute positions there is no row in the table at all (the topic's tiny GPT raises IndexError: learned positions stop at 256; got position 299, on purpose; no scaling rule exists for a learned table: retrain or switch scheme). The schemes and extension methods (position interpolation, NTK-aware scaling, YaRN, Llama 3's rule) belong to Positional Encodings; here is what the wall costs and why training at length is still needed.

Length also dilutes attention, with or without new angles. A softmax's weight on the key it wants shrinks as more keys compete, and the fixes sharpen the logits by a factor that grows with the log of the context: YaRN's temperature, Su's log M / log L, Qwen's LogN, Scalable-Softmax, Llama 4's query scale on its NoPE layers. The log is enough because a softmax's recall capacity grows exponentially with its sharpness (derived in the transformers-from-memory article); the formulas are on Positional Encodings, section 7.

Fig. 4: The tiny GPT past its 256-token training length: scaling trades the short range, training fixes both. The Attention lab's RoPE model (at_mha: 6 layers, 8 heads, 1,500 steps on 256-token windows) reads 24 held-out windows of 2,048 TinyStories tokens; each column is the loss at its positions, averaged over 64-position bins, one row per run, the glass plate at 256 marks the trained length. Two runs continued training for 300 steps at 1,024 tokens (2.46M tokens, a fifth of the original 12.3M); at_swa64 is the window-64 model. measured on Apple M1 Pro (CPU)

  1. Plain RoPE: the wall. Plain RoPE goes from 2.07 inside the trained length to 3.82 at 1,024 to 2,047: the columns climb as soon as the model sees angles it never trained on.
  2. Position interpolation, linear x4. Squeezing every position into the trained range, linear x4 holds better far out (3.15) but costs the short range (2.74): it also blurs the short distances every token needs.
  3. NTK-aware x8. Stretching only the slow dimensions keeps short distances almost exact (2.18) and holds to 1,023 tokens (2.32) but not to 2,047 (3.25).
  4. YaRN x8. Interpolating the slow dimensions and adding an attention temperature, YaRN x8 does best of the inference-time rules: 2.43 at 1,024 to 2,047 with 2.29 in range, without any training.
  5. Training at length beats every rule. 300 steps at 1,024 tokens bring positions 512 to 1,023 to 2.03 with interpolation and 2.03 with plain RoPE, below the original in-length loss; past the new length (the second plate) the interpolated model hits a new wall (3.29, where x4 runs out) while the plain one degrades gently (2.14).
  6. A window has no wall. The window-64 model stays flat (2.1 in range, 2.09 at 1,024 to 2,047): no query ever looks further than 64 tokens, which is also why it cannot retrieve from further.
Every number of the position runs, and the code

src/past/past_len.py (CPU, about 30 s) writes the per-position losses to src/past/out/past.json; src/past/finetune_long.py (MPS, about a minute each) ran the two 300-step continuations; src/kv/run_kv.py map (CPU, about 40 minutes) the SmolLM2 grid of section 8. All three outputs are recorded for reuse by Positional Encodings.

Plain RoPE goes from 2.07 inside the trained length to 3.82 at positions 1,024 to 2,047. Linear interpolation x4 holds better at length (3.15) but costs the short range (2.74 in the first 256 positions); YaRN x8 stays at 2.43 with 2.29 in range. 300 steps at 1,024 tokens bring positions 512 to 1,023 to 2.03 with interpolation and 2.03 with plain RoPE, below the original in-length loss; past the new length the interpolated model hits a new wall (3.29, where x4 runs out) while the plain one degrades gently (2.14). At this scale the training, not the scaling rule, did the work. The window-64 model has no wall at all (2.1 in range, 2.09 at 1,024 to 2,047): no query ever looks further than 64 tokens, which is also why it cannot retrieve from further.

Why a wall. In one training window of length L, the distance d between a query and a key occurs L − d times: distance 1 at 255 query positions, distance 250 at 6. A model trained on 256-token windows has seen distances past 200 in about 5% of its query-key pairs and past 255 never. Drag to see the share of training pairs at or beyond a distance (the slider beside).

An et al. trace short effective contexts in open models to exactly this "left-skewed frequency distribution of relative positions", and find effective lengths "typically not exceeding half of their training lengths" (An et al. 2024, third-party). So production recipes pair a scaling rule with training at the new length: Gemma 3 pre-trains with 32K sequences and rescales RoPE by 8 to reach 128K (Gemma 3 report, section 5.3, vendor); Llama 3 grew from 8K to 128K over six stages (section 6). How to check: read rope_scaling and original_max_position_embeddings, then plot loss by position on long held-out documents; a curve that turns up at the trained length is the wall.

Predict. The tiny GPT reads 1,024 to 2,047 tokens with RoPE scaled 8 times at inference, no retraining. Which scaling keeps the loss closest to the in-length loss?

Why: a distance is learned only as often as it is seen

8. Effective context: accepting a token is not using it

A model can fit a 128K prompt in memory, read it without a position error, and still ignore most of it. The effective context is the longest input at which it still does a given task well: it depends on the task and the threshold and is measured, never read from the config. max_position_embeddings is an allocation, not a training fact: Qwen3 32B's config says 40,960 for a model trained to 32,768 natively, MiniMax-M1's 10,240,000 (root's Architecture map). Published measurements at scale (RULER found that of models claiming 32K or more "only half" hold up at 32K; NoLiMa removes the shared words between question and needle and finds most models effective to 2K or less; and position matters even inside the window: in Liu et al.'s lost-in-the-middle experiment accuracy traces a U, highest when the evidence comes first or last and lowest in the middle) are owned by Long-context and multimodal benchmarks.

Read it as a wall, not a slope. Inside 8,192 tokens the misses are near-misses (at 1K and 2K always the first digit, 1 for 6 or 7; at 8,192 only with the number 8K tokens back); past it every answer is broken text such as "a1...." for 66226. Short prompts are not easier for this 135M model, a reminder that 20 prompts per length is coarse.

Four causes, each with a section above: positions trained rarely (7); attention spread thinner over more keys, so one relevant token gets a smaller share (a length-dependent temperature, such as YaRN's, counters it); windows that cannot see far (5); caches compressed by policies the model never trained with (4). The shape of the heads matters too: at a fixed parameter budget, wider heads (a larger head dimension) barely changed pretraining loss or short-task scores but improved long-context retrieval, with more retrieval heads (heads that copy a token from far back) forming, and the gain held even with the attention projections frozen during long-context continued pretraining (Head Dimension Matters for Long-Context Retrieval (arXiv 2610.32213)). How to check, at the length and prompt format you ship: loss by position, a retrieval grid over length and depth, then a task string matching cannot solve (NoLiMa-style). Report the length at which your threshold still holds.

SmolLM2-135M retrieves one number up to its configured 8,192 tokens, then nothing

The pass-key prompt of section 4, full cache, seven lengths, five needle depths, four seeds per cell (140 prompts); cells give correct answers out of 4. Config: max_position_embeddings 8,192, RoPE base 100,000, no rope_scaling; the model card names the base model "SmolLM2-135M-8k" (read 2026-10-18); the SmolLM2 paper describes a 2K to 8K extension for the 1.7B model only (Allal et al. 2025, vendor). measured on Apple M1 Pro (CPU)

The same 80 GB GPU and 128K requests, one lever at a time: only a trained layout plus fp8 reaches 32

9. Designing for a context budget

The question. "Serve 128K-token requests, 32 at a time, on one 80 GB GPU." Start from Llama 3.1 8B and move one lever at a time (bf16 weights, 92% of memory usable, vLLM's default gpu_memory_utilization; derived, src/wall/out/examples.json):

  1. As released. Llama 3.1 8B: 32 layers, 8 KV heads of 128, every layer global, bf16 cache. Each 128K request needs as much memory as the whole model, and 3 fit.
  2. fp8 cache. Same model, each cached number in one byte instead of two. Free to switch on in vLLM or SGLang; 8 bits were lossless on SmolLM2 here (section 3). 6 fit.
  3. MQA instead. One KV head shared by all 32 query heads: eight times smaller entries, but the model must be retrained or uptrained. 26 fit.
  4. 5 local : 1 global. Five of every six layers keep only the last 1,024 tokens (Gemma 3's layout). Six times smaller, and prefill attention falls from 70% to 28% of the FLOPs. Trained in, not imposed: 20 fit.
  5. Layout and fp8. Both: 41 requests fit, past the 32 asked for.
The five designs as a table
DesignCache per tokenPer 128K sequenceSequences that fitAttention share of prefill
As released (8 KV heads, all global)128 KiB17.18 GB369.6%
fp8 cache64 KiB8.59 GB669.6%
MQA (1 KV head), retrained16 KiB2.15 GB2670.3%
5 local : 1 global, window 1,024, retrained20.84 KiB2.8 GB2027.9%
5 : 1 layout and fp8 cache10.42 KiB1.4 GB4127.9%

Reading it. No single lever reaches 32. fp8 is free but only doubles capacity; MQA and a local/global layout cut the cache 8 and 6 times but are training-time choices (section 5); only the windowed layout also cuts prefill compute (attention from 70% to 28% of the FLOPs). The design review answer: a model trained with a local/global layout (as Gemma 3 and gpt-oss are), an fp8 cache, chunked prefill so the 128K prompts do not stall the 31 streams already decoding, sinks never evicted, and a retrieval acceptance test at 128K, because none of these numbers says the model uses the context (section 8).

Other budgets. Many short chats favour MLA or few KV heads plus prefix caching. Long single sequences (agents, codebases) make one sequence's cache and its prefill dominate: hybrids with a constant-state mixer in most layers or trained sparse attention change the curve rather than shift it. Mixture-of-experts models move the weight bar, not the cache: DeepSeek-V3 needs 671 GB of fp8 weights on eight 141 GB GPUs but only 9.21 GB of MLA cache per 128K sequence, so 39 fit. Try any of them in the KV-cache calculator.

Depth

Design question: a coding agent that reads 1M tokens of repository per task

Concurrency is low, so one sequence's cache and the prefill dominate. At 1,048,576 tokens Llama 3.1 8B's cache alone is 128 GiB; DeepSeek-V3's MLA 68.6 GiB; Qwen3-Next's hybrid 24 GiB; DeepSeek-V4-Pro's compressed attention under 5 GiB (calculator). So: a hybrid with constant-state layers in most of the stack plus a few global attention layers (Qwen3-Next's 1 in 4, Nemotron-H's 4 of 52), or trained sparse or compressed attention; context parallelism for the prefill across GPUs; an fp8 cache for the global layers; no question-aware eviction (the question changes every turn); evaluation of retrieval and multi-hop use at 1M, and retrieval into a shorter context when the effective length falls short (Agentic retrieval, long context and memory).

Design question: eviction or quantisation at the same memory?

Quantisation first: it keeps every entry, needs no attention scores, works with fused kernels and paged blocks, and 8 or 4 bits cost little (here int4 kept retrieval and copying; eviction at 25% kept neither copying nor, unless question-aware, retrieval). SnapKV beats H2O on a planted fact (87% against 0% at 12.5%) because it scores by the question's own attention, while H2O keeps tokens many queries attended, which a fact read once is not. Evict when the context itself must be bounded (streaming), with sinks kept.

Design question: why not make a trained full-attention model local/global after the fact?

Its retrieval heads are spread over many layers; making most of them local removes the paths it learned (SmolLM2 with 25 of 30 layers made local: 37% at half the cache, 3% at a quarter, copy loss 1.56). Models with a layout are trained with it (Gemma 2 and 3, gpt-oss); conversion needs continued training.