Inferensys

Glossary

KV-Cache

A memory optimization technique that stores the Key and Value tensors of previously processed tokens to avoid recomputing them during each step of autoregressive text generation.
Data engineer managing feature store on laptop, feature definitions visible, casual data engineering session.
MEMORY OPTIMIZATION

What is KV-Cache?

KV-Cache is a memory optimization technique that stores the Key and Value tensors of previously generated tokens to eliminate redundant computation during autoregressive text generation.

The KV-Cache (Key-Value Cache) is a critical inference optimization that prevents the recomputation of attention states for prior tokens. During autoregressive decoding, a transformer model computes Key (K) and Value (V) projections for every token in the sequence. Without caching, each new token generation would require recalculating these projections for the entire context window, resulting in quadratic computational complexity. By storing these tensors in GPU memory, the model only computes the K and V vectors for the newest token and appends them to the cache.

This mechanism transforms the computational complexity of attention from quadratic to linear with respect to sequence length during inference. The cache grows linearly with the number of generated tokens, making memory bandwidth the primary bottleneck rather than compute. Techniques like multi-query attention (MQA) and grouped-query attention (GQA) reduce the cache's memory footprint by sharing K and V heads. Efficient KV-Cache management, including paged attention and prefix caching, is essential for high-throughput serving systems like vLLM.

MEMORY OPTIMIZATION

Key Characteristics of KV-Cache

The KV-Cache is a critical inference optimization that trades memory for computation. By storing the Key and Value tensors of previously processed tokens, it eliminates redundant matrix multiplications during autoregressive generation, transforming the quadratic complexity of attention into a linear operation for each new token.

01

Mechanism of Autoregressive Caching

During autoregressive decoding, a standard Transformer would recompute the Key (K) and Value (V) projections for the entire sequence at every step. The KV-Cache stores these tensors in GPU memory after they are first computed. When generating token t+1, the model only computes the Query (Q) for the new token and performs attention against the cached K and V from tokens 0 through t. This reduces the computational complexity of generation from quadratic to linear relative to sequence length, drastically lowering latency per step.

O(n)
Per-Step Complexity
02

Memory Footprint and Precision

The memory required for the KV-Cache scales linearly with batch size, sequence length, number of layers, and hidden dimensions. The formula is: 2 * batch_size * seq_len * num_layers * hidden_dim * precision_bytes.

  • FP16 Precision: Standard for inference, balancing speed and memory.
  • INT8/INT4 Quantization: Applied to the cache itself to compress memory usage, often with minimal accuracy loss.
  • Head Dimension: In Multi-Head Attention (MHA), the cache stores separate tensors per head, significantly increasing the total memory volume.
Tensors Stored (K & V)
04

Multi-Query and Grouped-Query Attention

To reduce the size of the KV-Cache, architectural variants modify the attention heads:

  • Multi-Query Attention (MQA): All Query heads share a single Key and Value head. This drastically shrinks the cache but can slightly degrade quality.
  • Grouped-Query Attention (GQA): An interpolation where Query heads are divided into groups, and each group shares a single K and V head. GQA provides a balance between the memory efficiency of MQA and the quality of standard Multi-Head Attention (MHA).
05

Prefix Caching and Sharing

A system-level optimization where the KV-Cache for a common, static prefix—such as a system prompt or few-shot examples—is computed once and reused across multiple distinct requests. When a new request arrives with the same prefix, the engine performs a hash-based lookup to retrieve the pre-computed cache blocks, bypassing the expensive prefill phase entirely. This is critical for high-throughput serving of conversational AI agents with long, complex instructions.

06

Cache Eviction Policies

When the sequence length exceeds the available memory budget, the KV-Cache must be evicted. Simple sliding window attention discards the oldest tokens. More advanced strategies use attention sink theory, which observes that initial tokens often act as massive attention sinks. Eviction policies may preserve these high-attention tokens while discarding middle tokens, mitigating the 'lost in the middle' phenomenon and preserving long-context coherence without infinite memory growth.

KV-CACHE MECHANICS

Frequently Asked Questions

Explore the fundamental mechanisms behind Key-Value caching in transformer inference, addressing common questions about memory allocation, performance trade-offs, and implementation strategies.

A KV-Cache (Key-Value Cache) is a memory optimization technique that stores the computed Key and Value tensors from previous generation steps during autoregressive decoding. In standard transformer attention, every new token generation requires recomputing the Keys and Values for all preceding tokens, resulting in quadratic computational complexity. The KV-Cache eliminates this redundancy by retaining these intermediate tensors in GPU memory. When generating token t+1, the model only computes the Query, Key, and Value for the new token, then concatenates the new Key and Value with the cached tensors from steps 0 through t. This reduces the attention computation from O(n^2) to O(n) per step, dramatically accelerating inference. The cache is typically stored in high-bandwidth memory (HBM) and grows linearly with sequence length, batch size, and the number of transformer layers.

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.