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.
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.
| Lever | Shrinks | Quality cost (evidence on this page) | Needs training? | Section |
|---|---|---|---|---|
| Fewer KV heads (GQA, MQA) | cache, decode reads | small when trained (GQA paper) | yes (or uptraining) | 3 |
| Latent cache (MLA) | cache, decode reads | none: DeepSeek-V2's ablation has MLA above MHA (its Table 9) | yes | 3 |
| Quantised cache (fp8, int4) | cache, decode reads | int8 none, int4 small, int2 large (measured) | no | 3 |
| Eviction (StreamingLLM, H2O, SnapKV) | cache (not the prefill peak) | invisible in perplexity, large on retrieval and copying unless the question is known (measured) | no | 4 |
| Local and global layers | cache and prefill FLOPs | small when trained (Gemma reports); large when imposed on a trained model (measured) | yes | 5 |
| FlashAttention, chunked prefill, context parallelism | prefill memory, stalls, memory per GPU | none (exact) | no | 6 |
| RoPE scaling plus training at length | the position wall | scaling alone helps partly and costs short-range quality (measured) | yes, for good results | 7 |
| Recurrent or sparse mixers | cache to a constant, prefill FLOPs | weaker exact recall (owned by Beyond attention) | yes | 5 |
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):
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 DSAAcross 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:
| Model | Design | Per token | At 131,072 |
|---|---|---|---|
| Llama 2 7B | MHA, 32 KV heads | 512 KiB | 64 GiB |
| Llama 3.1 8B / 70B | GQA, 8 KV heads | 128 / 320 KiB | 16 / 40 GiB |
| Gemma 3 27B | 5 local (W 1,024) : 1 global | 496 KiB if all global | 10.41 GiB (62.00 if all global) |
| gpt-oss-120b | 1 local (W 128) : 1 global | 72 KiB | 4.50 GiB (9.00) |
| DeepSeek-V3, Kimi K2 | MLA, 61 layers | 68.6 KiB | 8.58 GiB |
| DeepSeek-V3.2 | MLA + DSA indexer keys | 83.9 KiB | 10.48 GiB |
| Qwen3-Next-80B-A3B | 12 attention of 48 layers | 24 KiB | 3.07 GiB incl. state |
| DeepSeek-V4-Pro | compressed sparse attention, FP8/FP4 | 4,939.5 bytes | 0.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.
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).
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.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.
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.
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.
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.
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).
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)
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:
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.
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.)
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.
| Policy | Keeps | Source |
|---|---|---|
| recent | the most recent tokens only: a sliding window applied to a model trained without one | baseline |
| sink + recent | the first 4 tokens plus the most recent | StreamingLLM |
| random | a random subset per head, plus the first 4 tokens and the question: the cheap control | control |
| H2O | half the budget for the most accumulated attention, half for the most recent | H2O |
| SnapKV | per head, the tokens most attended by the last 32 prompt tokens (the question is inside), pooled over 7 positions | SnapKV |
| SnapKV, before the question | the same, scored from the 32 tokens before the question: compressed when the document arrived (a second turn, a cached system prompt) | this page |
| local + global | every 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, int2 | every entry, rounded in groups of 32 numbers per token with an fp16 scale and zero per group | per-token quantisation |
| KIVI int4, int2 | the 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.
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) | Layout | Window | Cache at 128K, bf16 derived | If every layer were global |
|---|---|---|---|---|
| Mistral 7B v0.1 | every layer local | 4,096 | 0.50 GiB | 16.00 GiB |
| Gemma 2 9B | 1 local : 1 global | 4,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 27B | 5 local : 1 global | 1,024 | 10.41 GiB | 62.00 GiB |
| gpt-oss-120b | 1 local : 1 global | 128 | 4.50 GiB | 9.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.
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.
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).
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.
| Cost | Fix | What it changes | Owned by |
|---|---|---|---|
| Memory for the T × T score matrix | FlashAttention: tiles and an online softmax, never storing the matrix | memory linear in T; FLOPs still quadratic (exact) | FlashAttention paper page; Writing kernels |
| One long prompt stalls everyone's stream | Chunked prefill: the prompt enters in chunks between decode steps | latency for others; the long prompt itself slightly slower | Batching, 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 instead | memory per GPU; adds communication that grows with T | Distributed Training, Distributed PyTorch, Llama 3 paper page |
| The quadratic FLOPs themselves | Windows (section 5), trained sparse attention (NSA, DSA), linear or state-space layers | each query reads fewer positions | Attention 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.
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)
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.
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.
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 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):
| Design | Cache per token | Per 128K sequence | Sequences that fit | Attention share of prefill |
|---|---|---|---|---|
| As released (8 KV heads, all global) | 128 KiB | 17.18 GB | 3 | 69.6% |
| fp8 cache | 64 KiB | 8.59 GB | 6 | 69.6% |
| MQA (1 KV head), retrained | 16 KiB | 2.15 GB | 26 | 70.3% |
| 5 local : 1 global, window 1,024, retrained | 20.84 KiB | 2.8 GB | 20 | 27.9% |
| 5 : 1 layout and fp8 cache | 10.42 KiB | 1.4 GB | 41 | 27.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.
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).
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.
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.
How much KV cache one request needs, for 48 real models and any attention design, at any context. Pick a model, drag the context, then change the design and watch the same model's cache move against its weights and the GPU. Root-config presets equal the root's Config calculator byte for byte (its calc.py); the others are copied, with sources, from the pages that worked them out. derived Designs: as released, MHA, GQA with 8 KV heads, MQA, an MLA latent of 512 + 64 per layer, every layer windowed at 4,096, 5 local : 1 global at 1,024, or 3 linear : 1 attention. Units: KiB, MiB, GiB are powers of 2; GB is 109 bytes; 1M on the slider is 1,048,576 tokens.
What this does not model. Activations and engine workspace (they live in the 8% vLLM leaves by default), paged-block rounding and fragmentation (PagedAttention keeps waste under one block per sequence; before it, "only 20.4% to 38.2%" of KV memory held tokens, Kwon et al. 2023), tensor-parallel replication when there are fewer KV heads than GPUs, MXFP4 or other mixed weight formats (weights here are params × one dtype, all experts counted), prefix caching, and quality: every design but the dtype changes the model, and eviction is counted as if every dropped entry were freed. The decode ceiling is (weights + this sequence's cache) / bandwidth, an upper bound at batch 1.
Accelerators (memory and bandwidth as vendors state them, from Memory technology): H100 SXM 80 GB, 3.35 TB/s; H200 141 GB, 4.8 TB/s; B200 (HGX) 180 GB, 8.0 TB/s; B300 288 GB, 8.0 TB/s; MI300X 192 GB, 5.3 TB/s; MI355X 288 GB, 8.0 TB/s; TPU7x (Ironwood) 206.2 GB, 7.38 TB/s; RTX 5090 32 GB, 1.792 TB/s; Apple M1 Pro 16 GB, 0.2 TB/s. With several devices the calculator splits weights evenly and adds bandwidth, as tensor parallelism would.
Same dtype, eviction and state settings as above; designs as released. Bars are linear, so the small caches are thin on purpose. Blue is the growing cache, green the fixed recurrent state. Click a row to load it above.
| Figure | Computed here | Published | Arithmetic | Verdict |
|---|---|---|---|---|
| Llama 3.1 8B, one 131,072-token sequence, bf16 | 16.00 GiB (17.18 GB) | 16 GiB (root Attention lab; Memory technology: 17.18 GB) | 2 x 32 x 8 x 128 x 2 = 131,072 B per token | by construction |
| Llama 3.1 70B, one 131,072-token sequence, bf16 | 40.00 GiB | 40 GiB (root section 3) | 2 x 80 x 8 x 128 x 2 = 327,680 B per token | by construction |
| Mistral 7B: cache at 32,768 tokens, window against none | 8.0x smaller | "reduces the cache memory usage by 8x" (Mistral 7B paper) | 32,768 / 4,096 = 8 | independently |
| DeepSeek-V2 against DeepSeek LLM 67B, cache per token | 82.2% smaller in bf16; 93.3% with the cache at about 6 bits | "reduces the KV cache by 93.3%" (DeepSeek-V2 paper) | 69,120 against 389,120 B per token; V2 further quantised its cache to about 6 bits per element | reproduces only with the 6-bit cache |
| MLA per layer against MHA at DeepSeek-V3's shape | 56.9 times fewer numbers; 2.25 GQA groups | "about 57 times fewer", "GQA with only 2.25 groups" (V2 paper, via the DeepSeek page) | 32,768 / 576; 576 / (2 x 128) | independently |
| DeepSeek-V4-Pro against a GQA-8 cache at V3's shape, 1,000,000 tokens | 1.98% | "about 2%" (DeepSeek V4 report) | (4,939.5 x 10^6 + 4.5 MB of windows) / (249,856 x 10^6); rests on an FP4 indexer (FP8 gives 2.17%) | independently, with an assumed indexer precision |
| DeepSeek-V4-Pro and V4-Flash against V3.2's FP8 cache at 1,000,000 tokens | 10.3% and 7.3% | "10% of the KV cache" (V4-Pro) and 7% (V4-Flash) (DeepSeek V4 report) | V3.2 decodes from an FP8 cache of 48,068 B per token (FlashMLA, as the DeepSeek page reports); V4-Flash at the reported 3,514 B | consistent, approximately (our reconciliation) |
| DeepSeek LLM 67B against V4.1-Flash, cache per token | 437.2-fold | "437-fold" (V4.1-Flash model card) | 389,120 / 890 | by construction (890 is the card's own figure) |
| V4-Flash per token | 3,450 B (estimate from the config's 21 CSA and 20 HCA layers) | 3,514 B (DeepSeek's chart) | 21 x 160 + 20 x 4.5 | 1.9% below the published figure |
| GLM-5.3-Flash against GLM-5.3, average cache per layer | 4.59x (610 against 133 numbers) | "4.44 times smaller KV cache" per layer, BF16 (Z.ai docs) | (78 x 576 + 21 x 128) / 78 against 11 x (512 + 128/4) / 45; whole model 47,616 / 5,984 = 8.0x | about 3% above the published figure; no published detail explains the gap |
| Qwen3-Next: DeltaNet state against the cache it replaces | 512 tokens | 512 tokens (Qwen page) | 36 x 32 x 128 x 128 numbers / (36 x 2 x 2 x 256) per token | independently |
| Gemma 3 27B, cache over bf16 weights at 32,768 tokens | every layer global 31%; 5 local : 1 global 5.8% | "a memory overhead of 60%" falling to "less than 15%" at 32K (Gemma 3 report, section 5.2) | cache / (params x 2 bytes); the report's model size and precision for that figure are not given beside it | does not reproduce at 27B in bf16; same direction (about 5x less) |
Per token: bf16, every cache-growing layer at full cost (windows not credited; DSA indexer keys counted; DeepSeek-V4 in its published FP8/FP4 layout). At 131,072 tokens: windows credited, recurrent state included in FP32. Root-config presets equal the root's calc.py byte for byte at 4K, 32K and 128K (by construction).
| Model | Per token | One sequence at 131,072 | Fixed state (FP32) | Where the numbers come from |
|---|---|---|---|---|
| DeepSeek LLM 67B | 380.0 KiB | 47.50 GiB | DeepSeek page, Cache across generations (2 x 8 KV heads x 128 x 95 layers) source | |
| GLM-4.5 | 368.0 KiB | 46.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Llama 2 7B | 512.0 KiB | 64.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Llama 3.1 405B | 504.0 KiB | 63.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Llama 3.1 70B | 320.0 KiB | 40.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Llama 3.1 8B | 128.0 KiB | 16.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| MiniMax-M2 | 248.0 KiB | 31.00 GiB | MiniMax page and config.json (62 full-attention layers, GQA 48/8 x 128: 248 KiB per token) source | |
| Ministral 3 14B | 160.0 KiB | 20.00 GiB | Mistral AI page, Weights and cache (bytes per token only) source | |
| Ministral 3 3B | 104.0 KiB | 13.00 GiB | Mistral AI page, Weights and cache (bytes per token only) source | |
| Ministral 3 8B | 136.0 KiB | 17.00 GiB | Mistral AI page, Weights and cache (bytes per token only) source | |
| Mistral Medium 3.5 / Devstral 2 | 352.0 KiB | 44.00 GiB | Mistral AI page, Weights and cache (GQA 96/8, 88 layers, config.json) source | |
| Mixtral 8x22B | 224.0 KiB | 28.00 GiB | Mistral AI page, Weights and cache (GQA 48/8; 229,376 bytes per token) source | |
| Mixtral 8x7B | 128.0 KiB | 16.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Qwen3 32B | 256.0 KiB | 32.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Qwen3 8B | 144.0 KiB | 18.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Qwen3-235B-A22B | 188.0 KiB | 23.50 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Qwen3-30B-A3B | 96.0 KiB | 12.00 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| SmolLM2-135M | 22.5 KiB | 2.81 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Gemma 2 9B | 336.0 KiB | 21.66 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Gemma 3 1B | 26.0 KiB | 0.51 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Gemma 3 27B | 496.0 KiB | 10.41 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Llama 4 Maverick | 192.0 KiB | 7.12 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| Mistral 7B v0.1 | 128.0 KiB | 0.50 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| gpt-oss-120b | 72.0 KiB | 4.50 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| DeepSeek-V2 | 67.5 KiB | 8.44 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| DeepSeek-V3 | 68.6 KiB | 8.58 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| DeepSeek-V3.2 | 83.9 KiB | 10.48 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| DeepSeek-V4-Flash | 3.4 KiB | 0.42 GiB | DeepSeek page (21 CSA x 160 + 20 HCA x 4.5 B per token, estimate; DeepSeek's chart gives 3,514) source | |
| DeepSeek-V4-Pro | 4.8 KiB | 0.61 GiB | DeepSeek page (30 CSA x 160 B + 31 HCA x 4.5 B per token; FP8 entries, FP4 indexer; 128-token windows of 576 B in 61 layers) source | |
| DeepSeek-V4.1-Flash | 0.9 KiB | 0.11 GiB | DeepSeek page (890 bytes per token, reported on the model card) source | |
| GLM-5 / 5.1 | 107.2 KiB | 13.41 GiB | Zhipu GLM page, Long-context cost (78 x 576 + 78 x 128 numbers) source | |
| GLM-5.2 / 5.3 | 93.0 KiB | 11.62 GiB | Zhipu GLM page (IndexShare: 78 x 576 + 21 x 128 numbers) source | |
| Kimi K2 | 68.6 KiB | 8.58 GiB | root Config calculator (src/data/configs, 2026-10-18) source | |
| MiniMax-M3 | 134.2 KiB | 16.78 GiB | MiniMax page and config.json (60 layers, GQA 64/4 x 128: 120 KiB per token; 57 MSA layers (sparse_attention_freq) with one 128-number index key per token, BF16 assumed: 14.25 KiB; top 16 blocks of 128) source | |
| Mistral Large 3 | 68.6 KiB | 8.58 GiB | Mistral AI page (MLA, latent 512 + 64; 70,272 bytes per token) source | |
| Mistral Small 4 | 22.5 KiB | 2.81 GiB | Mistral AI page (MLA, latent 256 + 64; 23,040 bytes per token) source | |
| GLM-5.3-Flash | 11.7 KiB | 1.59 GiB | 136 MiB | Zhipu GLM page (11 sparse layers x (512 + 128/4 IndexPool); 34 KDA layers of 64 x 128 x 128) source |
| Kimi K3 | 27.0 KiB | 3.78 GiB | 414 MiB | LLM architecture gallery (24 x (512 + 64) MLA layers; KDA state about 414 MiB in FP32, rounded) source |
| MiniMax-Text-01 | 40.0 KiB | 5.27 GiB | 280 MiB | MiniMax page and config.json (attn_type_list: 10 softmax layers of 80, GQA 64/8 x 128, 40 KiB per token; 70 lightning layers x 64 heads x 128 x 128 state, 140 MiB in BF16) source |
| Nemotron-H 8B | 16.0 KiB | 2.10 GiB | 99 MiB | root Config calculator (src/data/configs, 2026-10-18) source |
| Qwen3-Next-80B-A3B | 24.0 KiB | 3.07 GiB | 75 MiB | root Config calculator (src/data/configs, 2026-10-18) source |
| Qwen3.5-397B-A17B | 30.0 KiB | 3.93 GiB | 180 MiB | Qwen page, Configs and cache (15 full layers x 2 x 2 x 256; 45 DeltaNet layers x 64 x 128 x 128) source |
| Qwen3.8-2.4T-A95B | 92.0 KiB | 12.04 GiB | 552 MiB | Qwen page, Configs and cache (23 full layers x 2 x 4 x 256; 69 DeltaNet layers x 128 x 128 x 128) source |
| Qwen3.8-27B | 64.0 KiB | 8.14 GiB | 144 MiB | Qwen page, Configs and cache (16 full layers x 2 x 4 x 256; 48 DeltaNet layers x 48 x 128 x 128) source |
| Qwen3.8-Flash-Next | 24.0 KiB | 3.11 GiB | 108 MiB | Qwen page, Configs and cache (12 full layers x 2 x 2 x 256; 36 DeltaNet layers x 48 x 128 x 128) source |
| LLaVA-1.5-7B | 512.0 KiB | 64.00 GiB | Vision-language models page (2 x 32 x 32 x 128 x 2 = 524,288 bytes) source | |
| Qwen3.5-0.8B | 12.0 KiB | 1.52 GiB | 19 MiB | Vision-language models page (6 attention layers of 24; 19,759,104-byte FP32 state, measured) source |
| SmolVLM-500M | 40.0 KiB | 5.00 GiB | Vision-language models page (2 x 32 x 5 x 64 x 2 = 40,960 bytes; measured slope equal) source |
This page's tabs, the parent and sibling pages, the knowledge base pages that own the neighbouring subjects, and the papers behind every lever, each with an approximate time. Outside sources are marked maker (by the lab that built the method or model) or third-party. Links checked on 2026-10-18; Mistral, Qwen and GLM sources read 1 to 19 October 2026 by their pages.
One token's cost, why decode and prefill slow down, every lever with its measured quality cost (eviction and quantisation on SmolLM2-135M, the tiny GPT past its length), effective context, and a design worked through. 22 min, plus 13 in closed details
45 real models, any context to 1M, the attention design as the variable; weights, GPU memory, sequences that fit, decode ceiling, and twelve published figures recomputed. a tool: 3 min to read, plus 6 in closed tables
The root: section 9 is the four walls in one paragraph, section 4 the four levers on the cache; its Config calculator (whose calc.py the KV-cache calculator reproduces byte for byte), Inside a real model (SmolLM2's attention sink) and Architecture map. 23 min, plus 13 in closed details
MHA, MQA, GQA, MLA, sliding windows as a cache design, sparse attention, sinks: what each token stores. 37 min, plus 28 in closed details
RoPE and the extension methods (PI, NTK, YaRN, Llama 3, LongRoPE): the position wall's fixes. This page's past-length runs are recorded for it in src/past/. 40 min, plus 21 in closed details
SSMs, linear attention and hybrids: the constant-state end of the cache spectrum. 37 min, plus 20 in closed details
The MLA before/after explainer: a 576-number cache entry against 32,768. 26 min
Needles, RULER, NoLiMa, MRCR, advertised against effective length for 39 published rows. 27 min
Paged caches, prefix caching, chunked prefill, preemption, and KV compression with the realisable-saving test. 37 min
HBM capacity and bandwidth, where the cache lives, and measured cache-read times on the M1 Pro. 27 min
FLOPs, bytes and the roofline that make decode bandwidth-bound. 24 min
Context parallelism among the other ways to split a training step. about 32 min
How a long-context training phase is run (it holds the former Continued Pretraining page). 45 min
Exact attention without the T x T matrix in memory. 26 min
When to retrieve into a short context instead of reading a long one. time on its page
Attention sinks; a sliding cache that keeps the first tokens. 40 min
Heavy-hitter eviction by accumulated attention. 40 min
Eviction scored by the prompt's observation window. 30 min
2-bit caches with keys per channel and values per token. 30 min
Sharing keys and values across adjacent layers. 25 min
Sliding windows plus cross-layer sharing, tested on RULER. 25 min
5 local : 1 global with 1,024-token windows; the KV-memory and perplexity ablations (section 5). 20 min for section 5
Alternating 4,096-window and global layers; Table 10 shrinks the window at inference. 15 min for sections 2 and 5
Sliding-window attention and the rolling buffer cache: "8x" less cache at 32K. 15 min
MLA and its cache formula (Table 1), the "93.3%" headline. 30 min for section 2
Compressed sparse attention: cache per token against V3.2 and GQA. 30 min
Why allocated cache is not used cache, and the block allocator every engine copied. 30 min
The per-token "card" convention and worked numbers for many architectures. 15 min
Context parallelism with K and V blocks passed round a ring. 30 min
Left-skewed position frequencies, and STRING. 30 min
Thirteen synthetic tasks and the "effective length" definition. 30 min
The model this page measures: data, training stages, the 2K to 8K extension (section 4.6). 40 min