Why KV cache quantization differs from weight quantization
When a model runs in BF16, each token appends two 16-bit tensors per attention layer to the KV cache. Unlike model weights, which are static across requests and can be calibrated once offline, keys and values are generated dynamically for every incoming token and remain bounded in size only by max_model_len and concurrent batch depth.
| Format | Bytes per element | Scaling and calibration behavior | Primary trade-off |
|---|---|---|---|
| BF16 / FP16 | 2 bytes | Unquantized reference baseline | Highest memory footprint and decode HBM traffic |
| FP8 E4M3 | 1 byte | Static k_scale / v_scale (or dynamic per-tensor/head scale) | 2x capacity; needs calibration to avoid clipping above 448 |
| FP8 E5M2 | 1 byte | Optional scale; wide exponent range up to 57,344 | Lower mantissa precision than E4M3; safer when uncalibrated |
| INT8 / INT4 (KIVI, KVQuant) | 1 byte or 0.5 bytes + scales | Asymmetric per-channel keys and per-token values | Preserves accuracy at 4 bits, with extra kernel and metadata overhead |
Keys and values also have distinct numerical shapes. KIVI and KVQuant showed that key tensors exhibit persistent outlier magnitudes along fixed feature channels across tokens, while value tensors vary more across token positions without strong channel spikes. That asymmetry is why naive per-tensor quantization hurts keys far more than values.
BF16 KV cache versus calibrated FP8 E4M3 KV cache
- Prefill & appendWrite unquantized 16-bit K and V vectors into paged blocks
- Capacity ceilingEach 16K sequence consumes 5.00 GiB on a 70B GQA model
- Decode attention readStream 2x bytes from HBM on every token step
- Scale & cast on writeApply calibrated k_scale / v_scale before storing FP8 pages
- 2x sequence capacitySame 16K sequence drops to 2.50 GiB, doubling concurrency
- Native FP8 attentionHalves KV HBM reads on Hopper, Ada, and Blackwell GPUs
Calculate KV capacity gains and key outlier error in Python
Before toggling flags in production, quantify both sides of the trade-off: how many extra sequences fit in your VRAM budget, how many gigabytes per decode step leave HBM, and how much quantization error a single outlier channel introduces under per-tensor versus per-channel scaling. Run this standalone script with Python 3.
import random
# Part 1: Llama 3.1 70B KV capacity & decode bandwidth (80 layers, 8 KV heads, d_head=128)
layers, kv_heads, head_dim = 80, 8, 128
seq_len, kv_pool_gib, batch = 16384, 32.0, 16
elems_per_tok = 2 * layers * kv_heads * head_dim
print("Llama 3.1 70B KV cache sizing (16K context, 32 GiB pool, batch=16):")
for name, bytes_per_elem in [("BF16 (16-bit)", 2.0), ("FP8 / INT8 (8-bit)", 1.0), ("INT4 payload (4-bit)", 0.5)]:
seq_gib = (elems_per_tok * seq_len * bytes_per_elem) / 2**30
max_seqs = int(kv_pool_gib // seq_gib)
step_read_gib = (elems_per_tok * seq_len * batch * bytes_per_elem) / 2**30
print(f" {name:<21} -> {seq_gib:5.2f} GiB/seq | max {max_seqs:2d} seqs | {step_read_gib:6.2f} GiB/step")
# Part 2: Per-tensor vs per-channel symmetric INT8 quantization on a key matrix with one outlier channel
rng = random.Random(42)
tokens, dim = 64, 128
keys = [[(rng.uniform(-32.0, 32.0) if c == 0 else rng.uniform(-1.2, 1.2)) for c in range(dim)] for _ in range(tokens)]
def quant_mse(matrix, per_channel):
if not per_channel:
scale = max(abs(v) for row in matrix for v in row) / 127.0
scales = [scale] * len(matrix[0])
else:
scales = [max(abs(row[c]) for row in matrix) / 127.0 for c in range(len(matrix[0]))]
sq_err = 0.0
for row in matrix:
for c, v in enumerate(row):
q = max(-127, min(127, round(v / scales[c])))
sq_err += (v - q * scales[c]) ** 2
return sq_err / (len(matrix) * len(matrix[0]))
print("\nSynthetic Key MSE (outlier channel 0 in [-32, 32], others in [-1.2, 1.2]):")
print(f" Per-tensor INT8 MSE : {quant_mse(keys, False):.6f}")
print(f" Per-channel INT8 MSE: {quant_mse(keys, True):.6f}")Llama 3.1 70B KV cache sizing (16K context, 32 GiB pool, batch=16):
BF16 (16-bit) -> 5.00 GiB/seq | max 6 seqs | 80.00 GiB/step
FP8 / INT8 (8-bit) -> 2.50 GiB/seq | max 12 seqs | 40.00 GiB/step
INT4 payload (4-bit) -> 1.25 GiB/seq | max 25 seqs | 20.00 GiB/step
Synthetic Key MSE (outlier channel 0 in [-32, 32], others in [-1.2, 1.2]):
Per-tensor INT8 MSE : 0.005425
Per-channel INT8 MSE: 0.000046In that illustrative matrix, one outlier channel expands the shared per-tensor scale by more than 25x and raises mean squared error by over 100x across the remaining 127 channels. Test full-cluster concurrency for your model in our GPU memory calculator, inspect decode bandwidth saturation in the latency and roofline calculator, or implement Per-Channel INT8 Quantization and Per-Channel INT8 Dequantization in Python.
FP8 E4M3 vs. E5M2, calibration scales, and 4-bit KV schemes
Production engines standardize on 8-bit floating point (FP8) for KV storage because modern attention kernels can read FP8 pages directly without large software dequantization overhead. Choosing between E4M3 and E5M2 hinges on dynamic range and whether you calibrate scaling factors:
- FP8 E4M3 (4 exponent bits, 3 mantissa bits): Caps finite values at
448. Its extra mantissa bit preserves finer attention-score fidelity, so production runs preferE4M3paired with per-layer or per-head statick_scaleandv_scalefactors measured on representative prompts. - FP8 E5M2 (5 exponent bits, 2 mantissa bits): Extends the representable range to
57,344at the cost of coarser rounding steps. Without calibrated scales,E5M2avoids silent overflow if activation outliers spike past448, though accuracy trails calibratedE4M3on needle-in-a-haystack retrieval. - Static calibration vs. dynamic scaling: Static calibration runs a small representative dataset once offline (for example via LLM Compressor) and stores fixed scale floats alongside the checkpoint. Dynamic online scaling (such as
--calculate-kv-scalesin vLLM) computes scales on the fly per step, avoiding an offline pass at a slight runtime cost. - Sub-8-bit KV (INT4 / 2-bit): Schemes like KIVI group keys per channel and values per token with residual FP16 windows for the newest tokens, pushing compression beyond 2x when context length dominates memory.
Enable and validate KV cache quantization in vLLM and SGLang
Both vLLM KV cache quantization and SGLang server arguments expose FP8 KV flags, yet safe deployment takes four disciplined checks:
- Match dtype and scaling flags to your checkpoint. In vLLM, start with
--kv-cache-dtype fp8(orfp8_e4m3/fp8_e5m2) and supply calibrated scales or--calculate-kv-scales. In SGLang, pass--kv-cache-dtype fp8_e4m3(orfp8_e5m2) and verify the selected attention backend logs native FP8 KV support at startup. - Build reproducible launch flags. Keep weight quantization and KV quantization explicit in your serving config; test combinations safely in the vLLM & SGLang command builder.
- Run long-context and reasoning evaluations before rollout. Standard short-prompt perplexity hides KV rounding drift. Evaluate multi-turn tool use, long-context retrieval at 75% to 100% of
max_model_len, and math or code generation against the BF16 KV baseline. - Verify goodput under real concurrency. Check whether KV quantization actually lowers queue wait and
num_preemptions. If your service runs tiny batches with short prompts, weight reads already dominate step time and FP8 weights matter more than FP8 KV. Master the underlying mechanics in our free KV cache lesson, the vLLM course, and the SGLang course.
KV cache quantization FAQ
Should I quantize weights to FP8/INT4 or the KV cache first?
Quantize weights first when the model barely fits in VRAM or when small-batch decode is bound by weight bandwidth. Add FP8 KV cache once long contexts or high concurrency fill your remaining memory pool and trigger request preemptions.
Why does FP8 E4M3 need calibration when BF16 does not?
BF16 covers magnitudes up to roughly 3.39e38 with an 8-bit exponent, while FP8 E4M3 caps at 448. Without a scale factor that maps large key channels below 448, values clip or become NaN.
Does FP8 KV cache stack with prefix caching and MLA?
Yes. Paged prefix caching stores quantized blocks in the same block pool, and models using Multi-Head Latent Attention can quantize their compact 576-element latent cache to FP8 for another 2x memory reduction.
Can I mix quantized KV cache with unquantized attention during prefill?
Yes. Prefill computes the prompt attention pass in BF16/FP16 directly from active tensors and writes quantized keys and values into paged KV blocks only for subsequent decode steps and prefix reuse.
Sources and further reading
Primary documentation and research behind this guide.
- vLLM documentation: Quantized KV Cache
- SGLang documentation: Server arguments and KV cache dtype
- FP8 Formats for Deep Learning (Micikevicius et al., 2022)
- KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache (2024)
- KVQuant: Towards 10 Million Context Length LLM Inference with KV Cache Quantization (2024)
