Sam Babichenko

Reading notes / Efficient sequence models

Learned KV-cache eviction

Hauzenberger et al., 2026

Cache and budget
h;h; ggKV head; one of the query heads that share it
t;t; q;q; uukey position; current query position; a later query position
s,s, w,w, kksink tokens, recent window, long-range slots per head
B=s+w+kB=s+w+kper-head cache budget (2,048 or 4,096)
E(q)E(q)tokens competing for the long-range slots at query qq
SStraining sequence length, 16,384
Target and loss
pu→tp_{u\to t}dense attention probability from query uu to key tt
mt;m_t; NtN_tmean future attention to tt after it leaves the window; number of such queries
rh,ttgt;r^{\rm tgt}_{h,t}; r^h,t\hat r_{h,t}target log score; scorer's predicted score
γh\gamma_hper-head decay of scores with age, learned in [0.999, 0.999999][0.999,\,0.999999]
tnew;t_{\rm new}; tbndt_{\rm bnd}token that just left the window; lowest-ranked token the teacher keeps
yq,h;y_{q,h}; ωq,h\omega_{q,h}keep (+1+1) or drop (−1-1) label of tnewt_{\rm new}; weight of that example
ℓ(u,t);\ell(u,t); LSEu\mathrm{LSE}_uattention logit; log normalizer of query uu
Constants
ϵ\epsilonsmall constant inside the log of the target rtgtr^{\rm tgt}
τ\tautemperature of the boundary loss (1.0 in the paper)

Context. To decode without recomputing the past, a transformer keeps the key and value of every earlier token, the the stored keys and values of all earlier tokens, per layer and per KV head; it grows by one entry per head with every generated token, and reads all of it at every step, so memory and the time per token grow with the length of the output. Reasoning models now write traces of tens of thousands of tokens, which makes the cache the main cost of decoding. keeping a fixed number of cached tokens per head and permanently deleting the rest, which bounds memory; sparse retrieval methods instead keep the full cache and read only part of it keeps a fixed number of entries and deletes the rest, and the question is which to keep. Fixed rules keep the first few tokens and a recent window (an eviction rule that keeps the first few tokens (attention sinks) and a window of the most recent tokens, and drops everything in between (Xiao et al., 2023)) or the tokens with the most attention right now (an eviction rule that drops, once the cache is full, the token with the lowest attention from the current query (Oren et al., 2024)), and these are guesses about the future from the past. The learned method dynamic memory sparsification: binary keep-or-evict gates per token and head, trained through a continuous relaxation, with eviction delayed by a short window (Łańcucki et al., 2025) trains eviction gates through a continuous relaxation but is given no target for which tokens to keep. KVpop (Hauzenberger et al., 2026) supervises that choice directly.

Which cached tokens a model will need later is largely predictable, and there is a label for it in the model's own attention: the attention each token receives from the queries that come after it leaves the recent window. A small scorer per KV head, trained on that label, keeps Qwen3-4B at 97% and Qwen3-8B at 100% of their accuracy on competition math with a cache of 2,048 tokens per head, 12.5% of the 16,384-token training length, where the fixed rules keep between 19% and 58%. The scorer can also wait to score a token until it leaves the window, and so see what followed it. The model itself is fine-tuned along with the scorer, and that training alone, with a fixed sparse pattern, already recovers part of the gap; the learned choice of tokens accounts for the rest.

