KV Cache
An inference optimization that caches previously computed Attention Key and Value tensors in GPU memory during autoregressive decoding, avoiding redundant recomputation at each token step
Table of Contents
Structure Diagram
What is KV Cache?
An inference optimization that caches previously computed Attention Key and Value tensors in GPU memory during autoregressive decoding, avoiding redundant recomputation at each token step. It is a core concept in LLM Fundamentals within AI / ML.
Core Principles
Autoregressive Decoder LLMs generate one token at a time. Because Causal Self-Attention ensures earlier tokens cannot attend to future tokens, their Key ($K$) and Value ($V$) projections never change once computed.
KV Caching stores those $K$ and $V$ tensors across all transformer layers in GPU VRAM. Each subsequent decoding step computes $Q, K, V$ for only the newest token and appends to the cache—trading compute for memory and making VRAM capacity and bandwidth the primary bottleneck in LLM serving.
Practical Takeaways
- Use PagedAttention in production serving: Engines like vLLM partition KV caches into non-contiguous memory blocks, eliminating fragmentation and boosting concurrent batch throughput.
- Understand GQA and MLA savings: Modern architectures use Grouped-Query Attention (GQA) or Multi-Head Latent Attention (MLA) to shrink per-token KV footprints dramatically.
- Quantize the KV cache for long contexts: Storing KV caches in FP8 or INT8 increases maximum concurrency and context length with minimal quality degradation.
Notable Examples
- vLLM & SGLang: Combine PagedAttention and RadixAttention to share prefix KV blocks across concurrent requests.
- Llama 3 & DeepSeek: Adopt GQA and MLA respectively so 128K-token contexts remain affordable in GPU memory.
- On-Device LLMs: Apply sliding-window or quantized KV caches to keep long chats within mobile RAM limits.