KV cache quantization

On this page 7

KV cache quantization is the technique of storing the attention keys and values that a transformer caches during text generation in a lower-precision number format, such as 8-bit or 4-bit, instead of 16-bit floating point. In AI infrastructure, it is one of the most effective ways to reduce inference memory, fit longer contexts and serve more concurrent requests on the same GPU.

The method targets the KV cache, not the model weights. Because the cache grows linearly with sequence length and batch size, it often exceeds the weight memory in long-context or high-concurrency serving, which makes compressing it a direct lever on throughput and cost per token.

Why the KV cache needs compression

During the decode phase, every new token attends to the keys and values of all previous tokens, so the server keeps them in GPU memory instead of recomputing them. The cache size equals 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element, which means each halving of precision halves the cache footprint.

For a model of roughly 70 billion parameters with grouped-query attention, a 128,000-token context in FP16 can occupy tens of gigabytes per sequence. Decoding is also memory-bandwidth bound: reading the cache at every step dominates the time per output token, so a smaller cache improves both capacity and speed.

FormatBits per elementCache size versus FP16
FP16 / BF1616100%
FP8 (E4M3)8About 50%
INT88About 50% plus scale overhead
INT44About 25% plus scale overhead
2-bit schemes2About 12-15% with metadata
Relative KV cache size by storage format

How KV cache quantization works

KV cache quantization converts each new key and value vector into a low-bit representation as it is written, and dequantizes it on the fly inside the attention kernel. Each group of values shares a scale factor (and sometimes a zero point) that maps integers back to real numbers, and the grouping granularity largely determines accuracy.

Keys and values behave differently. Keys contain outlier channels with consistently large magnitudes, so research methods such as KIVI quantize keys per channel and values per token. Other approaches keep the most recent tokens or a few attention-sink tokens in full precision, because errors there affect the output most.

GranularityHow scales are sharedTypical use
Per tensorOne scale for a whole layer cacheFP8 with calibrated scales
Per tokenOne scale per token vectorValues in INT4 or INT8
Per channelOne scale per hidden dimensionKeys with outlier channels
Per groupOne scale per block of 32-128 elementsAggressive 4-bit or 2-bit schemes
Common quantization granularities

Accuracy, speed and memory trade-offs

The central trade-off is memory savings versus output quality. FP8 KV cache is usually close to lossless for modern models and is supported natively by serving engines such as vLLM and TensorRT-LLM on recent GPUs. 4-bit caches typically cost a small but measurable accuracy drop, while 2-bit caches require careful outlier handling to stay usable.

Speed gains are not automatic. If the attention kernel does not fuse dequantization, the extra arithmetic can cancel the bandwidth benefit. The largest real gains come from the larger batch sizes that the freed memory allows, which raises aggregate tokens per second.

PrecisionQuality impactBest fit
FP8Negligible for most modelsDefault production choice
INT8Very small with good scalesHardware without FP8 support
INT4Small, task dependentLong-context or memory-limited serving
2-bitNoticeable without mitigationResearch and extreme context lengths
Practical trade-offs by precision

How it relates to other inference optimizations

KV cache quantization is complementary to other memory techniques rather than a replacement. PagedAttention removes fragmentation by allocating the cache in blocks; KV cache offloading moves cold blocks to CPU memory or storage; prompt caching reuses cached prefixes across requests. Quantization shrinks every block, so it multiplies the benefit of each.

Architectural changes such as grouped-query attention and multi-head latent attention reduce cache size at training time, whereas quantization applies after training without retraining. Weight quantization is a separate decision: a model can run with FP16 weights and an FP8 cache, or the reverse.

Deploying it safely

Teams should evaluate on their own workloads before enabling an aggressive cache format, because errors accumulate over long generations and affect long-context retrieval more than short chat. Needle-in-a-haystack tests, task benchmarks and side-by-side output comparison reveal degradation that perplexity alone can hide.

  • Start with FP8 and calibrated scales, then measure before trying 4-bit formats.
  • Confirm that the attention kernel supports the format natively to avoid slowdowns.
  • Track long-context accuracy separately from average benchmark scores.
  • Keep a fallback configuration in FP16 for workloads that prove sensitive.

Operational details also matter. Calibration of FP8 scales on representative prompts avoids clipping, while uncalibrated scales of 1.0 can work but leave accuracy on the table. Monitoring should compare quality metrics before and after rollout, because a silent regression in a rare task type may surface only in user feedback weeks later.

SymptomLikely causeFix
Facts lost in long documentsError accumulation over many tokensKeep recent tokens in full precision
Repetitive or garbled outputKey outliers clipped by coarse scalesUse per-channel key quantization
No throughput improvementKernel lacks fused dequantizationSwitch to a supported attention kernel
Accuracy drop after model updateStale calibration scalesRecalibrate on representative prompts
Symptoms of an overly aggressive cache format

The short version

When a language model writes text, it keeps notes about every word it has already seen. These notes take up a large share of the GPU memory. KV cache quantization writes the notes in a more compact form.

It is like saving photos in a smaller file format. You lose a tiny amount of detail. In return, far more fits on the same device. The server can then handle longer documents or more users at once.

Where it makes a difference

A company runs an internal assistant that answers questions over long contracts on servers with 80 GB GPUs. With the cache in FP16, each server holds only a handful of 100,000-token conversations before memory runs out, and users wait in a queue during busy hours.

The infrastructure team switches the serving engine to an FP8 KV cache and checks quality on a set of 500 real contract questions, where answers match the FP16 baseline in nearly every case. The freed memory roughly doubles the number of concurrent long sessions per server.

Queue times drop sharply during peak periods, and the team postpones buying additional GPUs. A later test with a 4-bit cache shows small errors in clause citations, so the team keeps FP8 for production.