Inferensys

Glossary

KV Cache Compression

KV cache compression is a category of techniques that reduce the memory footprint of a transformer's key-value cache through methods like quantization and pruning, enabling longer context lengths or higher batch sizes within fixed hardware constraints.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
INFERENCE OPTIMIZATION

What is KV Cache Compression?

A set of techniques to reduce the memory footprint of the key-value cache in transformer models, enabling longer contexts and higher throughput.

KV cache compression is a category of memory optimization techniques, including pruning and quantization, applied to the key-value cache of transformer models to reduce its memory footprint. By compressing the stored key and value tensors, these methods allow for longer context windows or larger batch sizes within fixed hardware memory constraints, directly addressing the memory-bound nature of autoregressive inference. The goal is to minimize the performance impact on model quality while achieving significant memory savings.

Common approaches include KV cache quantization, which stores tensors in lower precision formats like INT8, and selective caching or pruning strategies that evict less important cache entries. These techniques are critical for deploying large language models in production, as they lower infrastructure costs and reduce latency by decreasing memory bandwidth pressure. Effective compression is a key component of modern inference engines like vLLM and TensorRT-LLM.

KV CACHE MANAGEMENT

Primary Compression Techniques

These are the core algorithmic methods for reducing the memory footprint of the key-value cache, enabling longer contexts and higher batch sizes on fixed hardware.

01

Quantization

Quantization reduces the numerical precision of the cached key and value tensors. Instead of storing them in full 16-bit (FP16/BF16) or 32-bit (FP32) floating-point format, they are compressed to 8-bit integers (INT8) or 8-bit floating-point (FP8).

  • Mechanism: A quantization function maps a range of high-precision values to a smaller set of discrete low-precision values, often using a scaling factor and zero-point.
  • Impact: Reduces the cache's memory footprint by 50% (FP16→INT8) or 75% (FP32→INT8), directly increasing the maximum possible context length. This also lowers memory bandwidth pressure during the attention computation.
  • Challenge: Requires careful calibration to minimize the loss in model accuracy (perplexity increase) due to the approximation error. Techniques like per-tensor or per-channel quantization and smoothing are used to mitigate this.
50-75%
Memory Reduction
INT8/FP8
Target Precision
02

Pruning

Pruning involves selectively removing entries from the KV cache that are deemed less important for future token generation. It is a lossy compression technique that trades some model quality for significant memory savings.

  • Spatial Pruning: Drops entire tokens from the cache. Policies include:
    • StreamingLLM's Attention Sink: Retains the first few tokens (the "sink") and a sliding window of recent tokens.
    • H2O (Heavy-Hitter Oracle): Keeps tokens that have historically received high attention scores.
    • Random Eviction: A simple baseline for comparison.
  • Structural Pruning: Drops specific dimensions or heads within the cached tensors. For example, head pruning removes entire attention heads from the cache if they are found to be redundant.
  • Use Case: Essential for enabling infinite-length generation with models trained on finite context windows, or for operating within strict, fixed memory budgets.
10-50%
Cache Size Reduction
Sliding Window
Common Policy
03

Low-Rank Approximation

Low-Rank Approximation exploits the inherent structure and redundancy in the key and value matrices by representing them using a compressed, factorized form. The core idea is that the high-dimensional KV cache can often be approximated by the product of smaller matrices.

  • Mechanism: Techniques like singular value decomposition (SVD) are applied to project the keys and values into a lower-dimensional subspace. Instead of caching the full [sequence_length, d_model] tensor, the system caches a smaller [sequence_length, k] projection matrix and a [k, d_model] basis matrix, where k << d_model.
  • Benefit: Provides a mathematically grounded, lossy compression method. The compression factor is tunable via the chosen rank k, offering a direct trade-off between memory savings and approximation fidelity.
  • Application: More computationally intensive to apply dynamically than pruning or quantization, and is often researched as a method to compress cached states between decoding steps or for long-term context storage.
k << d_model
Core Principle
04

Selective Caching

Selective Caching is a policy-based technique where the system decides what to cache in the first place, rather than caching all computed keys and values. It prevents non-essential data from entering the cache, acting as a form of proactive compression.

  • Layer Skipping: In deep transformer models, keys and values from certain intermediate layers may be skipped and not cached if analysis shows they contribute less to the final output.
  • Token Importance Gating: A lightweight learned or heuristic gating function evaluates each token as it is processed in the prefill phase. Only tokens that pass an importance threshold have their KV states written to the long-term cache.
  • Benefit: Reduces the working set size of the cache from the moment of creation, improving memory efficiency and potentially reducing write amplification. It is often combined with other techniques like pruning for a multi-stage compression pipeline.
Proactive
Compression Strategy
05

