FP8 KV cache¶
At a glance
KV cache in 8-bit floats (see FP8KVConfig). Training-free; no parameters.
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
kv_fp8 |
KV-quantization | KV memory | no | no | FP8KVConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: real · trtllm: untested · vllm: real
kv_fp8 stores every key and value entry as an 8-bit float, the fp8 cache dtype of vLLM and TensorRT-LLM, in one
of the two formats of Micikevicius et al. (2022): e4m3 (4 exponent and 3 mantissa bits, the default) or e5m2
(a wider range with 2 mantissa bits). Entries are cast to fp8 when they are written and cast back to the model's
dtype when attention reads them. The cache holds the raw bytes, so the memory it reports is the memory it uses:
one byte per element, half of a bf16 cache. Three scaling rules are available. scale="none" casts directly and
saturates at the format's maximum, as vLLM does with unit scales. scale="token" divides every token's head vector
by its absolute maximum first, at the cost of one fp32 scale per token and head. scale="tensor" divides a layer's
keys and its values by one static scale each, calibrated as the layer's absolute maximum on calibration data. The
method is lossy and trains nothing.
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 makes the cache the larger part of the memory a request needs. 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()
from economize.techniques.kv_quant import FP8KVConfig
model = economize.apply(base, FP8KVConfig())
result = model.decode(prompt[0], 64)
print(tokenizer.decode(result.tokens))
stats = model.techniques["kv_fp8"].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
model.detach()
Every write is converted, drafts included, so under speculative decoding the output does not depend on the cycle length.
Scales and formats¶
Per-token scales keep outliers representable. e5m2 trades precision for range:
for config in (FP8KVConfig(scale="token"), FP8KVConfig(format="e5m2")):
model = economize.apply(base, config)
result = model.decode(prompt[0], 64)
print(config, (result.tokens == reference).float().mean().item())
model.detach()
Calibration¶
scale="tensor" computes its scales when it is applied, from the calibration batches passed to economize.apply:
model = economize.apply(base, FP8KVConfig(scale="tensor"), calibration=calibration)
result = model.decode(prompt[0], 64)
print((result.tokens == reference).float().mean().item())
Saving and loading¶
The calibrated scales are saved with the technique, so a loaded model skips the calibration:
model.save_pretrained("kv_fp8_tensor")
model.detach()
model = economize.load(base, "kv_fp8_tensor")
Combining with other techniques¶
kv_fp8 is the model's one KV quantizer, so it refuses kivi. It composes with the eviction techniques
(kv_evict, kv_evict_fused, DuoAttention), Quest, MInference, weight quantization and every drafter. The eviction
techniques store the layers they cover in buffers of their own, and over kv_fp8 those buffers hold each entry's fp8
bytes followed, under scale="token", by the four bytes of its fp32 scale. kv_fp8 hands them this format as an
entry codec, so an entry reads back exactly as it does from the fp8 cache alone and the kept entries take the fp8
size (D or D + 4 bytes per key instead of 2D in bfloat16). The combination decodes eagerly, without CUDA graphs:
from economize.techniques.kv_evict import KVEvictConfig
from economize.techniques.quant import QuantConfig
print(economize.compatible(FP8KVConfig(), KVEvictConfig(method="streaming"))) # True
print(economize.compatible(FP8KVConfig(), QuantConfig(format="int8"))) # True
Serving¶
vLLM, SGLang and TensorRT-LLM have native fp8 caches. The vLLM export maps the configuration onto kv_cache_dtype
(fp8_e4m3, fp8_e5m2, or fp8_per_token_head for scale="token"), writes calibrated scales as the k_scale and
v_scale tensors of an llm-compressor checkpoint, and turns layers=(...) into kv_cache_dtype_skip_layers:
from economize.backends.vllm import serving
plan = serving.to_vllm(model, "out/qwen-kv-fp8")
print(plan.engine)
llm = plan.llm()
TensorRT-LLM accepts only e4m3 with scale="none".
Configuration¶
FP8KVConfig
dataclass
¶
FP8KVConfig(format: str = 'e4m3', scale: str = 'none', layers: tuple[int, ...] = ())
FP8 KV cache.
Attributes:
| Name | Type | Description |
|---|---|---|
format |
str
|
|
scale |
str
|
|
layers |
tuple[int, ...]
|
1-indexed layers whose cache is stored in fp8 (empty: every layer). |
References¶
- Micikevicius, P., Stosic, D., Burgess, N., Cornea, M., Dubey, P., Grisenthwaite, R., Ha, S., Heinecke, A., Judd, P., Kamalu, J., Mellempudi, N., Oberman, S., Shoeybi, M., Siu, M., & Wu, H. (2022). FP8 formats for deep learning (arXiv:2209.05433). arXiv. https://doi.org/10.48550/arXiv.2209.05433