CompilerKV: Risk-Adaptive KV Cache Compression via Offline Experience Compilation

Ning Yang, Chengzhi Wang, Yibo Liu, Baoliang Tian, Haijun ZhangNeurIPS 2026

TL;DR

When compressing an LLM’s memory (KV cache) right after reading a prompt, you only get one shot—throw away the wrong token, and it’s gone forever. Existing methods try to guess which tokens matter on the fly using noisy statistics from that single prompt, leading to painful errors on complex inputs. CompilerKV flips the script by learning stable, model-wide rules offline across thousands of prompts, reducing live runtime decisions to tiny, ultra-fast $O(1)$ table lookups that dramatically preserve accuracy under extreme memory pressure.

What Problem Does This Paper Address?

As LLM context windows stretch to 128k tokens and beyond, the Key–Value (KV) cache—the model's working memory—balloons to over 100 GB even for a 7B model. A popular, deployment-friendly fix is prefill-only KV compression: right after reading the prompt (prefill), the system selects a small subset of tokens to keep, freezes that cache, and generates the response without ever touching the memory layout again.

Because this decision is irreversible, mistakes are permanent. Existing methods (like SnapKV or PyramidKV) decide what to keep by analyzing attention scores online, looking only at the single current prompt. The authors argue that a single prompt is the wrong statistical unit. Relying on one prompt exposes you to three fatal traps:

  1. Single-prompt noise (E1): Attention scores within one prompt are spiky, heavy-tailed, and biased by scale.
  2. Head heterogeneity (E2): Some attention heads are surgical retrieval specialists, while others consistently emit noise. Averaging them lets the noisy majority drown out the specialists.
  3. Prompt-level risk variance (E3): Easy prompts can be aggressively pruned, while complex, high-entropy prompts break if you cut too much. A rigid global rule fails on the hardest examples.
Figure 1: Empirical evidence that E1–E3 are real, distinct failure modes on calibration data. (a) The same token’s attention score has very different distributions across prompts (low-noise vs. high-noise prompt) and across heads (a scale-biased head spans a much wider range), confirming E1. (b) The aggregated distribution of compiled head-reliability weights is bimodal: a substantial cluster of heads is consistently down-weighted (noise emitters), while a smaller cluster receives weights >1.1 (retrieval-critical), confirming E2. (c) The compression damage of a fixed Top-k rule (color: NLL gap to FullKV) varies systematically with attention entropy and local perplexity, confirming E3 as a prompt-level effect that no global k can absorb.

Methods

The core realization behind CompilerKV is that while token importance changes per prompt, which heads are reliable and how sensitive a prompt is to pruning are stable architectural properties baked in during pre-training. Instead of re-estimating them online, CompilerKV compiles them offline once into tiny lookup tables (<100 KB for an 8B model) using a 50k-prompt calibration corpus.

Figure 2: Overview of the COMPILERKV framework. The pipeline has three stages: (1) a stabilized utility score that suppresses transient noise; (2) a compiled Head Heterogeneity Table that governs functional differences among attention heads; and (3) a compiled Risk-Adaptive Gating Table that calibrates the retention threshold to each prompt’s complexity.

At inference time, after a standard observation-window scan at the end of the prompt, CompilerKV executes three sequential steps—mapping cleanly to E1–E3—with minimal $O(1)$ table-lookup overhead:

  • Stabilized Token Utility (fixes E1): A parameter-free signal-processing step that smooths transient spikes via window aggregation and normalizes value norms within each head to remove scale bias.
  • Head Heterogeneity Table (fixes E2): An offline-compiled lookup table of continuous reliability weights per head. During inference, tokens are scored via weighted max-pooling across heads—giving reliable retrieval heads "veto power" to save an important token even if noisy heads ignore it.
  • Risk-Adaptive Threshold Gate (fixes E3): A 2D lookup table mapping a prompt's structural risk (attention entropy) and semantic risk (local perplexity) to a safe retention threshold. Low-risk prompts can elastically retain fewer tokens than the budget, while high-risk prompts drop the threshold and clamp cleanly at the hard budget limit.

What’s novel is how the two tables are trained: the authors frame policy compilation as a single-step contextual bandit solved via Conservative Q-Learning (CQL). CQL penalizes uncertain, rarely seen high-risk states, biasing the gate toward safer token retention on tricky tail prompts. Crucially, the head table and risk gate are compiled jointly against downstream Negative Log-Likelihood (NLL) loss, ensuring the threshold adapts to the exact score distribution created by the head weights.

