Inferensys

Glossary

KV Cache

A KV cache, or key-value cache, is a memory buffer used in transformer-based language models to store computed key and value tensors from previous tokens during autoregressive decoding, eliminating redundant computation and significantly reducing inference latency.
ML engineer running AI model benchmarks, performance charts on multiple screens, late night home office setup.
INFERENCE OPTIMIZATION

What is KV Cache?

A technical definition of the KV Cache, a core mechanism for accelerating transformer inference.

A KV cache (key-value cache) is a memory buffer used in transformer-based language models to store the computed key and value tensors from previously processed tokens during the autoregressive decoding phase. By caching these intermediate states, the model avoids recalculating them for every new token, transforming a quadratic-complexity operation into a linear one and dramatically reducing inference latency and computational load.

The cache's size grows linearly with sequence length and batch size, making it a primary bottleneck for long-context inference. Optimization techniques like PagedAttention, Multi-Query Attention (MQA), and KV cache quantization are essential to manage this memory footprint, directly impacting throughput and the feasible context window within fixed GPU memory constraints.

INFERENCE OPTIMIZATION

Key Characteristics of KV Cache

The KV cache is a foundational optimization for transformer inference. Its design and management directly dictate system performance, cost, and the feasible context length for applications.

01

Memory-Bound Bottleneck

During the decode phase, the primary computational cost shifts from matrix multiplication to loading the KV cache from GPU memory. The system enters a memory-bound regime, where performance is limited by memory bandwidth, not arithmetic throughput. This makes cache size and access patterns critical for latency.

  • Impact: Reading cached keys/values dominates runtime.
  • Optimization Goal: Minimize cache footprint and maximize data locality.
02

Autoregressive State

The KV cache stores the computational state of the transformer's attention mechanism for all previously generated tokens. Each new decoding step appends a single new key-value pair per layer and head while reading the entire cached history. This stateful design is what enables efficient autoregressive generation but also creates linear memory growth with sequence length.

  • Core Function: Enables O(1) computation for attention over history.
  • Consequence: Cache size scales as O(batch_size * num_layers * num_heads * seq_len * head_dim).
03

Prefill vs. Decode Phase

Transformer inference has two distinct phases governed by KV cache usage:

  • Prefill Phase: The initial, compute-intensive parallel processing of the input prompt. All prompt tokens are processed simultaneously, and their key/value tensors are computed and stored, populating the initial cache.
  • Decode Phase: The iterative, memory-intensive token generation. For each new token, the model reads the entire existing cache and appends one new KV pair.

This dichotomy necessitates different optimization strategies for each phase.

04

Linear Memory Growth

The KV cache consumes GPU memory that grows linearly with both batch size and sequence length. For a model with parameters L (layers), H (heads), and D (head dimension), the cache size for one sequence is approximately 2 * L * H * D * seq_len * dtype_size. This linear scaling is the fundamental constraint on context window length and batch size.

  • Example: A 70B model with 80 layers, 64 heads, and 128-dim heads at FP16 requires ~2.5MB of cache per token.
05

Architectural Dependence

The structure and size of the KV cache are directly determined by the model's attention architecture:

  • Multi-Head Attention (MHA): Each query head has a dedicated key and value head, resulting in the largest cache.
  • Multi-Query Attention (MQA): All query heads share a single key and value head, reducing cache size by a factor of H.
  • Grouped-Query Attention (GQA): A tunable hybrid where groups of query heads share a KV head, offering a memory/quality trade-off.

Choices like Rotary Positional Embedding (RoPE) also affect caching efficiency by enabling relative position calculations without storing absolute positions.

06

Management Complexity

Efficiently managing the KV cache in production involves solving several systems challenges:

  • Continuous Batching: Dynamically adding/removing sequences from a shared batch requires non-contiguous, variable-length cache allocation.
  • Cache Eviction: Policies (e.g., LRU) for discarding cached tokens when the context exceeds physical memory.
  • Offloading & Sharding: Moving cache to CPU/NVMe (offloading) or splitting it across GPUs (sharding) to overcome memory limits.
  • Quantization & Compression: Storing cache in lower precision (e.g., INT8) to reduce footprint.

Algorithms like PagedAttention (from vLLM) treat the cache as virtual memory with pages to solve fragmentation and sharing problems.

COMPARISON

KV Cache Optimization Techniques

A comparison of primary methods for reducing the memory footprint and improving the efficiency of the Key-Value cache during transformer inference.

TechniqueMemory ReductionCompute OverheadQuality ImpactPrimary Use Case

Multi-Query Attention (MQA)

~90% vs MHA

Low

Moderate (varies by task)

Extreme memory-constrained serving

Grouped-Query Attention (GQA)

Tunable (e.g., ~50%)

Low

Minimal

General-purpose serving (quality/efficiency trade-off)

KV Cache Quantization (INT8/FP8)

50% (FP16→INT8)

Low (dequantization)

Minimal with calibration

Increasing batch size or context length

PagedAttention (vLLM)

Eliminates internal fragmentation

Low (address translation)

None

Continuous batching with variable-length sequences

KV Cache Compression (Pruning)

10-50% (sparse)

Moderate (sparse ops)

Controlled loss

Research / extreme long-context

Sliding Window Attention

Fixed (window size)

None

None for in-window tokens

Streaming / infinite-length contexts

KV Cache Offloading (CPU/NVMe)

Enables context >> GPU RAM

High (PCIe/NVMe latency)

None (data preserved)

Research & ultra-long-context analysis

KV CACHE

Frequently Asked Questions

A KV cache, or key-value cache, is a memory buffer used in transformer-based language models to store the computed key and value tensors from previous tokens during the autoregressive decoding phase, eliminating redundant computation and significantly reducing inference latency.

A KV cache is a memory buffer that stores the computed key and value tensors for each token in a transformer model's context during autoregressive decoding. It works by eliminating redundant computation: during the decode phase, the model only computes the query, key, and value for the new token, then retrieves the keys and values for all previous tokens from the cache to compute attention scores. This transforms the computational complexity of generating token N from O(N²) to O(N), drastically reducing latency. The cache is populated during the initial prefill phase when the prompt is processed, and grows with each generated token.

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.