Setting. Each one set of keys and values; under grouped-query attention several query heads share it, and the cache is stored per KV head hh keeps s=4s=4 the first tokens of the sequence, kept permanently because attention heads put much of their weight on them, a protected window of the w=256w=256 most recent tokens and kk long-range slots, a budget B=s+w+kB=s+w+k of 2,048 or 4,096 entries. Positions are numbered from 0, so the sinks are positions 0 to s−1s-1. At query position qq the tokens E(q)={t: s≤t≤q−w}E(q)=\{t:\ s\le t\le q-w\} compete for the kk slots, and exactly one token, tnew=q−wt_{\rm new}=q-w, joins them. The label is the mean attention a token receives once it has left the window. With the dense causal attention probability from query position uu to key tt, for one query head gg of the group sharing KV head hh and SS the training sequence length,mt=1Nt∑u=t+wS−1pu→t,Nt=max⁡(1,S−t−w),rh,ttgt=max⁡g log⁡(ϵ+mt(h,g)),\begin{aligned}m_t&=\frac{1}{N_t}\sum_{u=t+w}^{S-1}p_{u\to t},\\N_t&=\max(1,S-t-w),\\r^{\rm tgt}_{h,t}&=\max_{g}\,\log\big(\epsilon+m^{(h,g)}_t\big),\end{aligned}where the maximum over the query heads sharing the KV entry keeps a token that any one of them relies on, and ϵ\epsilon is a small constant. Both the target ranking and the scorer's ranking subtract the token's age times a learned per-head rate, adding (q−t)log⁡γh(q-t)\log\gamma_h with a learned decay per KV head, constrained to [0.999, 0.999999][0.999,\,0.999999]; at 0.999 a token's score falls by 1 per 1,000 tokens of age, so a token with a high score cannot hold its slot forever. The teacher (the original model with its full cache, whose attention gives the target) keeps the kk best tokens of E(q)E(q) under this ranking; let tbndt_{\rm bnd} be the lowest-ranked token it keeps and yq,h=+1y_{q,h}=+1 if it keeps tnewt_{\rm new}, −1-1 if not. The scorer's predicted scores r^\hat r, age-adjusted the same way to r^h,t(q)=r^h,t+(q−t)log⁡γh\hat r_{h,t}(q)=\hat r_{h,t}+(q-t)\log\gamma_h, are trained with a logistic loss on that single pair:Lscore=Eq,h[ ωq,h softplus(−yq,h Δq,h/τ)],Δq,h=r^h,tnew(q)−r^h,tbnd(q).\begin{aligned}L_{\rm score}=\mathbb E_{q,h}\Big[&\,\omega_{q,h}\,\mathrm{softplus}\Big(\\&-y_{q,h}\,\Delta_{q,h}/\tau\Big)\Big],\\\Delta_{q,h}&=\hat r_{h,t_{\rm new}}(q)-\hat r_{h,t_{\rm bnd}}(q).\end{aligned}Here τ\tau is a temperature, ωq,h\omega_{q,h} a weight that discounts near-ties and balances keep and drop labels, and softplus(x)=log⁡(1+ex)\mathrm{softplus}(x)=\log(1+e^x), a smooth version of max⁡(x,0)\max(x,0) makes the loss small once the decision is right by a margin. Comparing with the cutoff token trains exactly the decision that changes what is in the cache.

