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).
Glossary
Key-Value (KV) Cache

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.
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.
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.
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 steps0tot-1. - Result: This transforms a quadratic
O(n^2)compute operation per step into a linearO(n)one, wherenis the sequence length.
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.
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.
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.
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.
| Feature | Multi-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 |
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.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
The KV Cache is a critical component of the autoregressive generation pipeline. These related concepts define the attention mechanisms it supports, the architectural variants designed to shrink it, and the algorithms that accelerate it.
Multi-Query Attention (MQA)
An architectural variant where all attention heads share a single set of Key and Value projection weights, while retaining separate Query projections. This dramatically reduces the size of the KV Cache by a factor equal to the number of heads, lowering memory bandwidth requirements during inference. MQA trades a small amount of model capacity for significant decoding speedups, making it a popular choice for production deployments where memory is the bottleneck.
Grouped-Query Attention (GQA)
An interpolation between Multi-Head Attention and Multi-Query Attention that partitions Query heads into groups. Each group shares a single set of Key and Value heads. GQA balances the inference speed of MQA with the model quality of standard multi-head attention. It achieves near-MQA memory savings for the KV Cache while recovering most of the representational power lost by aggressive sharing, as adopted in Llama 2 and subsequent models.
FlashAttention
An IO-aware exact attention algorithm that minimizes reads and writes between GPU High Bandwidth Memory (HBM) and on-chip SRAM. By fusing the attention computation into a single tiled kernel, FlashAttention avoids materializing the full N x N attention score matrix in HBM. This reduces the memory footprint of the KV Cache during computation and accelerates both training and inference without any approximation.
Autoregressive Decoding
The sequential generation process where a language model predicts one token at a time, appending each new token to the input sequence for the next step. Without a KV Cache, this would require re-computing the Key and Value vectors for all previous tokens at every step, resulting in quadratic complexity. The KV Cache is the primary optimization that makes autoregressive decoding computationally tractable for long sequences.
Context Window
The maximum number of tokens a model can process in a single forward pass, defining the upper bound of the KV Cache size. As context windows expand from 4K to 128K or even 1M tokens, the KV Cache becomes the dominant memory consumer during inference. Managing this cache efficiently—through techniques like GQA, MQA, or KV cache quantization—is essential for serving long-context models at scale.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us