KV-cache eviction: StreamingLLM, H2O, SnapKV and PyramidKV¶
At a glance
KV-cache eviction with StreamingLLM, H2O or SnapKV: committed entries outside the kept set are forgotten.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
kv_evict |
KV-eviction | KV memory or compute | no | no | KVEvictConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: untested · onnx: no · sglang: no · trtllm: untested · vllm: real
kv_evict keeps a fixed budget of KV-cache entries per layer and KV head and drops the rest. Five policies choose
the entries. StreamingLLM (Xiao et al., 2024) keeps the first sinks entries, which attract much of the attention
of every query, and a window of the last recent entries. H2O (Zhang et al., 2023) keeps the recent window and the
heavy older entries with the largest attention accumulated over all queries so far, and evicts again after every
exact pass. h2o_prefill applies the H2O rule once to the prompt, as the KVCache-Factory benchmarks run it. SnapKV
(Li et al., 2024) compresses only the prompt: the last observation_window prompt queries score every earlier
prompt entry, the scores are pooled over neighbouring slots, and the heavy best entries of each KV head are kept
together with the window. PyramidKV (Cai et al., 2024) makes the same selection with a budget that shrinks linearly
from the bottom layer to the top, at the same total. Every policy is lossy and trains nothing.
Every policy frees the evicted entries. StreamingLLM keeps the covered layers' K/V in buffers of
sinks + recent + headroom + 1 slots instead of the dense cache: the sinks, a ring of recent entries that wraps in
place, and one slot that absorbs the writes of padding. The headroom (default 256) holds the uncommitted entries of
a pass, so a verify pass of a drafter, a tree or a prompt chunk must fit into it, and the whole prompt must fit into
recent + headroom when it is fed in chunks; a pass that would overwrite entries it still attends to raises a
ConfigError that names the headroom. These buffers are CUDA-graph safe.
The score-based policies keep different entries in every KV head, so each covered layer stores a pool per KV head that holds only the kept entries and the new ones, together with the position of every pool column. The pool is compacted when a pass does not fit, and reallocated to the kept entries when an eviction leaves most of it empty (SnapKV after the prompt). The policies' keep masks and scores stay per position, five bytes per position and KV head, and the pools come in blocks of 64 columns with an eight-byte position per column, so the saving shows on long caches. These pools decode without CUDA graphs.
Positions are never reassigned, so both storages produce the tokens of a dense cache that masks the evicted entries
(tests/techniques/test_kv_evict.py and tests/techniques/test_kv_evict_compact.py compare them with such a
reference for plain decoding, drafting, trees, batching and chunked prefill). Eviction needs the cache layers for
itself, so it is refused next to KIVI, the fused KV quantizers or Quest, under an attention implementation other than sdpa,
eager and economize's kernel, when layers share or copy their KV, and on the draft path of draft_with, whose
verifying model reads every entry. The byte accounting counts the stored entries.
Compacted eviction runs the prompt-time policies on economize's attention kernel.
Setup¶
Every tutorial starts from the same model and prompt:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import economize
device = "cuda" if torch.cuda.is_available() else "cpu"
base = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2.5-0.5B", dtype=torch.bfloat16, device_map=device)
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B")
ids = tokenizer("Natalia sold clips to 48 of her friends in April, and then she sold half as many clips in May. "
"How many clips did Natalia sell altogether?", return_tensors="pt").input_ids.to(device)
Training data is a flat file of uint32 token ids, the format of nanoGPT-style pretraining shards, and calibration
data is a [N, S] tensor of token ids. Both are made here from GSM8K:
import numpy as np
from datasets import load_dataset
texts = [f"{row['question']}\n{row['answer']}" for row in load_dataset("openai/gsm8k", "main", split="train")]
tokens = np.concatenate([tokenizer(t + tokenizer.eos_token).input_ids for t in texts]).astype(np.uint32)
tokens[: len(tokens) * 9 // 10].tofile("train.bin")
tokens[len(tokens) * 9 // 10 :].tofile("val.bin")
calibration = torch.from_numpy(tokens[: 128 * 2048].astype(np.int64)).view(128, 2048)
Quick start¶
A long prompt and the plain model's greedy output on it as the reference:
text = "\n\n".join(texts[:20]) + "\n\n" + tokenizer.decode(ids[0]) + "\n"
prompt = tokenizer(text, return_tensors="pt").input_ids.cuda()
plain = economize.apply(base)
reference = plain.decode(prompt[0], 64).tokens
plain.detach()
The four policies at the same budget of 512 entries per layer and KV head:
from economize.techniques.kv_evict import KVEvictConfig
budget = 512
configs = {
"StreamingLLM": KVEvictConfig(method="streaming", recent=budget - 4), # 4 sinks by default
"H2O": KVEvictConfig(method="h2o", recent=budget // 2, heavy=budget // 2),
"SnapKV": KVEvictConfig(method="snapkv", heavy=budget - 32), # plus a window of 32
"PyramidKV": KVEvictConfig(method="pyramidkv", heavy=budget - 8, observation_window=8),
}
for name, config in configs.items():
model = economize.apply(base, config)
result = model.decode(prompt[0], 64)
stats = model.techniques["kv_evict"].cost_summary(result)
agreement = (result.tokens == reference).float().mean().item()
print(name, stats["kv_bytes"], stats["kv_compression"], agreement)
model.detach()
kv_bytes models the cache kept at the last exact pass and kv_compression its ratio to the full cache;
kv_bytes_allocated_batch measures the bytes the cache really held. The agreement is the fraction of the 64 tokens
that equal the plain model's.
StreamingLLM and H2O evict before every exact pass, so their cache stays at the budget plus the tokens of one cycle.
SnapKV, PyramidKV and h2o_prefill compress the prompt once and keep every generated entry, so their cache grows by
one entry per token after the prefill. Each policy reads only some of the fields, and a field the chosen policy
ignores must keep its default, so that a configuration states what it does. StreamingLLM defaults to 4 sinks and the
other policies to none.
Attention implementation¶
H2O, SnapKV and PyramidKV select by attention probabilities, which sdpa does not return. Under sdpa economize
recomputes them in fp32 for the queries of exact passes, and under eager it reads the returned weights. Other
attention implementations are refused for these methods. StreamingLLM needs no scores and runs under any of them.
Speculative decoding¶
SnapKV, PyramidKV and h2o_prefill select once from the prompt, so their output does not depend on the cycle length
of a drafter. StreamingLLM and H2O evict at exact-pass boundaries, which a drafter spaces by the number of accepted
tokens, so their output depends on the cycle. StreamingLLM also trims the cache to the window when the prompt pass
ends, so the draft steps after the prompt already see only the sinks and the window. At cycle_length=1 all of them equal the output above.
Combining with other techniques¶
A model has at most one eviction technique, so kv_evict refuses kv_evict_fused and DuoAttention. Over kv_fp8
the ring or the pools store the fp8 cache's codes: each entry's fp8 bytes followed, under scale="token", by the
four bytes of its fp32 scale (an entry codec that kv_fp8 provides). Attention reads them decoded exactly as kv_fp8
alone would, the kept entries take the fp8 size, and the reported bytes count them at that size. The combination
decodes eagerly, without CUDA graphs. KIVI quantizes keys per channel over groups of tokens, so no single entry has a
code of its own that the ring could move or a pool could keep, and kivi_fused and kv_fp8_fused hand their own
buffers to their kernels: these three are refused, and Quest too, since it reads pages by position in the full cache.
kv_evict composes with kv_fp8, MInference and speculative decoding:
from economize.core.compatibility import incompatibility
from economize.techniques.kv_quant import FP8KVConfig, KIVIConfig
from economize.techniques.minference import MInferenceConfig
print(incompatibility(KVEvictConfig(method="snapkv"), KIVIConfig(bits=4)))
print(economize.compatible(KVEvictConfig(method="snapkv"), FP8KVConfig(scale="token"))) # True
print(economize.compatible(KVEvictConfig(method="snapkv"), MInferenceConfig())) # True
Serving¶
vLLM serves StreamingLLM through economize's custom attention backend: decoding queries read the sink pages and the window, and the pages in between are freed once a request decodes. TensorRT-LLM and MLX serve StreamingLLM natively. The score-based policies select different entries per KV head, which the engines' paged caches cannot express:
from economize.backends.vllm import serving
model = economize.apply(base, KVEvictConfig(method="streaming", recent=1020))
plan = serving.to_vllm(model, "out/qwen-streaming")
print(plan.engine)
llm = plan.llm()
Configuration¶
KVEvictConfig
dataclass
¶
KVEvictConfig(method: str = 'streaming', sinks: int | None = None, recent: int = 256, heavy: int = 256, observation_window: int = 32, kernel_size: int = 7, pooling: str = 'max', beta: int = 20, layers: tuple[int, ...] = (), storage: str | None = None, headroom: int = 256)
KV-cache eviction.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
Name in :data: |
sinks |
int | None
|
First entries of every row that are never evicted ( |
recent |
int
|
Most recent committed entries that are never evicted ( |
heavy |
int
|
Older entries kept per KV head by score: H2O's heavy hitters, or the prompt entries SnapKV selects.
An absolute number of entries; SnapKV's budget excludes the observation window (the reference's
|
observation_window |
int
|
SnapKV: last prompt tokens whose queries score the prompt (always kept). 32 as in SnapKV; PyramidKV's per-layer budgets use 8. |
kernel_size |
int
|
SnapKV: width of the pooling over neighbouring slots (odd; 1 disables pooling). |
pooling |
str
|
SnapKV: |
beta |
int
|
PyramidKV: ratio of the bottom layer's prompt budget to the top layer's (about |
layers |
tuple[int, ...]
|
1-indexed layers whose cache is evicted (empty: every layer). |
storage |
str | None
|
Name in :data: |
headroom |
int
|
Positional methods: ring slots beyond |
The method options (:attr:method_options) that the chosen method does not read
(:attr:EvictionMethod.options <economize.techniques.kv_evict.EvictionMethod.options>) must keep their defaults.
References¶
- Cai, Z., Zhang, Y., Gao, B., Liu, Y., Li, Y., Liu, T., Lu, K., Xiong, W., Dong, Y., Hu, J., & Xiao, W. (2024). PyramidKV: Dynamic KV cache compression based on pyramidal information funneling (arXiv:2406.02069). arXiv. https://doi.org/10.48550/arXiv.2406.02069
- Li, Y., Huang, Y., Yang, B., Venkitesh, B., Locatelli, A., Ye, H., Cai, T., Lewis, P., & Chen, D. (2024). SnapKV: LLM knows what you are looking for before generation. In Advances in Neural Information Processing Systems. https://doi.org/10.48550/arXiv.2404.14469
- Xiao, G., Tian, Y., Chen, B., Han, S., & Lewis, M. (2024). Efficient streaming language models with attention sinks. In International Conference on Learning Representations. https://doi.org/10.48550/arXiv.2309.17453
- Zhang, Z., Sheng, Y., Zhou, T., Chen, T., Zheng, L., Cai, R., Song, Z., Tian, Y., Ré, C., Barrett, C., Wang, Z., & Chen, B. (2023). H2O: Heavy-hitter oracle for efficient generative inference of large language models. In Advances in Neural Information Processing Systems. https://doi.org/10.48550/arXiv.2306.14048