2026-10-02 · 23 min · kv-cache · inference · long-context · attention
A 1:26 narrated explainer, drawn in code. Every number and picture in it is this article's own; the sources are below.
› transcript
Hi, I'm Oskar. A long chat fills a cache of past tokens, and it gets huge. Let me show you how to shrink it and still reuse it. The trick is to score the cache without looking at your question. Then one compressed cache can answer any question you ask later. First, read the whole context once and store it as a key value cache. Then ask the model to read that context again, straight from the cache. Give each stored pair a score: the most attention it gets during that reread. Keep the pairs that earned attention, and throw the rest away. The scoring never saw your question, so this one cache serves any query. The old way scores the cache against the current question, so it fits that one question and nothing else. Score by rereading instead, and the same small cache holds up across every later question. Here is the full cache, one cell per stored pair. Keep about the top thirty percent, and the answers barely change. That is three to four times less memory, and about twice the decode speed, with almost no loss. Score the cache without your question, and you compress it once and reuse it for every answer. So: reread to score the cache, compress once and reuse, and get it three to four times smaller and about twice as fast. Every source is in the full article. I'm Oskar. Bye!
Why read this
Essentialtop 10%Runs KVzip's official scorer: reproduces its Figure 5 and measures prefill-scored vs reread-scored eviction on one reused cache. Checks Ramp's GLM-5.3 80%.
- Interactive explanations
- Original analysis
- Runs on a consumer GPU
Inference & servingMITResearch paper
How this was scored
- Is it new?
- 2 of 3: A real new idea, method or capability
- Can I trust it?
- 2 of 3: Measures key facts from files, code or configs
- Can I run it?
- 2 of 3: Open code or weights with real limits
- Will I understand it?
- 3 of 3: Mechanism carried by interactives built from real code or data
- Can I act on it?
- 2 of 3: A concrete recipe, numbers or comparison
- Will it last?
- 2 of 3: A reference for a year or more
- Does it affect many?
- 2 of 3: A widely used model, tool or lab release
- Only here?
- 2 of 3: A teardown or measurement few others did
Score 75 of 100, ranked 75 of 773 rated articles. Each question is answered 0–3 by hand, and a 3 is rare. How articles are scored
Long context costs memory, and most of that memory is the KV cache. KVzip (arXiv 2505.23416, NeurIPS'25 oral, MIT code) shrinks it with one idea: score every cached pair by how much the model needs it to recite the context back, then throw away the pairs it never reaches for. Because no question is involved in the scoring, the compressed cache serves every question that comes later.
The first version of this page explained that idea from the papers and repository and ran nothing. This one runs it. I installed the official code on an RTX 3090, scored real contexts with its own scorer, and measured the claim the method rests on: that the attention a pair gets during the reread is a better guide to keep it than the attention it got while the context was first read. It is, by a wide margin. One thing the earlier version of this page had backwards is fixed below too.
The second half covers Attention Matching (arXiv 2602.16284), which keeps none of the real pairs and fits a smaller synthetic cache, and the Ramp Labs write-up that put both methods on GLM-5.3 and reported an 80% smaller cache.
The cache is the bill
A decoder-only transformer stores, for every token it has seen, the key and value vectors of every attention layer. Generating the next token is then one attention step over that store instead of a re-read of the whole prompt. The KV cache architecture note covers MHA, MQA, GQA and MLA byte by byte; how self-attention works sits under it.
The store grows linearly with context. The KVzip paper's own example: 120K tokens in Qwen2.5-14B at FP16 is about 33 GB of cache, more than the model's 28 GB of weights at the same precision. Every decoded token reads all of it, so the cache sets attention latency as well as memory. Halve it and you get both back.
Shrinking it means dropping pairs. Every method answers the same question differently: which pairs, and scored against what?
A cache scored for one question fails the next
H2O, SnapKV and PyramidKV score each cached pair by how much the current query attends to it, then keep the top fraction. In a one-question setting that works. The tokens the question looks at are the tokens its answer needs.
It breaks when the cache is reused. Compress a document's cache for the first question and you have kept what that question looked at. Ask a second, unrelated question and the pairs it needs may be gone. The KVzip paper measures this on SQuAD with LLaMA3.1-8B (its Figure 2): SnapKV holds up when it re-runs prefill and compression for every question, and falls away when the cache compressed for the first question is reused for the rest. The abstract puts it bluntly: query-aware methods "suffer from performance degradation even at a 90% cache budget ratio under multi-query scenarios."
So the score has to be query-agnostic. Compute it once, without reference to any future question, and one compressed cache can serve a whole conversation.
The reread
KVzip's query-agnostic question is: which pairs does the model need in order to reproduce this context? After the normal prefill, it runs one more forward pass over the cache. The input is a repeat instruction followed by the context itself, teacher-forced, so a single pass simulates the model reciting its context. The code states the prompt literally:
# model/wrapper.py: the reconstruction "query" is the same for every context
prompt = "\n\nRepeat the previous context exactly."
# later chunks: "...starting with <last 8 tokens of the previous chunk>"
input_ids.append((a_ids, torch.cat([q_ids, self.postfix_ids, a_ids], dim=1)))During that pass each cached pair receives some attention from each reciting position. Its importance is the maximum it receives, over every reciting position and every query head that shares its KV head (grouped-query attention):
# attention/score.py: softmax over keys, then max over the GQA group and the queries
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
score = attn_weights[..., self.sink:self.sink + ctx_len].amax(dim=(-3, -2))Writing for the attention that reciting position in query head puts on cached pair , after the softmax:
Max, not sum, so a pair that one reciting position depends on heavily is kept even if nothing else looks at it. The system prompt (the "sink") is never evicted. Eviction is a single global threshold over every layer and KV head, so a head whose pairs score high keeps more of them; KVzip adapts AdaKV's variable-length FlashAttention kernel to run a cache with a different length per head.

Why the reread and not the first read
There is a cheaper query-agnostic score sitting right there: the attention each pair received during prefill, when the context read itself. No second pass needed. Why not use that?
The paper's answer is its Figure 5, a histogram of the max attention per pair under both passes, on SQuAD with LLaMA3.1-8B. The reread is sparser. During prefill a model mixes information densely across tokens, so many pairs collect a moderate maximum; during the reread most pairs get almost nothing and a few get a lot, because the model can lean on what the cache already encodes plus what its weights know. The data files behind the figure ship in the arXiv source. As plotted, in bins of 0.1, 81.6% of pairs get a maximum below 0.1 under reconstruction against 55.0% under prefill; a finer copy of the same data in bins of 0.05 puts 71.9% against 33.5% below 0.05.
The earlier version of this page said the opposite: that prefill attention is the spiky one and reconstruction the broad one. That was wrong, and the widget that illustrated it was a toy built on the wrong direction. The chart below replaces it with data.
To check the figure I ran the official scorer, unmodified, on Qwen3-4B-Instruct-2507 (one RTX 3090, bf16, KVzip's RetainCache), and added a hook that records the prefill-side maximum from the same query and key states. The reconstruction scores are KVzip's own kv.score. Two sets of contexts: the first 101 SQuAD training contexts that KVzip's own load_squad returns (5,892,480 scored pairs in all), and one 8,000-token context from the Paul Graham essay haystack the repository ships for its needle test.
On SQuAD, 66.6% of Qwen3-4B's pairs fall in the lowest bin under reconstruction and 22.2% under prefill. In the paper's coarser 0.1 bins that is 76.4% against 37.0%, next to LLaMA3.1-8B's 81.6% against 55.0%. On the long essay it is 75.2% against 24.9%. Different model, same shape as the paper's LLaMA numbers. One detail I had to decide: during prefill every token attends to itself, and that self-attention can set a pair's maximum. Dropping it (the checkbox) moves the prefill histogram further toward zero, to 33.6% in the lowest bin on SQuAD, but it stays well short of the reread's sparsity. The headline figures use KVzip-style scoring with the diagonal included.
Sparse is only good if it is also right. A score that is near zero for most pairs is useful for eviction if those pairs really are dispensable. So the second measurement: one prefill per context, then every SQuAD question about that context answered from the same cache, after evicting by the reconstruction score, by the prefill score, or by a seeded random score. Same model, same KVzip global threshold, same greedy decoding (32 new tokens); an answer counts as correct when a gold SQuAD answer string appears in it. That is 98 questions over the first 20 contexts, each run at four cache sizes.
With the full cache the model gets 89 of the 98 right (90.8%). Keep 20% of the cache by KVzip's reread score and it gets 91; keep 30% or 50% and it gets 90 and 89. Those are the same as the full cache within a question or two, which on 98 questions is noise. At 10% it drops to 71. Score by prefill attention instead and the same budgets give 15, 17 and 41 at 20%, 30% and 50%, and 7 at 10%. Random eviction gives 14, 37 and 69, and 8 at 10%.
That last comparison is the surprise: at 30% and 50% of the cache, evicting by prefill attention is worse than evicting at random. It is also a claim about one exact setup (prefill score with each token's self-attention included, under KVzip's single global threshold across heads), so I reran the same contexts with two changes. The loader's cut-off leaves 94 questions on this run, with 85 right on the full cache.
| Kept | Prefill, no self-attention, global | Prefill, uniform per head | Reread, uniform per head | Reread, global (main run, of 98) |
|---|---|---|---|---|
| 10% | 14 | 21 | 17 | 71 |
| 20% | 18 | 28 | 38 | 91 |
| 30% | 28 | 50 | 53 | 90 |
| 50% | 42 | 66 | 73 | 89 |
Dropping the self-attention term helps the prefill score a little and it stays below random at 30% and 50%. The bigger effect is the budget. Give every KV head the same share (KVzip's pair_uniform mode) and the prefill score recovers most of the way to the reread score, while the reread score loses most of its lead: 53 against 50 at 30%, and at 10% the prefill score is ahead. So in my run the reread score and the global threshold work as a pair. A global threshold lets a head whose pairs score high keep more of them, which is the right call when the score means "needed to reproduce the context" and the wrong one when it means "attended to while reading". The paper makes the same point in its own ablation (its Figure 16, LLaMA3.1-8B on SQuAD): 92.4 with the non-uniform budget against 77.9 with a uniform one at 30% kept, a smaller gap than mine but the same direction.
This is small-scale. SQuAD contexts are short (a few hundred tokens), the model is 4B, and string containment is a coarse grader. It is not a replication of the paper's benchmark grid. What it does show is the mechanism and its dependency: with KVzip's global budget, the reread score keeps what later questions need and the first-read score does not, at every budget I tried; with a uniform per-head budget, much of that difference goes away.
The paper's own numbers
The efficiency claim is 3-4x smaller KV cache and about 2x faster FlashAttention decode with negligible loss, measured on LLaMA3.1-8B with a 124K-token context on an A100 in FP16 (their Figure 8). The 2x is attention decode latency, not end-to-end generation.
The accuracy claim is the benchmark grid below: twelve datasets on Qwen2.5-7B-Instruct-1M, accuracy against the share of cache kept. KVzip stays near flat down to about 30% while H2O, SnapKV and PyramidKV fall away, worst on retrieval tasks where a query-aware cache threw the needle out.

The models span 3B to 14B (LLaMA3.1-3B and 8B, Qwen2.5-7B-1M and 14B-1M, Gemma3-12B) at contexts up to 170K tokens. Gemma3 is compressed only on its global-attention layers.
The reread is not free. The paper puts the scoring pass at "approximately twice the computational overhead of standard prefill" with under 2% extra memory, paid once per context. It scores in chunks of tokens, so the cost is per chunk and over a context of tokens. On my 8,000-token essay the official code took 1.27 s to prefill and 2.66 s to score on the 3090 (one timing, on a box other jobs were sharing), 2.1 times the prefill time, which is about what the paper says. Part of that is structural: the score needs a max over query positions after the softmax over keys, which a fused FlashAttention kernel never materialises, so the scoring pass runs attention the slow way. The paper also tests a softmax-free variant that scores on raw logits and trades a little quality for that (its Figure 15).
There is also a cheaper mode. Context-independent KVzip computes per-head scores once per model and drops whole heads' context KV, DuoAttention-style, with no per-context cost but a smaller ratio (--ratio 0.6 recommended, about 1.67x). The README describes the head-score fit as "a few forward passes within one minute", against DuoAttention's optimisation-based fit.
[NeurIPS'25 Oral] Query-agnostic KV cache eviction: 3–4× reduction in memory and 2× decrease in latency (Qwen3/2.5, Gemma3, LLaMA3)
- license
- MIT
- branch
- main
- forks
- 17
- open issues
- 5
- tests
- none found
- source
- 175.3 kB
- commit date
- 2026-02-11
GitHub REST API, 2026-11-21 — branch, commit, commitDate, createdAt, description, forks, languages, license, openIssues, pushedAt, stars, topics
local clone, 2026-10-02 at 5d84729 — fileCount, hasTests, licenseFile, shallow
shallow clone: counts describe the pinned tree, not the history
One stacked number from the paper: KVzip on top of QServe's 4-bit KV quantization takes a 16.3 GB FP16 cache at 124K tokens to 1.2 GB with 70% eviction. 16.3 / 1.2 is about 13.6x. Eviction and quantization are separate axes, and they multiply.
Attention Matching keeps none of the real pairs
KVzip keeps a subset of the cached pairs exactly as they were. Fast KV Compaction via Attention Matching (Adam Zweiger, Xinghong Fu, Han Guo and Yoon Kim; arXiv 2602.16284, code, MIT) keeps none of them unchanged. It builds a shorter cache whose keys, per-key biases and values are fitted so that attention over the short cache behaves like attention over the long one.
Take one KV head. The full cache is with rows. The compact cache is with rows, where is a scalar bias added to each compact key's logit. The requirement is that the compacted prefix still works when later tokens are appended: the user's next turn, the model's own continuation. Attention over a concatenation of blocks is a mixture of each block's local attention, weighted by each block's share of the softmax mass. So for a set of reference queries it is enough to match two quantities for the prefix block:
Match the mass and the block keeps its right share of attention against whatever comes after it. Match the local output and that share carries the right content.

Solving that jointly would be a nonconvex fit. The paper splits it into three steps, two of which have closed forms:
- Pick the compact keys from the real keys. Two rules: HighestAttnKeys keeps the keys with the largest aggregated attention under the reference queries (the same family of score as KVzip's; the paper's appendix compares aggregation functions), and OMP (orthogonal matching pursuit) greedily adds whichever key best explains the attention mass the current set still misses.
- Fit the mass. With keys fixed, the mass condition is linear in : a nonnegative least squares over the reference queries. Then . A of 5 says this one kept key now stands in for about five keys' worth of attention mass.
- Fit the values. With keys and biases fixed, the attention weights over the compact cache are known numbers, and the value condition is ordinary least squares for .
The reference queries come mainly from a repeat-prefill pass (the same reread KVzip uses), with a few self-study prompts to widen them, and the cache is built one layer at a time so each layer is fitted to the queries the already-compacted layers below it actually produce.

That figure is where "50x in seconds" comes from, and it is worth reading carefully. At 50x the original cache scores about 0.71 on QuALITY. The fastest fitted variant (HighestAttnKeys-fast, roughly 8 seconds per article) lands near 0.58; the OMP variants reach about 0.66 but take minutes per article. KVzip, as one of the baselines, sits near 0.42 at this ratio. Fifty-fold compaction is far past where KVzip's paper evaluates it (its curves stop at a 0.1 ratio, 10x), so this is a comparison at the far end of the range, not a contradiction of KVzip's own results.

Across ratios the picture is the same. From about 0.05 of the cache upward, the AM curves sit near the full-cache line on most panels. KVzip closes the gap at 0.10-0.20 on some of them, and the paper credits KVzip's non-uniform head budget for that ("KVzip sometimes matches Attention Matching performance, which we attribute to its non-uniform budget outperforming our precomputed budget at certain compaction ratios"). Their appendix also runs the 6,500 RULER tasks from NVIDIA's kvpress: at 5% of the cache on Llama-3.1-8B-Instruct, KVzip scores 46.6 and AM-HighestAttnKeys-fast 83.3, and at 12.5% they are 92.3 and 95.1 against 95.7 for the full cache (their Table 11). Stacked on a summary, AM-OMP reaches about 200x total (6,340 to 31 effective tokens on average) at roughly the summary's own accuracy (their Table 4).
Two limits stay in the paper. Everything is per KV head, with separate keys, biases and values for each, and nothing addresses a cache that is shared across heads. And the models stop at 12B.
What Ramp Labs actually measured on GLM-5.3
The write-up that brought both papers to this site is Ramp Labs' "Scaling KV Cache Compression to Frontier Models" (Jeff Zheng and Alex Chen, posted as an X article). Its model is GLM-5.3, the 78-layer model, not the smaller GLM-5.3-Flash the earlier version of this page pointed at. Their architecture description matches the config the GLM-5.3 page reads: DeepSeek Sparse Attention, where a learned indexer picks at most 2,048 positions for each query; IndexShare, which reuses one indexer's selection across a group of layers (21 groups); and multi-head latent attention, where one shared 576-dimensional latent key and 512-dimensional latent value serve all 64 query heads in a layer.
That breaks both methods as published. KVzip and Attention Matching choose a separate set of positions per layer and head, and a shared latent cache needs one set for every head in an IndexShare group. And sparse attention only scores what the indexer selected, so a position with no observed attention may simply never have been routed. Their fixes:
- KVzip: run the reread with dense attention through all 78 layers, so every position gets a score, then choose one shared set per group. Taking the raw maximum across the group lets a few loud heads take the budget. Normalising each head's scores to sum to one first ("normalized maximum") raised strict accuracy on 47 ComplexMCP tool-use tasks at 30% compression to 60.3%, 5.0 points above the raw maximum, over three runs.
- Attention Matching: keep shared keys, but fit a separate bias per head and key, then fit shared latent values jointly across heads, layer by layer on queries from the already-compressed lower layers. That is the MLA extension the Attention Matching paper does not have.
The 80% headline comes from the second one. On QuALITY, five articles and 90 questions, four runs, full context scores 91.8%. Attention Matching with OMP keeps 83.9% at 80% compression, 81.8% at 90% and 77.8% at 95%; with HighestAttnKeys it is 73.7% at 95%; eviction alone with their KVzip adaptation is 67.8% at 95%.
So the claim checks as arithmetic: 83.9 / 91.8 is 91.4% of full-context accuracy at 80% compression. Carry the context with it. The method behind it is Attention Matching with OMP, not KVzip. The sample is 90 questions on five articles, where one question is 1.1 points. And no code is released, so the run cannot be repeated. A reply under the post makes the serving point too: 80% smaller lifts a KV-bound concurrency ceiling by at most 5x, and accuracy alone does not show whether scoring overhead keeps time-to-first-token and tail latency intact. Ramp's own number for that overhead is a 199.775-second dense score-capture pass on their ComplexMCP prefix of 29,807 tokens.
What the write-up does show is that a per-head method can be bent onto a shared-latent sparse model and still work, and that on such a model fitting beats eviction by about 10 points at 95%. That second result agrees with the Attention Matching paper's own small-model comparisons.
Subset or synthesis
Quantization makes each cached number smaller (4-bit KV via Model Optimizer, sub-2-bit runtime compression). Architecture makes the cache grow slower (GLM-5.3-Flash's linear and sparse layers, SparDA, Grouped Value Attention, Flash-dLLM). These two methods work after the fact. KVzip keeps a subset of the real pairs; Attention Matching keeps synthetic ones fitted to behave like the whole.
If I were adding one of them to a serving stack today, I would start with KVzip. It is a scorer and a mask over a cache you already have, the reread costs about one extra prefill per context, and at the ratios its paper evaluates (down to 30% kept) the curves are close to flat. My run says its central mechanism is real, with a condition attached: the reread score plus the global cross-head budget is what makes query-agnostic eviction work, and the cheaper first-read score is not a substitute under that budget. Keep the non-uniform budget if you adopt it; my uniform-budget run lost most of the gain. Past 10x, the Attention Matching results say fitting beats any subset, and Ramp's GLM-5.3 run agrees. I would want their code before believing the 80% transfers to a different workload.