Skip to content

Compacted KV-cache eviction

At a glance

One-shot KV eviction decoded on a fused kernel over compact pools (see FusedKVEvictConfig).

Registered name Family Saves Lossless Trainable Configuration
kv_evict_fused KV-eviction KV memory or latency no no FusedKVEvictConfig

Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: no · trtllm: no · vllm: no

kv_evict_fused runs the prompt-time eviction policies of kv_evict, SnapKV (Li et al., 2024), PyramidKV (Cai et al., 2024) and the prompt-time form of H2O (Zhang et al., 2023), and changes how attention reads the result. These three policies select once, right after the prompt pass, and never change the selection. Every covered layer stores its K/V in a pool per row and KV head that holds only the kept prompt entries and the generated ones, and the pool is reallocated to that size at the end of the prompt pass, so the evicted entries free their memory. economize's attention kernel attends over the pool under a per-head mask, and a decoding step reads kept + generated entries per head instead of the whole cache.

The selection, the keep mask, the storage and the byte accounting are those of kv_evict with the same fields, so the greedy tokens equal those of kv_evict up to the summation order of the softmax. The pools decode eagerly, without CUDA graphs. Prefer the technique on a CUDA GPU with long prompts and a prompt-time policy, and kv_evict for StreamingLLM, the decoding-time form of H2O and other attention implementations.

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

The compact cache is read by economize's attention kernel. economize.attention.install() registers it with transformers, and the model selects it by name, at load time with attn_implementation="economize" or afterwards:

import economize.attention

economize.attention.install()
base.set_attn_implementation("economize")

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()

FusedKVEvictConfig takes the fields of KVEvictConfig, with SnapKV as the default method:

from economize.techniques.kv_evict_fused import FusedKVEvictConfig

model = economize.apply(base, FusedKVEvictConfig(method="snapkv", heavy=480, observation_window=32))
economize.attention.kernel_usage(reset=True)
result = model.decode(prompt[0], 64)

stats = model.techniques["kv_evict_fused"].cost_summary(result)
print(stats["kv_bytes"], stats["kv_bytes_full"], stats["kv_compression"])
print((result.tokens == reference).float().mean().item())   # agreement with the plain model
print(economize.attention.usage_summary())                  # which attention path each call took
model.detach()

On a GPU the decoding steps run on the kernel path over the pools. On a CPU the kernel falls back to sdpa over the same pools, so the tokens and the byte counts equal those of kv_evict.

Methods that keep evicting while decoding are refused when the configuration is built, and the technique checks the attention implementation when it is applied:

try:
    FusedKVEvictConfig(method="streaming")
except economize.ConfigError as error:
    print(error)

base.set_attn_implementation("sdpa")
try:
    economize.apply(base, FusedKVEvictConfig())
except economize.IncompatibleTechniquesError as error:
    print(error)
base.set_attn_implementation("economize")

Combining with other techniques

kv_evict_fused is the model's eviction technique, so it refuses kv_evict and DuoAttention. The pools take the covered layers out of the inner cache. Over kv_fp8 they hold its fp8 codes (fp8 bytes plus, under scale="token", each entry's fp32 scale), and the kernel receives the decoded keys and values of the pools, so the pools take the fp8 size. KIVI quantizes keys per channel over groups of tokens, which a pool of single entries cannot hold, and kivi_fused and kv_fp8_fused hand their own buffers to their kernels, so these three are refused. Quest reads its pages by position in the full cache and is refused too, as are the trainable layer copies of dmtd and of jump and early_exit with adaptation="full", which write the cache past the layers the pools hook. MInference changes only the prefill and composes:

from economize.core.compatibility import incompatibility
from economize.techniques.kv_quant import FP8KVConfig, KIVIConfig
from economize.techniques.minference import MInferenceConfig

print(incompatibility(FusedKVEvictConfig(), KIVIConfig()))
print(economize.compatible(FusedKVEvictConfig(), FP8KVConfig(scale="token")))   # True
print(economize.compatible(FusedKVEvictConfig(), MInferenceConfig()))           # True

Serving

The policies keep a different set of entries per KV head, which the paged caches of vLLM, SGLang and TensorRT-LLM cannot hold, so the technique runs in transformers only:

print(economize.backend_support("kv_evict_fused")["vllm"].detail)

Configuration

FusedKVEvictConfig dataclass

FusedKVEvictConfig(method: str = 'snapkv', 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 eviction at prefill ("snapkv", "pyramidkv" or "h2o_prefill") on a registered fused attention kernel such as "economize".

The fields are those of :class:~economize.techniques.kv_evict.KVEvictConfig; method must name a method that selects once (:attr:~economize.techniques.kv_evict.EvictionMethod.selects_once), and the storage is always the compact pools of :class:~economize.techniques.kv_evict.CompactEvictionCache.

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
  • 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