Inferensys

Glossary

Key-Value (KV) Cache

An inference optimization technique that stores previously computed Key and Value vectors for all generated tokens, preventing redundant re-computation during autoregressive decoding.
Developer testing AI inference on mobile phone in hand, laptop with optimization code visible, casual tech review moment.
INFERENCE OPTIMIZATION

What is Key-Value (KV) Cache?

The KV cache is a memory optimization technique that stores previously computed Key and Value vectors during autoregressive text generation, eliminating redundant computation and transforming inference from a quadratic to a linear-time operation per step.

A Key-Value (KV) Cache is a dynamic memory buffer that stores the Key and Value vectors from all previously processed tokens during autoregressive decoding in Transformer models. Without caching, the model would recompute the full attention matrix for the entire growing sequence at each generation step, resulting in prohibitive computational cost. By retaining these vectors, each new token only computes attention against its own Query and the stored Keys and Values, reducing per-step complexity from O(n²) to O(n).

The KV cache directly trades memory for speed, becoming the dominant memory bottleneck during inference with large language models. Its size scales linearly with batch size, sequence length, number of layers, and hidden dimension. Techniques like Multi-Query Attention (MQA) and Grouped-Query Attention (GQA) were explicitly designed to shrink the KV cache footprint, while FlashAttention optimizes the I/O patterns of cache reads and writes in GPU SRAM for maximum throughput.

INFERENCE OPTIMIZATION

Core Characteristics of the KV Cache

The Key-Value (KV) Cache is a defining optimization for autoregressive language models, trading memory capacity for a dramatic reduction in redundant computation. The following cards break down its essential properties, mechanisms, and design trade-offs.

01

Mechanism: Avoiding Redundant Computation

During autoregressive decoding, a new token is generated at each step. Without a cache, the model would recompute the Key and Value vectors for all previous tokens at every step. The KV Cache stores these previously computed vectors in GPU memory.

  • Process: At step t, only the Query vector for the new token is computed. This Query attends to the cached Keys and Values from steps 0 to t-1.
  • Result: This transforms a quadratic O(n^2) compute operation per step into a linear O(n) one, where n is the sequence length.
O(n)
Compute per Step
02

Memory Capacity: The Bottleneck

The KV Cache's primary cost is memory. Its size scales linearly with the batch size, sequence length, number of layers, and head dimension.

  • Formula: 2 * batch_size * seq_len * num_layers * hidden_dim * precision_bytes.
  • Impact: For large models and long contexts, the cache can consume tens of gigabytes, often exceeding the memory required for the model weights themselves. This makes memory bandwidth the primary bottleneck for inference throughput.
GBs
Cache Size
04

Pre-fill vs. Decode Phases

The KV Cache's behavior is split into two distinct phases:

  • Pre-fill Phase: The initial prompt is processed in parallel. The Keys and Values for all prompt tokens are computed and stored in the cache in a single, compute-bound forward pass.
  • Decode Phase: Tokens are generated one by one. Each step computes a new Query and appends a single new Key-Value pair to the cache. This phase is memory-bound, limited by the speed of reading the cache from memory.
05

Continuous Batching

In production serving, the KV Cache enables continuous batching. Instead of waiting for all sequences in a batch to finish, a serving system can dynamically evict completed sequences and insert new requests into the batch. This requires intelligent memory management to allocate and free cache blocks without fragmentation, maximizing hardware utilization.

INFERENCE MEMORY TRADE-OFFS

KV Cache Variants: MHA vs. MQA vs. GQA

Comparison of Key-Value cache memory footprint and bandwidth requirements across standard Multi-Head Attention, Multi-Query Attention, and Grouped-Query Attention mechanisms during autoregressive decoding.

FeatureMulti-Head Attention (MHA)Multi-Query Attention (MQA)Grouped-Query Attention (GQA)

KV Head Count

h (equal to Query heads)

1 (shared across all heads)

g (1 < g < h)

KV Cache Size (relative)

100% (baseline)

~1/h of MHA

~g/h of MHA

Memory Bandwidth Demand

High

Low

Medium

Inference Throughput

Baseline

Significantly higher

Higher than MHA

Model Quality Impact

Highest fidelity

Potential minor degradation

Near-MHA quality

Training Complexity

Standard

Standard

Standard

Adopted By

Original Transformer, BERT

PaLM, Falcon

Llama 2 (70B), Llama 3

KV CACHE

Frequently Asked Questions

Clear, technical answers to the most common questions about the Key-Value Cache mechanism, its role in optimizing large language model inference, and the engineering trade-offs involved.

A Key-Value (KV) Cache is an inference optimization technique that stores the previously computed Key and Value vectors for all generated tokens, preventing redundant re-computation during autoregressive decoding. In a standard Transformer, generating each new token requires the model to attend to all previous tokens. Without a cache, the Key and Value projections for the entire sequence would be recomputed from scratch at every time step, resulting in a quadratic increase in computation. By storing these vectors in memory, the model only needs to compute the Query, Key, and Value for the single new token and then attend to the concatenation of the cached history and the new projection. This changes the computational complexity of each decoding step from quadratic to linear with respect to sequence length, making real-time text generation feasible.

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.