Architectural Modifications (MQA/GQA)

This approach compresses the KV cache by fundamentally changing the transformer's attention mechanism. Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) are model architecture changes that reduce the number of unique key and value heads.

  • Multi-Query Attention (MQA): All query heads share a single key head and a single value head. This drastically shrinks the KV cache size by a factor equal to the number of attention heads (e.g., 32x).
  • Grouped-Query Attention (GQA): A generalization of MQA where query heads are divided into groups, and each group shares a single key and value head. This provides a tunable trade-off: an 8-group GQA offers an 8x cache reduction with less quality degradation than full MQA.
  • Impact: These are pre-training techniques. Models like Llama 2 and 3 use GQA. The compression is "baked in," requiring no runtime algorithm, making it one of the most effective methods for production inference systems.
8-32x
Cache Reduction (MQA)
GQA
Llama 2/3 Standard
06

Offloading to CPU/NVMe

Offloading is a systems-level compression technique that treats high-cost GPU memory as a cache for a larger, slower memory hierarchy. It moves portions of the KV cache from GPU RAM to CPU RAM or even NVMe storage.

  • Mechanism: A caching policy (e.g., LRU) decides which blocks of the KV cache reside in fast GPU memory. "Cold" blocks are evicted to slower, higher-capacity CPU memory or SSD. When needed again, they are fetched back, causing increased I/O latency.
  • Technology Enabler: Relies on Unified Virtual Memory (UVM) frameworks like CUDA UVM or high-speed interconnifts like NVLink to manage the coherent address space between GPU and CPU.
  • Use Case: Critical for supporting extremely long context windows (e.g., 1M+ tokens) that far exceed available GPU memory. It explicitly trades latency for capacity, making it suitable for offline or non-latency-sensitive batch processing of long documents.
1M+ Tokens
Target Context
MECHANISM

How It Works and Key Trade-offs

KV cache compression reduces the memory footprint of the key-value cache, a critical bottleneck in transformer inference, by applying lossy or lossless data reduction techniques to enable longer contexts and higher batch sizes.

KV cache compression works by applying pruning, quantization, or sparsity techniques to the stored key and value tensors after each attention computation. Pruning removes entries deemed non-critical, while quantization reduces the numerical precision of each entry from 16-bit to 8-bit or 4-bit formats. These methods directly shrink the cache's memory footprint, allowing more tokens to be cached within fixed GPU memory, which is essential for long-context workloads.

The primary trade-off is between compression ratio and model quality. Aggressive compression saves significant memory but can introduce noise, degrading output accuracy or coherence. A secondary trade-off involves computational overhead; some techniques add latency from the compression/decompression operations themselves. Effective systems balance these factors, often using lightweight, per-token quantization that minimizes quality loss while maximizing memory savings for scalable inference.

METHODOLOGY

Comparison of KV Cache Compression Techniques

A technical comparison of primary methods for reducing the memory footprint of the key-value cache in transformer inference, evaluating trade-offs in compression ratio, quality impact, and computational overhead.

Metric / FeaturePruningQuantizationLow-Rank ApproximationSelective Caching

Core Mechanism

Removes entries deemed non-critical

Reduces numerical precision of stored tensors

Factorizes cache into compact matrices

Caches only a subset of layers or heads

Primary Compression Target

Sparsity (number of cache entries)

Bit-width (e.g., FP16 -> INT8)

Matrix rank (dimensionality reduction)

Cache depth (number of stored layers)

Typical Memory Reduction

30-70%

50% (FP16->INT8)

40-60%

20-50%

Quality Impact (PPL Degradation)

< 2%

1-5%

2-8%

Variable, can be < 1%

Decode Phase Overhead

Low (sparse reads)

Low (dequantization ops)

Medium (reconstruction matmul)

Very Low (no computation)

Prefill Phase Overhead

High (requires scoring)

None

High (requires factorization)

None

Compatibility with PagedAttention

Requires Model Retraining

Best Suited For

Very long contexts, batch inference

General-purpose latency reduction

Fixed, known deployment targets

Models with known redundancy

KV CACHE COMPRESSION

Frequently Asked Questions

KV cache compression is a critical set of techniques for reducing the memory footprint of the key-value cache in transformer models. This FAQ addresses common questions about its mechanisms, trade-offs, and implementation.

KV cache compression is a category of techniques, including pruning and quantization, aimed at reducing the memory footprint of the key-value cache in transformer models. It is needed because the KV cache grows linearly with both batch size and sequence length, quickly exhausting the limited high-bandwidth memory (HBM) of GPUs. Without compression, serving long-context models or large batches becomes prohibitively expensive or impossible, directly limiting a model's practical utility and increasing inference cost.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.