Memory & attention5 min read

KV cache quantization explained: FP8, INT8, and scaling

Weight quantization gets a 70B model onto fewer GPUs, yet high-concurrency serving still hits memory walls as long prompts and active conversations fill the KV cache. Storing cached keys and values in FP8 or INT8 cuts KV capacity and per-step decode memory reads roughly in half, provided you handle key outliers and scaling correctly.

Conceptual illustration of thick unquantized memory plates alongside twice as many slim calibrated quantized plates.
Quantizing cached keys and values to FP8 or INT8 doubles sequence capacity while requiring careful scaling for key outliers.

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.

Comparing common KV cache storage formats in production inference engines.
FormatBytes per elementScaling and calibration behaviorPrimary trade-off
BF16 / FP162 bytesUnquantized reference baselineHighest memory footprint and decode HBM traffic
FP8 E4M31 byteStatic k_scale / v_scale (or dynamic per-tensor/head scale)2x capacity; needs calibration to avoid clipping above 448
FP8 E5M21 byteOptional scale; wide exponent range up to 57,344Lower mantissa precision than E4M3; safer when uncalibrated
INT8 / INT4 (KIVI, KVQuant)1 byte or 0.5 bytes + scalesAsymmetric per-channel keys and per-token valuesPreserves 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.

Visual explanation

BF16 KV cache versus calibrated FP8 E4M3 KV cache

BF16 KV cache2 bytes per element
  1. Prefill & appendWrite unquantized 16-bit K and V vectors into paged blocks
  2. Capacity ceilingEach 16K sequence consumes 5.00 GiB on a 70B GQA model
  3. Decode attention readStream 2x bytes from HBM on every token step
FP8 E4M3 KV cache1 byte + k_scale / v_scale
  1. Scale & cast on writeApply calibrated k_scale / v_scale before storing FP8 pages
  2. 2x sequence capacitySame 16K sequence drops to 2.50 GiB, doubling concurrency
  3. Native FP8 attentionHalves KV HBM reads on Hopper, Ada, and Blackwell GPUs
Illustrative memory and read-traffic comparison for Llama 3.1 70B (80 layers, 8 KV heads, d_head=128) at 16,384 tokens. Calibrated FP8 scales prevent channel outliers from clipping at 448.

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.

Run with Python 3; no GPU or packages required
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}")
Calculated output
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.000046

In 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 prefer E4M3 paired with per-layer or per-head static k_scale and v_scale factors measured on representative prompts.
  • FP8 E5M2 (5 exponent bits, 2 mantissa bits): Extends the representable range to 57,344 at the cost of coarser rounding steps. Without calibrated scales, E5M2 avoids silent overflow if activation outliers spike past 448, though accuracy trails calibrated E4M3 on 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-scales in 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:

  1. Match dtype and scaling flags to your checkpoint. In vLLM, start with --kv-cache-dtype fp8 (or fp8_e4m3 / fp8_e5m2) and supply calibrated scales or --calculate-kv-scales. In SGLang, pass --kv-cache-dtype fp8_e4m3 (or fp8_e5m2) and verify the selected attention backend logs native FP8 KV support at startup.
  2. Build reproducible launch flags. Keep weight quantization and KV quantization explicit in your serving config; test combinations safely in the vLLM & SGLang command builder.
  3. 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.
  4. 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.

  1. vLLM documentation: Quantized KV Cache
  2. SGLang documentation: Server arguments and KV cache dtype
  3. FP8 Formats for Deep Learning (Micikevicius et al., 2022)
  4. KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache (2024)
  5. KVQuant: Towards 10 Million Context Length LLM Inference with KV Cache Quantization (2024)

Keep learning

Related guide · 4 min readMulti-Head Latent Attention (MLA) explained: KV compressionRelated guide · 5 min readGPU memory for LLM inference: how to size and choose a GPURelated guide · 6 min readLLM quantization explained: FP8, INT8, INT4, AWQ, GPTQRelated guide · 7 min readKV cache explained: formula, diagram, and memory sizingAcademy course · 9 unitsInference Engineering FoundationsAcademy course · 13 unitsvLLMAcademy course · 13 unitsSGLangAcademy course · 20 unitsHugging Face Transformers
Back to all articles