KV Cache Quantization in Practice: Bit Width, Group Size, and Evaluation
This article explains how to estimate KV cache memory, choose bit width and group size, apply mixed precision and kernel-aware implementation, understand benefit boundaries, and evaluate quantized KV caches against an FP16 baseline. It focuses on practical trade-offs for long-context LLM inference.
1. Estimate KV Cache Memory First
Memory pressure in long-context inference comes mainly from the KV cache. Model weights have a fixed size after loading, while the KV cache grows linearly with sequence length. The estimation formula is:
KV bytes ≈ 2 × L × H_kv × D × S × B × b / 8
Here, 2 represents the two caches for K and V, L is the number of layers, H_kv is the number of KV heads, D is the head dimension, S is the sequence length, B is the batch size, and b is the number of bits per element.
Consider a set of assumed parameters: L=32, H_kv=8, D=128, S=131072 (128K), and B=1. With FP16 storage (b=16), the cache is about 16 GiB. With INT8 (b=8), it is about 8 GiB, and with INT4 (b=4), it is theoretically about 4 GiB.
These numbers include only the data itself. The formula does not account for paged management, memory alignment, runtime buffers, or framework overhead, so actual usage is usually higher. Before launch, measure peak memory on the target device; do not treat the formula result as an exact value.
2. Choosing Bit Width and Group Size
The basic quantization approach is to store historical K/V in low bit width and dequantize during attention computation, or to fuse dequantization with matrix operations inside the kernel. Newly generated tokens can remain at higher precision, while only the stable historical portion is compressed.
Common trade-offs are shown below (bits per element are calculated with group size 32 and one FP16 scale factor per group):
| Option | Bits per element | Relative to FP16 storage | Main risk | Suitable scenario |
|---|---|---|---|---|
| FP16 | 16 | 100% | None | Baseline and quality reference |
| INT8 | 8.5 | About 53% | Small loss, relatively stable | Tight memory but high quality requirements |
| INT4 (grouped) | 4.5 | About 28% | Long-context recall may degrade | Clearly insufficient memory, and already tested |
| NF4 and other non-uniform 4-bit formats | About 4.5 | About 28% | Implementation-dependent; confirm kernel support | Scenarios sensitive to numerical distribution |
If asymmetric quantization or a zero point is used, each group also needs to store a zero point, and the bit overhead increases accordingly.
Group Size
Smaller groups make each scale factor fit the local value range more closely, which usually improves accuracy, but scale factors also take more space. With group size 32, one FP16 scale factor adds 0.5 bits per element; with group size 64, it adds 0.25 bits; with group size 128, it adds 0.125 bits. In practice, start with 32 or 64 and adjust based on evaluation results.
Quantization Steps
- Collect calibration data. Use long texts similar to the business workload and cover the target context length. The amount should be sufficient to obtain stable statistics.
- Compute the maximum absolute value per group and calculate the scale factor. For symmetric quantization, the formula is scale = max(|x|) / (2^(b-1) - 1).
- Handle all-zero groups. Set a very small lower bound for the scale factor, such as max(scale, 1e-8), to avoid division by zero.
- Map floating-point values to integers and store them, along with the scale factor for each group.
- Dequantize by group before attention computation, or fuse the dequantization step inside the kernel.
K and V often have different value distributions. Channel-wise outliers in K are usually more pronounced than in V, so some implementations group K by channel and V by token. This choice should be determined by comparing results on your own model.
3. Mixed Precision and Retaining Sensitive Layers
Layers differ in their sensitivity to quantization. Three common approaches are:
- Keep the first and last several layers at higher precision and use low bit width for the middle layers.
- Test attention heads for sensitivity and keep FP16 for heads with larger errors.
- Keep tokens in a recent window at higher precision and compress distant history to low bit width. This sliding-window strategy balances the precision of new content with the memory footprint of history.
Memory savings from mixed precision must be calculated by layer and by token. For example, in a 32-layer model, if 8 layers remain FP16 and the other 24 use INT4, the average is about 7.4 bits per element. This is lower than all-INT4 but still substantially lower than all-FP16.
4. Kernel Implementation Notes
- Dequantization and attention computation should be fused. If the entire history is dequantized to FP16 and written back to GPU memory, the temporary buffer can cancel most of the benefit.
- Memory layout should match access patterns. Pack integer data and scale factors together so that data from the same group can be read contiguously.
- Decode is often limited by memory bandwidth. Compressed cache reduces read volume, but unpacking adds computation. Prefill and decode should be measured separately on the target hardware.
- Confirm that the inference framework’s kernels support the chosen bit width and group size. Some frameworks implement only a subset of combinations.
5. Benefit Boundaries and Alternatives
Quantization reduces resident KV cache memory, not weight memory. If the bottleneck is mainly weights, the benefit of quantizing the KV cache is limited. Whether throughput improves depends on kernels and hardware; you cannot infer faster speed from lower bit width alone.
Quantization is often used together with other techniques:
| Technique | Problem it addresses | Relationship to quantization |
|---|---|---|
| Paged management (e.g., PagedAttention) | Reduces memory fragmentation and reservation waste | Can be stacked with quantization; they do not replace each other |
| GQA or MQA | Reduces the number of KV heads through model architecture | Determined by model architecture and cannot be changed at inference time |
| Evicting or compressing historical tokens | Discards or merges part of the history | May harm long-range recall; must be evaluated together with quantization |
| KV offload to CPU or disk | Moves cold data out of GPU memory or the memory pool | Data transfer bandwidth becomes a new bottleneck and must be measured |
6. Evaluation Protocol
Evaluation should cover both quality and resources, compared with an FP16 baseline.
Quality metrics:
- Perplexity: compare on long-text corpora to detect overall distribution shift.
- Long-context retrieval: insert target information at different depths and test recall. This type of test most easily exposes long-context quantization issues.
- Task metrics: use business question answering, summarization, or code tasks and score them with the existing criteria.
- Output consistency: fix decoding parameters (e.g., greedy decoding) and measure the length of the prefix matching the baseline output, or the proportion of exactly matching samples.
Resource metrics:
- Peak memory: record the peak memory of the whole process, including weights and runtime state.
- Time to first token and decode throughput (tokens/s).
- Maximum context length and batch size that can run stably.
Measurement conditions should be consistent. Record the hardware model, driver and framework versions, context length, batch size, warm-up iterations, and repeat count. Repeat each configuration multiple times and report the mean and variation range.
7. Risks
- Quantization may reduce long-context recall or cause generation quality fluctuations on specific tasks. Passing short-text tests does not mean long-text behavior is problem-free.
- If calibration data differs greatly from the business data distribution, scale factors may be inaccurate.
- Sensitivity to bit width varies widely across models; others’ conclusions cannot be directly applied to your model.
- It is advisable to validate on offline samples or with a small share of traffic first; broader use should follow only after quality metrics meet the target.