Computing the target, and running the cache. The target needs, for each key, a sum over all later queries, a column sum of the S×SS\times S attention matrix, which an attention kernel never forms. Write ℓ(u,t)\ell(u,t) for the attention ℓ(u,t)=qu⊤kt/dk\ell(u,t)=q_u^\top k_t/\sqrt{d_k}, the score before the softmax, with dkd_k the key dimension and LSEu=log⁡∑t′≤ueℓ(u,t′)\mathrm{LSE}_u=\log\sum_{t'\le u}e^{\ell(u,t')} for the softmax normalizer of query uu, which PyTorch's compiled path for attention variants written as a score modifier and a mask, which also returns each row's log normalizer returns with its output. Thenlog⁡∑u≥t+wpu→t=log⁡∑u≥t+weℓ(u,t)−LSEu,\begin{aligned}&\log\sum_{u\ge t+w}p_{u\to t}\\&\quad=\log\sum_{u\ge t+w}e^{\ell(u,t)-\mathrm{LSE}_u},\end{aligned}a log-sum-exp over uu for fixed tt, which is what an attention call returns for each query once queries and keys swap roles: key tt becomes the query, the score modifier subtracts LSEu\mathrm{LSE}_u and the mask keeps u≥t+wu\ge t+w. One extra attention-like pass during training gives every target, and the paper uses the normalizers of the sparse attention it already computes in place of the dense ones, which it finds works as well. Selection is cheap too: with a fixed decay rate the ranking at every query equals a ranking by one static priority per token, so each new eligible token is inserted into a a binary indexed tree: an array that supports adding a count and finding where a running count reaches a value, each in logarithmic time of ranks and the kk-th best is read off, O(Slog⁡S)O(S\log S) per head, and the resulting mask is evaluated inside the attention kernel. The scorer is either a two-layer MLP on the token's key and value (KVpopmlp_{\rm mlp}) or an a gated linear-attention cell from xLSTM: a fixed-size matrix memory that each token updates with a gated outer product of its key and value features, read with a query vector per KV head that has read the keys and values up to qq when it scores tnew=q−wt_{\rm new}=q-w, so the decision uses the 256 tokens that followed the token. Scorer inputs are detached: the scorer learns only from LscoreL_{\rm score} and the model only from a KL divergence to the dense teacher's top 256 logits.

In practice KVpop is a retrofit: about 2,000 steps of full fine-tuning (2B tokens on 8 H100s in the paper) of an existing model on long reasoning traces, after which every head carries the same fixed-size cache. For Qwen3 models on competition math, a 4,096-entry cache per head lost at most 2% of accuracy and a 2,048-entry cache cost 0 to 3% of accuracy, with peak memory flat at about 19 GB while dense decoding reached 36 GB at 131K tokens. The uniform per-head budget matters for speed: DMS lets a few heads keep most of the long-range budget, which gives ragged caches that are slow to execute, and KVpop decoded 131K tokens in about 40% of DMS's time (read off a plot). The authors have not yet tested it in a paged serving system such as vLLM, so the speed figures come from a research implementation at batch size 1.

Step 1

On competition math, learned eviction keeps almost all of the dense accuracy where fixed rules lose half. Qwen3-4B-Instruct and Qwen3-8B (in thinking mode) were retrofitted on high-effort math traces of at most 16,384 tokens and scored by pass@1 over 16 samples on AIME 2024 and 2025 and HMMT February and November 2025, about 120 problems. At 88% compression (a budget of 2,048 per head against the 16,384-token training length) the averages for 4B and 8B are 0.45 and 0.43 for the dense teacher, 0.21 and 0.08 for StreamingLLM, 0.26 and 0.08 for TOVA, 0.33 and 0.29 for StreamingLLM fine-tuned with the same budget, 0.40 and 0.36 for DMS, 0.42 and 0.42 for KVpopmlp_{\rm mlp}, and 0.44 and 0.43 for KVpop with the mLSTM scorer. The baselines separate two effects. Fine-tuning the model under StreamingLLM's fixed pattern, with the same budget and training, recovers part of the gap, so some of the gain is the model adapting to a sparse cache. DMS, trained with the same budget and a scorer of matched size, trails KVpop by 8 points of relative accuracy on 4B and 16 on 8B, which the authors attribute to the future-attention target, since budget and scorer size are matched. At 75% compression (a budget of 4,096) every method except StreamingLLM on 8B improves, and KVpop, DMS and KVpopmlp_{\rm mlp} are within 0.01 to 0.03 of each other and of the teacher. By my rough estimate the sampling noise (one standard deviation) of a difference between two such averages is at most about 0.016, the binomial bound 2⋅14/(120⋅16)\sqrt{2\cdot\tfrac14/(120\cdot16)} for 120 problems with 16 samples each, and nearer 0.013 if many problems are always or never solved; training-seed variation would add to it, so gaps of 0.01 to 0.02 are not resolved.

Step 2

