FP8 KV cache with a fused attention kernel¶
At a glance
KV cache in 8-bit floats, decoded inside the attention kernel (see FusedFP8KVConfig).
| Registered name | Family | Saves | Lossless | Trainable | Configuration |
|---|---|---|---|---|---|
kv_fp8_fused |
KV-quantization | KV memory or latency | no | no | FusedFP8KVConfig |
Backends (default configuration): transformers: real · gguf: no · mlx: no · onnx: no · sglang: real · trtllm: no · vllm: real
kv_fp8_fused stores the KV cache as 8-bit floats exactly as kv_fp8 does with scale="none", in
the e4m3 or e5m2 format of Micikevicius et al. (2022), and changes only how attention reads it. kv_fp8 casts
the stored bytes back to the model's dtype before attention, which makes a full-precision copy of the layer's cache
at every step. kv_fp8_fused hands the fp8 buffers to economize's attention kernel, which decodes them in registers,
so a decoding step reads one byte per cached element and allocates no upcast copy. The cache holds the same bytes
as under kv_fp8, and the memory saving is real. The method is lossy, like kv_fp8, and trains nothing.
Prefer kv_fp8_fused on a CUDA GPU with unscaled fp8, where it removes the upcast from every decoding step. Prefer
kv_fp8 for per-token or calibrated per-layer scales, on other devices and with 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¶
economize.attention.install() registers the kernel with transformers, 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()
from economize.techniques.kv_fp8_fused import FusedFP8KVConfig
model = economize.apply(base, FusedFP8KVConfig())
economize.attention.kernel_usage(reset=True)
result = model.decode(prompt[0], 64)
stats = model.techniques["kv_fp8_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, and a prefill upcasts the prompt's fp8 entries once for
FlashAttention. On a CPU every call falls back to sdpa on upcast entries, so the tokens equal those of kv_fp8.
Only scale="none" is accepted, and the technique checks the attention implementation when it is applied:
try:
FusedFP8KVConfig(scale="token")
except economize.ConfigError as error:
print(error)
base.set_attn_implementation("sdpa")
try:
economize.apply(base, FusedFP8KVConfig())
except economize.IncompatibleTechniquesError as error:
print(error)
base.set_attn_implementation("economize")
Combining with other techniques¶
kv_fp8_fused is a KV quantizer, so it refuses kivi and kivi_fused. It composes with Quest, MInference, weight
quantization and every drafter. The eviction techniques (kv_evict, kv_evict_fused, duo_attention) store the
covered layers in buffers of their own, while the fused kernel reads the fp8 pages that kv_fp8_fused owns, so they
are refused as well. Eviction over an fp8 cache works with the unfused kv_fp8, whose entry codes the eviction
buffers hold:
from economize.core.compatibility import incompatibility
from economize.techniques.kv_evict import KVEvictConfig
from economize.techniques.quest import QuestConfig
print(economize.compatible(FusedFP8KVConfig(), KVEvictConfig(method="snapkv"))) # False
print(economize.compatible(FusedFP8KVConfig(), QuestConfig())) # True
print(incompatibility(FusedFP8KVConfig(), KVEvictConfig()))
Serving¶
vLLM's and SGLang's attention backends read fp8 pages directly, so the export is that of kv_fp8
(kv_cache_dtype="fp8_e4m3" or "fp8_e5m2"):
from economize.backends.vllm import serving
model = economize.apply(base, FusedFP8KVConfig())
plan = serving.to_vllm(model, "out/qwen-kv-fp8")
print(plan.engine)
llm = plan.llm()
Configuration¶
FusedFP8KVConfig
dataclass
¶
FusedFP8KVConfig(format: str = 'e4m3', scale: str = 'none', layers: tuple[int, ...] = ())
FP8 KV cache whose bytes the attention kernel reads directly.
Attributes:
| Name | Type | Description |
|---|---|---|
format |
str
|
|
scale |
str
|
Must be |
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