Inferensys

Glossary

KV-Cache

A memory mechanism in transformer models that stores the computed key and value tensors from previous tokens to avoid redundant computation during autoregressive text generation.
Data engineer managing feature store on laptop, feature definitions visible, casual data engineering session.
TRANSFORMER MEMORY MECHANISM

What is KV-Cache?

A memory mechanism in transformer models that stores the computed key and value tensors from previous tokens to avoid redundant computation during autoregressive text generation.

KV-Cache is a memory optimization technique that stores previously computed Key and Value tensors from the attention mechanism during autoregressive text generation. By caching these intermediate representations, the model avoids recomputing them for all prior tokens at each new generation step, transforming the quadratic computational complexity of attention into a linear operation per new token.

This mechanism is fundamental to achieving acceptable Time-to-First-Token (TTFT) and inter-token latency in production language model serving. The cache grows linearly with sequence length, making its memory footprint a critical constraint in continuous batching systems and a primary target for optimization through techniques like PagedAttention and quantized KV-Cache compression.

MECHANISM

Core Characteristics of KV-Cache

The KV-Cache is a fundamental inference optimization that eliminates redundant computation by storing previously computed Key and Value tensors, transforming the quadratic cost of autoregressive generation into a linear memory operation.

01

Linearized Autoregressive Decoding

Without a cache, each new token forces a full recalculation of attention over the entire growing sequence, resulting in O(n²) time complexity. The KV-Cache stores the Key and Value projections from all prior tokens. When generating token t+1, the model only computes the Query, Key, and Value for the single new token and appends them to the cache. This reduces the computational cost of each step to O(n) linear time, making long-form generation feasible.

02

Memory Capacity Planning

The cache size scales linearly with four factors:

  • Batch Size (B): Number of concurrent sequences
  • Sequence Length (L): Total tokens generated
  • Number of Layers (H): Transformer depth
  • Hidden Dimension (D): Model width

Total memory = 2 * B * L * H * D * sizeof(dtype) bytes. For a 7B model generating 2048 tokens with a batch of 32 in FP16, the cache alone consumes over 2 GB of VRAM. This often exceeds the model weights themselves, making it the primary bottleneck for high-throughput serving.

2 GB+
Cache VRAM (7B Model, BS=32)
Factor vs. Model Weights
03

Prefill vs. Decode Phase Disparity

The KV-Cache creates a distinct performance profile with two phases:

  • Prefill Phase: The initial prompt is processed in parallel. This is compute-bound, saturating the GPU's matrix multiplication units as it computes the full cache for all input tokens simultaneously.
  • Decode Phase: Each subsequent token is generated sequentially. This is memory-bound, as the entire cache must be loaded from VRAM to compute attention for a single new token. Optimization strategies must target these two bottlenecks differently.
05

Multi-Query and Grouped-Query Attention

Standard Multi-Head Attention (MHA) stores separate Key and Value tensors for each head, multiplying memory usage. Optimization variants reduce this:

  • Multi-Query Attention (MQA): All heads share a single Key and Value tensor, drastically cutting cache size but potentially degrading quality.
  • Grouped-Query Attention (GQA): A middle ground where heads are divided into groups sharing a single K and V. Models like Llama 2 70B use GQA to achieve near-MHA quality with a significantly smaller memory footprint, directly lowering the cost of the KV-Cache.
06

Cache Eviction and Quantization

For extremely long contexts, the cache can exceed available memory. Mitigation strategies include:

  • Sliding Window Attention: Only the most recent W tokens' cache entries are retained, enforcing a fixed memory bound.
  • KV-Cache Quantization: Storing Keys and Values in lower precision (e.g., INT8 or FP8 instead of FP16) reduces memory pressure by 2-4x with minimal accuracy loss.
  • Token Dropping: Heuristics like StreamingLLM evict the cache entries for middle tokens while preserving initial 'attention sinks' and recent tokens to maintain coherence.
CACHE COMPARISON

KV-Cache vs. Related Caching Mechanisms

A technical comparison of KV-Cache against other caching strategies used in retrieval-augmented generation and inference pipelines.

FeatureKV-CacheSemantic CacheEmbedding CacheLRU Cache

Primary Purpose

Stores key-value tensors from prior tokens to avoid recomputation during autoregressive decoding

Stores query-answer pairs based on semantic similarity to skip retrieval and generation

Persists computed vector embeddings to eliminate redundant neural network inference

Evicts least recently accessed items to maintain a bounded memory footprint for general data

Data Stored

Multi-head attention key and value tensors per layer per token

Natural language query and its synthesized response

High-dimensional floating-point vector representations

Arbitrary byte sequences or objects

Cache Key

Sequence position and layer index

Semantic vector of the user query

Hash of the raw text chunk

Exact object reference or string

Hit Determination

Exact sequence prefix match

Cosine similarity above threshold

Exact hash match

Exact key match

Typical Latency Reduction

10-100x for decode step

Eliminates retrieval + generation entirely

Eliminates embedding model inference

Variable, depends on backend latency

Memory Overhead

High; scales with batch size × sequence length × layers × hidden dim

Low; stores only text pairs

Medium; stores one vector per chunk

Configurable; bounded by max size

Invalidation Trigger

Sequence divergence or max length exceeded

Semantic drift or TTL expiration

Source document update

Capacity eviction or TTL

Primary Use Case

Transformer text generation

FAQ and conversational AI

Semantic search indexing

General-purpose application caching

KV-CACHE MECHANICS

Frequently Asked Questions

Explore the core concepts behind the Key-Value Cache, the critical memory mechanism that makes autoregressive text generation computationally feasible by eliminating redundant attention calculations.

A KV-Cache (Key-Value Cache) is a memory mechanism in transformer-based language models that stores the computed Key and Value tensors from previous tokens during autoregressive text generation. Without a KV-Cache, the model would recompute the attention scores for the entire sequence every time it generates a new token, leading to quadratic time complexity. The mechanism works by appending the new Key and Value projections for the latest token to the cached tensors, so the model only computes attention for the single new query token against all historical keys. This optimization reduces the computational complexity of generation from O(n²) to O(n), transforming a theoretical architecture into a practical inference engine.

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.