Skip to content

KIVI with a fused attention kernel

At a glance

KIVI quantization of the KV cache, attended over as packed codes (see FusedKIVIConfig).

Registered name Family Saves Lossless Trainable Configuration
kivi_fused KV-quantization KV memory or latency no no FusedKIVIConfig

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

kivi_fused is KIVI (Liu et al., 2024) with the read path of the paper's kernels. The quantization is the same: keys per channel and values per token in groups of group_size, the last residual_length tokens in full precision, 2, 4 or 8 bits. The storage is that of kivi: the packed integer codes with their fp16 scales and zero points and a short full-precision ring of the recent entries, with no dense buffer for the quantized layers. kivi_fused requires economize's attention kernel, which reads the codes of the quantized entries and dequantizes them in registers, and reads the ring only for the full-precision residual. A decoding step therefore moves about as many bytes as the quantized cache holds. The output is the same as that of kivi, bit for bit. Like kivi the method is lossy and trains nothing.

kivi reads the same codes when the model runs the economize kernel and a dense copy of one layer at a time under sdpa or eager. kivi_fused differs only in refusing the attention implementations that cannot read the codes, so prefer it when a recipe must decode on the kernel path and kivi on other devices and 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 kernel is an attention implementation registered with transformers. economize.attention.install() registers it, and the model selects it by name, either at load time with attn_implementation="economize" or afterwards:

import economize.attention

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

A long prompt shows the effect. 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()

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

FusedKIVIConfig takes the fields of KIVIConfig:

from economize.techniques.kv_kivi_fused import FusedKIVIConfig

model = economize.apply(base, FusedKIVIConfig(bits=2))
economize.attention.kernel_usage(reset=True)
result = model.decode(prompt[0], 64)

stats = model.techniques["kivi_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, usage_summary()["calls"] counts the decoding steps that read the packed codes under the path kernel_kivi. On a CPU every call falls back to sdpa over a transient dense copy of the dequantized entries, so the tokens do not change.

The technique checks the attention implementation when it is applied. On a model that runs sdpa or eager it raises an IncompatibleTechniquesError that names the implementations it accepts:

base.set_attn_implementation("sdpa")
try:
    economize.apply(base, FusedKIVIConfig(bits=2))
except economize.IncompatibleTechniquesError as error:
    print(error)
base.set_attn_implementation("economize")

Combining with other techniques

kivi_fused composes with MInference and with every drafter. It refuses the other KV quantizers, the eviction techniques (kv_evict, kv_evict_fused, duo_attention) and quest. Like kivi it quantizes keys per channel over groups of tokens, so no single entry has a code that an eviction buffer could hold, and its kernel reads its own packed buffers. economize.core.compatibility.incompatibility gives the reason:

from economize.core.compatibility import incompatibility
from economize.techniques.kv_evict import KVEvictConfig
from economize.techniques.quest import QuestConfig

print(economize.compatible(FusedKIVIConfig(), KVEvictConfig(method="snapkv")))   # False
print(incompatibility(FusedKIVIConfig(), QuestConfig()))

Serving

vLLM serves kivi_fused exactly like kivi, through economize's custom attention backend: the pages hold only the packed codes, scales and zero points, the newest tokens live in full precision outside the pages, and the paged kernel dequantizes the codes in registers on every pass (see the kivi tutorial for what it refuses):

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

Configuration

FusedKIVIConfig dataclass

FusedKIVIConfig(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 whose packed codes the attention kernel reads.

Attributes:

Name Type Description
bits int

Bits per quantized element (2, 4 or 8).

group_size int

Tokens per key group (per channel) and channels per value group (per token).

residual_length int

Most recent tokens kept in full precision (a multiple of group_size).

layers tuple[int, ...]

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

headroom int

Ring slots beyond residual_length for the uncommitted tokens of one cycle.

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