Practical KV-Cache Quantization for Long-Context Transformer Serving
At context lengths beyond 32,768 tokens, autoregressive decoding becomes strictly memory-bandwidth bound. Even with Grouped-Query Attention (GQA), storing FP16 key and value tensors quickly dominates GPU HBM capacity and limits concurrent batch size.
Memory Footprint per Sequence
For a 70B-class GQA model with 80 layers, 8 KV heads, and head dimension 128, a single sequence at 64K tokens consumes roughly 20.5 GB in FP16. Quantizing the KV cache to FP8 (E4M3) cuts this in half with negligible quality loss, while per-channel INT4 brings the footprint down to ~5.4 GB.
| KV Precision | 64K Memory / Req | Max Batch (80GB) | PPL Delta (WikiText-2) |
|---|---|---|---|
| FP16 (baseline) | 20.5 GB | 2 | 0.00 |
| FP8 E4M3 | 10.3 GB | 5 | +0.02 |
| INT4 (per-channel K, per-token V) | 5.4 GB | 10 | +0.09 |
Key Implementation Detail: Asymmetric Outliers
Key tensors exhibit persistent channel-wise outliers across tokens, whereas value tensors vary primarily along the token dimension. Applying per-channel scaling factors to Keys and per-token scaling to Values preserves attention softmax sharpness on long-range retrieval tasks.
# Minimal per-channel K / per-token V quantization scale calculation
k_scale = k.abs().amax(dim=-2, keepdim=True).clamp(min=1e-6) / 7.0
v_scale = v.abs().amax(dim=-1, keepdim=True).clamp(min=1e-6) / 7.0
k_q = torch.round(k / k_scale).clamp(-8, 7).to(torch.int8)
v_q = torch.round(v / v_scale).clamp(-8, 7).to(torch.int8)
Takeaways
In production deployments, FP8 KV-cache is effectively a free 2x concurrency boost on Ada/Hopper GPUs. INT4 becomes worthwhile when serving 64K+ prompts under tight memory budgets, provided calibration keeps the first four sink tokens in FP16.