On code and science questions, which need shorter traces, all eviction methods stay near the dense model. On a set of hard multiple-choice science questions written by domain experts and a benchmark of programming problems collected after model training cutoffs, scored by running the code, outside the math training data, the Qwen3-4B teacher scores 0.59 and 0.35, KVpop 0.56 to 0.57 and 0.33 to 0.34, and even untrained StreamingLLM 0.49 to 0.54 and 0.35 to 0.36. The learned policy stays close to the dense model out of domain (Qwen3-4B only), and these tasks do not separate the methods; the paper notes that they need smaller reasoning budgets than the math benchmarks.

Step 3

Delayed scoring helps a little, and the policy keeps the tokens that structure the argument. Scoring each token when it leaves the window, with the mLSTM's memory of what followed, raises the share of next tokens the model predicts correctly, about 0.77 here (read off the plot) over scoring it on arrival by about 0.002 (0.2 percentage points) after 2,000 steps, a small effect; in the main table the mLSTM scorer's advantage over the MLP shows mainly at 88% compression (0.97 against 0.93 of the teacher on 4B, a gap of 0.02 in absolute pass@1, near the noise level estimated in Step 1). At 75% compression on 4B, the scorer keeps on average 81% of the tokens the oracle ranking by true future attention would keep. In the traces shown, it drops purely numeric tokens more often and keeps tokens that structure the argument (Thus, =, operation words) across more heads and layers, while the first layer keeps nearly everything. DMS under the same budget ends with a few heads using nearly the whole long-range budget and many heads reduced to the sliding window.

Step 4

Memory stays flat and decoding is faster at long generations. For Qwen3-8B at 75% compression and batch size 1, peak memory for dense attention rises from 18 GB at 16K generated tokens to 36 GB at 131K, while KVpop and DMS stay near 16 to 19 GB. End-to-end time to generate 128K tokens is roughly 33,000 s dense, 6,000 s for DMS and 2,500 s for KVpop (approximate, read off the plot), all with the Hugging Face implementations; the dense time grows faster than linearly in this implementation. KVpop's lead over DMS comes from the equal budget per head, which compiles and runs as regular tensors.

Terms

Budget B=s+w+kB=s+w+k
4 sinks, a protected recent window, and kk long-range slots chosen by the scorer; 2,048 or 4,096 per head
Future-attention target
mt=1Nt∑u≥t+wpu→tm_t=\frac1{N_t}\sum_{u\ge t+w}p_{u\to t}, the mean attention tt receives after leaving the window; max over query heads
Age decay
scores ranked with (q−t)log⁡γh(q-t)\log\gamma_h added, γh∈[0.999,0.999999]\gamma_h\in[0.999,0.999999], so old high scorers can be displaced
Boundary loss
logistic loss on r^tnew−r^tbnd\hat r_{t_{\rm new}}-\hat r_{t_{\rm bnd}}, labeled by whether the teacher keeps tnewt_{\rm new}
Transposed attention
swap queries and keys and subtract LSEu\mathrm{LSE}_u: the returned log normalizer is each key's log future attention
Delayed scoring
an mLSTM scorer scores a token when it leaves the window, after reading the 256 tokens that followed it
Fine-tuned StreamingLLM
same training and budget with a fixed pattern; separates model adaptation from learned token choice
Results at 88% compression
KVpop 0.97 (4B) and 1.00 (8B) of teacher accuracy; DMS 0.89 and 0.84; StreamingLLM 0.47 and 0.19
Memory and time
Qwen3-8B to 131K tokens: dense 18 to 36 GB, KVpop about 19 GB; KVpop about 2,500 s against 6,000 s for DMS (read off a plot)

Quiz

  1. What label does KVpop train its scorer to predict for each cached token?
  2. Why is the scorer's loss computed only on the pair tnewt_{\rm new} and tbndt_{\rm bnd} at each query?
  3. Why does KVpop decode long generations faster than DMS at a comparable budget?

Sources