Skip to content

KIVI

At a glance

KIVI: the KV cache in low-bit codes, keys quantized per channel and values per token.

Registered name Family Saves Lossless Trainable Configuration
kivi KV-quantization KV memory no no KIVIConfig

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

KIVI (Liu et al., 2024) quantizes the KV cache to 2 or 4 bits without calibration data or training. Keys have a few channels of large magnitude, so they are quantized per channel: every group of group_size consecutive tokens gets one scale and one zero point per channel. Values are quantized per token, in groups of group_size channels. The most recent tokens stay in full precision. Keys are quantized in whole blocks of residual_length tokens once a block is complete, and values once a token is more than residual_length tokens old, so with l cached tokens floor(l / R) * R keys and max(0, l - R) values are quantized. The method is lossy and trains nothing.

economize stores the quantized entries as packed codes (bits / 8 bytes per element) with an fp16 scale and zero point per group, and the recent entries in a short full-precision ring of residual_length + headroom slots. No dense buffer stays allocated for the quantized layers, so with bf16 entries the cache holds about bits / 16 + 2 / group_size of the plain cache's bytes. The economize attention kernel reads the codes directly; sdpa and eager read a dense copy of one layer at a time.

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 KV-cache technique matters once the prompt is long. This prompt puts twenty worked GSM8K problems in front of the question, and the plain model's greedy output on it is the reference:

text = "\n\n".join(texts[:20]) + "\n\n" + tokenizer.decode(ids[0]) + "\n"
prompt = tokenizer(text, return_tensors="pt").input_ids.cuda()
print(prompt.shape[1])                  # prompt tokens

plain = economize.apply(base)
reference = plain.decode(prompt[0], 64).tokens
plain.detach()

economize.apply with a KIVIConfig quantizes the cache of every layer. The technique's cost_summary adds the KV bytes held at the last exact pass to the decoder's cost summary:

from economize.techniques.kv_quant import KIVIConfig

model = economize.apply(base, KIVIConfig(bits=2))
result = model.decode(prompt[0], 64)
print(tokenizer.decode(result.tokens))

stats = model.techniques["kivi"].cost_summary(result)
print(stats["kv_bytes"], stats["kv_bytes_full"])     # modelled KV bytes, packed and in the model's dtype
print(stats["kv_compression"])                       # kv_bytes_full / kv_bytes
print(stats["kv_bytes_allocated_batch"])             # measured bytes the cache held (whole batch)
print((result.tokens == reference).float().mean().item())   # agreement with the plain model
model.detach()

decode does not stop at the end-of-sequence token, so the two outputs have the same length and agree token by token until the first position where the quantization error changes the greedy choice.

Options

Four bits keep more of the base model's output at a lower compression. A longer residual keeps more recent tokens exact, and a residual at least as long as the whole sequence quantizes nothing:

for config in (KIVIConfig(bits=4), KIVIConfig(bits=2, residual_length=256), KIVIConfig(bits=2, group_size=64)):
    model = economize.apply(base, config)
    result = model.decode(prompt[0], 64)
    stats = model.techniques["kivi"].cost_summary(result)
    print(config, stats["kv_compression"], (result.tokens == reference).float().mean().item())
    model.detach()

residual_length must be a multiple of group_size. layers=(...) restricts quantization to some layers (1-indexed), for example to keep the first layers exact. headroom (256 by default) is the room the ring keeps for the uncommitted tokens of one cycle: a speculative cycle that writes more tokens than that between two exact passes is refused, and a larger headroom costs 2 * headroom * head_dim full-precision values per KV head and layer.

Speculative decoding

New entries are quantized at the start of each exact pass, and draft K/V stay in full precision until they are verified. Under speculative decoding a drafter spaces the exact passes by the number of accepted tokens, so the output with KIVI depends on the cycle length and on the acceptance. At cycle_length=1 it equals the output above.

Combining with other techniques

KIVI is the model's one KV quantizer, so it refuses kv_fp8. It also refuses the eviction techniques (kv_evict, kv_evict_fused, duo_attention). Eviction stores the layers it covers in buffers of its own, entry by entry, and over kv_fp8 those buffers hold each entry's fp8 code. KIVI quantizes keys per channel over groups of tokens and keeps the newest tokens in a full-precision residual, so no single entry has a code of its own that eviction could move or drop. It composes with every drafter.

from economize.techniques.kv_evict import KVEvictConfig

print(economize.compatible(KIVIConfig(), KVEvictConfig(method="snapkv")))   # False
print(economize.incompatibility("kivi", "kv_evict"))

Serving

vLLM runs KIVI through economize's custom attention backend. Its pages hold only the packed codes of every token with their scales and zero points, so vLLM sizes its KV cache from the compact cell and fits about 16 / bits times as many tokens as in a 16-bit cache. The residual_length newest tokens stay in full precision in a small per-request buffer outside the pages, and attention dequantizes the codes as it reads them. Speculative decoding works with drafters that reuse the target's own layers (early exit, layer skip); the backend refuses a layer subset, sliding-window layers and drafters with attention layers of their own, such as EAGLE-3:

print(economize.backend_support("kivi")["vllm"])

Configuration

KIVIConfig dataclass

KIVIConfig(bits: int = 2, group_size: int = 32, residual_length: int = 128, layers: tuple[int, ...] = (), storage: str | None = None, headroom: int = 256)

KIVI KV-cache quantization.

Attributes:

Name Type Description
bits int

Bits per quantized element (2 or 4 in the paper; 8 for reference).

group_size int

Tokens per key group (per channel) and channels per value group (per token). The paper uses 32.

residual_length int

Most recent tokens kept in full precision (R, a multiple of group_size; 128 in the paper). A residual at least as long as the generation quantizes nothing, which is exact.

layers tuple[int, ...]

1-indexed layers whose cache is quantized (empty: every layer).

storage str | None

How the cache stores its entries (:data:~.storage.KIVI_STORAGES); None (the default) is "packed": packed codes and a full-precision ring and no dense buffer, so the memory really shrinks.

headroom int

Ring slots of the packed storage beyond residual_length: room for the uncommitted tokens of one cycle (draft steps and a verify pass). Passes of at most this many queries read the packed codes directly in an attention kernel that supports them.

kivi_storage property

kivi_storage: str

The storage in use: :attr:storage, else "packed".

References

  • Liu, Z., Yuan, J., Jin, H., Zhong, S., Xu, Z., Braverman, V., Chen, B., & Hu, X. (2024). KIVI: A tuning-free asymmetric 2bit quantization for KV cache. In International Conference on Machine Learning. https://doi.org/10.48550/arXiv.2402.02750