Datasets

  • Calibration (Offline Compilation): Two disjoint ~50k long-context corpora—one scientific (arXiv + PubMed) and one conversational (ShareGPT + UltraChat)—used to fit the tables and test cross-domain transfer.
  • Evaluation: LongBench (16 multitask benchmarks), RULER (synthetic retrieval and length scaling from 16k to 128k), Needle-in-a-Haystack (NIAH) at 32k, and MATH-500 for reasoning transfer. No new benchmarks are introduced.

Key Insights and Ideas

  • Head reliability is a portable architectural prior: Compiled head-reliability rankings are remarkably consistent across completely unrelated text domains (mean Spearman correlation $\bar{\rho} = 0.90$ between scientific papers and chat logs). Even wilder: you can take a table compiled on one model and plug it directly into a different model architecture, losing only 0.4–0.8 LongBench points on average.
  • Denoising can occasionally beat no compression at all: At a 512-token budget, CompilerKV slightly outperforms the uncompressed FullKV baseline on three out of four backbones. Suppressing noisy heads acts as a regularizer—though at extreme 128-token bottlenecks, FullKV expectedly takes back the lead.
  • Elasticity + coupled CQL is the secret sauce: Ablations reveal that removing elastic threshold gating causes the single biggest accuracy drop (~4.2 points), and compiling the head and risk tables independently rather than jointly leaves nearly a full LongBench point on the table.

Key Results

Evaluated across four 7B–8B backbones (LLaMA-3, Qwen2, Mistral, InternLM-2.5) plus Qwen3-8B:

  • LongBench SOTA: At a 512-token budget, CompilerKV beats the strongest prefill-only baselines across all four primary backbones by +1.67 points on average (42.31 vs. FullKV's 42.14). On Qwen3-8B, it beats offline head-typing predecessor DuoAttention by +9.97 points (49.67 vs. 39.70).
  • Thriving under pressure: Keeping a strict 1.56% cache ratio (scaling from 256 cached tokens at 16k up to 2048 at 128k), CompilerKV scores ~73 on 128k RULER (FullKV: ~79, SnapKV: ~38). On 32k NIAH, it hits 0.89 accuracy vs. SnapKV’s 0.42.
  • Real-world serving speedups: On a single A100-80GB GPU at 32k context (98.44% compression), CompilerKV delivers 2.45$\times$ decoding throughput and enables batch-16 serving (with 8k output) where FullKV crashes with Out-Of-Memory beyond batch 8.

Limitations and Future Work

  • Upfront compilation cost: Compiling the tables is not free—it takes ~20 GPU-hours for an 8B model and ~169 GPU-hours for a 72B model (mostly spent running forward passes to collect statistics and rewards). However, this is a one-time offline cost amortized over deployment.
  • Serving engine constraints: The current SGLang integration requires disabling Radix Cache, chunked prefill, and CUDA Graphs to handle one-shot KV block remapping.
  • Future directions: The authors plan to explore streaming updates to the compiled tables during deployment and expand testing to broader model architecture families.

Summary updated

Abstract

Prefill-only KV compression freezes a token subset at the end of prefill and decodes from it without further eviction. The retention decision is therefore irreversible, yet existing methods estimate the corrective signals it relies on, per-head reliability and prompt-level compression sensitivity, online from a single noisy prompt. We argue this is the wrong statistical unit: these signals exhibit far higher cross-prompt regularity than within-prompt signal-to-noise. We introduce CompilerKV, a KV-retention policy whose corrective tables are compiled offline from a calibration corpus, reducing online correction after the standard observation-window scan to $O(1)$ lookups plus a budget clamp. We find that compiled retention tables behave as portable architectural priors: rankings transfer across disjoint corpora on four backbones (mean Spearman $\bar\rho{=}0.90$), and direct model-to-model table transfer costs only $0.4$--$0.8$ LongBench points on average. At a 512-token budget, CompilerKV attains compressed-SOTA on all four backbones, improving over the strongest prefill-only baseline by $+1.67$ points on average (task-bootstrap 95\% CI $[+1.08,+2.37]$). Pressure regimes amplify the gap: under a fixed $512/32k$ cache ratio, \textsc{CompilerKV} remains the strongest compressed method through 128k RULER ($\sim 73$ vs. FullKV $\sim 79$, SnapKV $\sim 38$); on 32k NIAH it reaches $0.89$ vs. SnapKV $0.42$; and at 32k input, retaining only $1.56\%$ of the prefill KV, batch-16 serving remains feasible where FullKV is OOM. Code is available at https://github.com/Chengzhi-W/CompilerKV.
BibTeX
@inproceedings{yang2026compilerkv,
  author = {Ning Yang and Chengzhi Wang and Yibo Liu and Baoliang Tian and Haijun Zhang},
  title = {{CompilerKV: Risk-Adaptive KV Cache Compression via Offline Experience Compilation}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=MYIR2frWUj},
}
Figure