Inferensys

Glossary

KV Cache

A memory buffer that stores computed key and value tensors from previous tokens during autoregressive generation to prevent redundant computation.
Data engineer managing feature store on laptop, feature definitions visible, casual data engineering session.
INFERENCE OPTIMIZATION

What is KV Cache?

A memory buffer that stores computed key and value tensors from previous tokens during autoregressive generation to prevent redundant computation.

The KV cache is a memory buffer that stores the previously computed Key and Value tensors during the autoregressive decoding phase of a transformer model. 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 cost per step.

This mechanism is essential for achieving interactive latency in large language models. Without a KV cache, generating the N-th token would require a full forward pass over all N-1 preceding tokens. The cache grows linearly with sequence length, making its memory footprint a primary bottleneck for long-context serving, which is addressed by techniques like PagedAttention and Multi-Query Attention.

MEMORY MECHANICS

Core Characteristics of KV Cache

The KV Cache is a defining architectural optimization for autoregressive transformers. It trades memory capacity for a dramatic reduction in redundant computation, fundamentally enabling the real-time generation of long sequences.

01

Mechanism of Autoregressive Caching

During autoregressive decoding, each new token must attend to all previous tokens. Without a cache, the Key and Value projections for the entire sequence would be recomputed at every step, resulting in quadratic complexity. The KV Cache stores these computed tensors in GPU memory.

  • Write Phase: When a new token is generated, its Key and Value tensors are computed and appended to the cache.
  • Read Phase: The attention mechanism reads all historical Keys and Values directly from the cache, computing only the single new Query vector.
  • Result: Reduces the computational complexity of a single decoding step from quadratic to linear relative to the sequence length.
02

Memory Capacity and Bottleneck

The cache size scales linearly with batch size, sequence length, number of layers, and hidden dimension. For large models, this creates a significant memory bottleneck.

  • Calculation: cache_size = 2 * batch_size * seq_len * num_layers * hidden_dim * precision_bytes
  • Example: A 70B parameter model serving a single 4096-token sequence can require over 2.5 GB of memory just for the KV Cache.
  • Impact: Memory bandwidth, not compute, often becomes the primary limiter of throughput, a phenomenon known as memory-bound inference.
03

PagedAttention and Fragmentation

Traditional KV Caches allocate one large contiguous block of memory per sequence, leading to internal fragmentation and limiting total throughput. PagedAttention solves this by partitioning the cache into non-contiguous blocks.

  • Block-Based Management: Memory is allocated in fixed-size blocks, similar to virtual memory paging in operating systems.
  • Zero Waste: Blocks can be shared across sequences for parallel sampling or beam search, eliminating redundant storage.
  • Result: This enables a serving system to handle a significantly higher number of concurrent requests by dynamically mapping logical KV caches to physical GPU memory blocks.
04

Prefix Caching for Shared Prompts

Many applications use a long, static system prompt or few-shot examples. Prefix Caching identifies and reuses the KV Cache for these shared prefixes across multiple distinct requests.

  • Mechanism: The serving engine hashes the prompt prefix tokens. If a match is found in a persistent cache, the pre-computed Keys and Values are loaded instantly.
  • Benefit: Eliminates the computationally expensive prefill phase for the shared portion, drastically reducing Time To First Token (TTFT) and freeing compute for unique suffixes.
  • Use Case: Critical for chatbots with large system instructions or Retrieval-Augmented Generation (RAG) applications with a fixed retrieved context.
05

Trade-off: Latency vs. Throughput

The KV Cache embodies a fundamental trade-off in inference serving. Saving compute by caching tensors consumes scarce high-bandwidth memory (HBM).

  • Latency-Optimized: Keeping the entire cache in GPU HBM ensures the fastest possible token generation speed.
  • Throughput-Optimized: Offloading less-frequently accessed cache blocks to CPU RAM or NVMe storage allows for serving extremely long contexts or more concurrent users, at the cost of higher per-token latency.
  • Quantization: Applying KV Cache Quantization (e.g., FP8 or INT8) is a common strategy to compress the cache, increasing effective memory capacity with minimal accuracy loss.
06

Multi-Query and Grouped-Query Attention

Architectural changes to the attention mechanism directly reduce the size of the KV Cache. Multi-Query Attention (MQA) uses a single Key-Value head shared across all Query heads.

  • MQA: Drastically shrinks the cache size, but can lead to quality degradation.
  • Grouped-Query Attention (GQA): A compromise where a small number of Key-Value heads (e.g., 4) serve a larger number of Query heads (e.g., 32).
  • Impact: GQA achieves near-MHA quality while significantly reducing the memory footprint of the KV Cache, enabling larger batch sizes and longer context windows on the same hardware.
INFERENCE MEMORY MANAGEMENT

KV Cache vs. Related Caching Mechanisms

A technical comparison of the KV Cache against other caching strategies used during large language model inference to reduce redundant computation and memory overhead.

FeatureKV CachePrefix CachingSemantic Caching

Cached Data Structure

Key and value tensors per token

KV Cache for shared prompt prefixes

Embedding vectors or raw text of prompts

Primary Objective

Eliminate recomputation of previous tokens

Eliminate recomputation for identical prompt starts

Eliminate inference entirely for semantically similar queries

Granularity

Per-token within a single sequence

Per-prefix across multiple requests

Per-request across a session or fleet

Storage Location

GPU VRAM (high-bandwidth memory)

GPU VRAM or CPU RAM

External database or in-memory store (e.g., Redis)

Exact Match Required

Cache Hit Condition

Autoregressive step > 1

Identical token sequence at prompt start

Vector similarity above threshold

Memory Overhead

Linear with sequence length (O(n))

Linear with prefix length, shared across users

Constant per entry, scales with number of entries

Risk of Staleness

KV CACHE

Frequently Asked Questions

Explore the mechanics of the Key-Value cache, the critical memory buffer that makes autoregressive text generation computationally feasible by eliminating redundant matrix multiplications.

A KV Cache is a memory buffer that stores the computed Key and Value tensors from previous tokens during autoregressive generation. In a standard Transformer, the attention mechanism computes Query, Key, and Value projections for every token. Without a cache, each new token generation would require recomputing these projections for the entire preceding sequence, resulting in quadratic computational complexity. The KV Cache works by saving these pre-computed Keys and Values in GPU memory. When generating token t+1, the model only computes the Query for the new token and retrieves all previous Keys and Values from the cache, concatenating them for the attention calculation. This transforms the generation step from O(n²) to O(n), dramatically accelerating inference.

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.