Contents
Key concepts
What is cached, and why
For each layer and each KV head the cache holds K and V for all previous tokens; queries are not cached because each step only needs the new token’s query. Prefill processes the prompt in one parallel pass and writes the cache; each decode step appends one token’s K and V per layer and reads the whole cache. Without it, step t would redo O(t) projections and the full prefix attention, making generation quadratic in compute for no benefit.
Flow · 3 stepsHow the KV cache fills during generation
- Prefill Prefill processes the prompt in one parallel pass and writes K and V for every prompt token to the cache.
- Decode step Each decode step computes only the new token's own projections, appends its K and V to the cache and reads the whole cache.
- Loop The produced next token becomes the new token of the next decode step.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Prefill | Prefill processes the prompt in one parallel pass and writes K and V for every prompt token to the cache. |
| 2 | Decode step | Each decode step computes only the new token's own projections, appends its K and V to the cache and reads the whole cache. |
| 3 | Loop | The produced next token becomes the new token of the next decode step. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Prompt | Input | one parallel pass |
| Prefill | Prefill | writes the cache |
| KV cache | Memory | K and V per layer and KV head |
| Decode step | Decode | new token only |
| Next token | Decode | becomes the new token |
Source: This page's text
Memory formula
Bytes per token = 2 (K and V) × layers × kv_heads × head_dim × bytes per element. Total = that × tokens per sequence × concurrent sequences. It depends on the number of KV heads, not query heads, and not directly on parameter count: a Llama-3-8B-style config (32 layers, 8 KV heads, head_dim 128, bf16) needs 128 KiB per token, whereas a head_dim-256 model with more KV heads can need far more despite being similar in size.
CalculatorKV cache memory for a model config
- Bytes per token
- 128 KiB
- 131,072 bytes
- Bytes per sequence
- 1 GiB
- 1,073,741,824 bytes
- Total KV bytes
- 16 GiB
- 17,179,869,184 bytes
Bytes per token = 2 × Layers × KV heads × Head dim × Bytes per element = 128 KiB
Bytes per sequence = Bytes per token × Tokens per sequence = 1 GiB
Total KV bytes = Bytes per token × Tokens per sequence × Concurrent sequences = 16 GiB
| Case | Layers | KV heads | Head dim | Bytes per element | Tokens per sequence | Concurrent sequences | Bytes per token | Bytes per sequence | Total KV bytes |
|---|---|---|---|---|---|---|---|---|---|
| 8B-class GQA, 16 users at 8k | 32 | 8 | 128 | 2 | 8,192 | 16 | 128 KiB | 1 GiB | 16 GiB |
| Same load, 32 KV heads | 32 | 32 | 128 | 2 | 8,192 | 16 | 512 KiB | 4 GiB | 64 GiB |
| 70B bf16, 32 users at 32k | 80 | 8 | 128 | 2 | 32,768 | 32 | 320 KiB | 10 GiB | 320 GiB |
MQA, GQA and latent attention
Multi-query attention shares one K/V head across all query heads (cache shrinks by the head count, with some quality loss); grouped-query attention uses an intermediate number of KV groups, e.g. 32 query heads sharing 8 KV heads cuts the cache 4× with little quality loss and can be uptrained from a multi-head checkpoint. DeepSeek’s multi-head latent attention caches a low-rank latent (512 dimensions plus a 64-dimensional decoupled RoPE key per layer) and reconstructs K/V on the fly; DeepSeek-V2 reports a 93.3% smaller cache than its 67B dense predecessor.
Compare · 3 variantsKV cache per token across attention variants
Data
| Variant | Query heads | KV heads | KV cache per token (bytes) | Computed as |
|---|---|---|---|---|
| Multi-head attention | 32 | 32 | 524,288 | 2 × 32 × 32 × 128 × 2 |
| Grouped-query | 32 | 8 | 131,072 | 2 × 32 × 8 × 128 × 2 |
| Multi-query | 32 | 1 | 16,384 | 2 × 32 × 1 × 128 × 2 |
Source: This page's text
Paged allocation (PagedAttention)
Reserving a contiguous max-length buffer per request wastes memory through internal and external fragmentation; the vLLM paper found earlier systems used only about 20–40% of KV memory for real token state. PagedAttention splits the cache into fixed-size blocks (16 tokens by default in vLLM) mapped through a per-request block table, so waste is limited to the last partial block, and blocks can be shared copy-on-write across beams, parallel samples and common prefixes.
Prefix caching and provider prompt caching
Self-hosted engines hash each full block together with its parent’s hash (plus LoRA ID or image hashes) and reuse matching blocks across requests, evicting least-recently-used free blocks. Hosted APIs expose the same idea as prompt caching: an exact-prefix match within a TTL (Anthropic’s default is 5 minutes) billed at a premium to write (1.25× for the 5-minute tier) and a steep discount to read (0.1× base input price as standard; as of November 2026 some newer models charge 0.05× or less). Any change early in the prompt invalidates everything after it, so put stable content (system prompt, tool definitions, documents) first and volatile content (timestamps, user turn) last. A semantic cache is different: it reuses whole responses for similar queries and can return wrong answers.
Why decode is bandwidth-bound
Each decode step reads every weight once plus the entire KV cache of every sequence in the batch, while doing only about 2 FLOPs per weight per sequence. Batching amortises weight reads, but KV reads grow with batch × context, so at long context the attention part stays memory-bound and KV bytes, not FLOPs, set the per-token latency and the maximum batch size.
Shrinking or moving the cache
FP8 KV halves memory (INT4 quarters it) at an accuracy cost that must be measured on long-context retrieval: vLLM saw 128k needle accuracy fall from 91% to 13% from attention accumulation precision before a fix, and for Llama-3.1-8B on one H100, FP8 KV only beat BF16 decode latency above about 7k tokens. Sliding-window or local attention layers cap per-layer cache at the window size (Gemma-style local:global layer mixes); attention-sink/eviction schemes (StreamingLLM, H2O) keep a subset of tokens; hybrid models with linear-attention or state-space layers keep a constant-size state in those layers. Offloading to CPU memory or SSD tiers trades capacity for transfer latency. Frontier designs now break the simple per-token formula: Qwen3.5 keeps KV in only one layer in four, and DeepSeek-V4’s compressed sparse attention needs about 10% of V3.2’s KV at 1M tokens. Offload tiers are first-class in vLLM connectors, LMCache, Mooncake and Dynamo.
Stack · 4 layersWhere the KV cache can live, fastest first
Each decode step reads the entire KV cache of every sequence in the batch.
Offloading to CPU memory trades capacity for transfer latency.
SSD tiers trade capacity for transfer latency; LMCache stores KV in local storage.
LMCache shares KV across requests and engines; Mooncake pools CPU, DRAM, SSD and NIC resources into a distributed KV cache.
Capacity planning
Usable KV memory ≈ GPU memory − weights − activation workspace − runtime overhead (engines reserve a fraction, e.g. vLLM’s gpu-memory-utilisation). Divide by bytes per token to get the token budget, then by the realistic context distribution, not the maximum, to get concurrency. When the budget is exhausted engines preempt (swap or recompute) requests, which shows up as latency spikes rather than errors.
Worked examples
Cache size for an 8B-class model serving 16 users at 8k tokens
A model has 32 layers, 8 KV heads and head dimension 128, with a bf16 cache. Estimate KV memory for 16 concurrent requests of 8,192 tokens each, and compare with full multi-head attention using 32 KV heads.
Per token: 2 × 32 layers × 8 heads × 128 dims × 2 bytes = 131,072 B = 128 KiB.
Per sequence: 8,192 tokens × 128 KiB = 1,048,576 KiB = 1 GiB.
16 sequences: 16 × 1 GiB = 16 GiB, on top of ~16 GB of bf16 weights (8B × 2 bytes).
Without GQA (32 KV heads): 4× larger, 512 KiB per token, 64 GiB for the same load, which no longer fits next to the weights on an 80 GB card.
Takeaway: within the same 16 GiB KV budget, GQA’s 4× saving is the difference between 16 and 4 concurrent 8k requests. FP8 KV would halve the GQA figure again to 8 GiB.
Will a 70B model serve 32 users at 32k context on two 80 GB GPUs?
Llama-3-70B-like config: 80 layers, 8 KV heads, head_dim 128. Target: 32 concurrent users at 32k tokens on 2 × 80 GB GPUs with tensor parallelism. Check feasibility and propose a configuration.
Weights: 70e9 × 2 B = 140 GB in bf16, leaving ~20 GB of the 160 GB before any cache or overhead. FP8 weights: ~70 GB.
KV per token (bf16): 2 × 80 × 8 × 128 × 2 = 327,680 B = 320 KiB.
Demand: 32 × 32,768 = 1,048,576 tokens × 320 KiB = 320 GiB. Impossible as stated, even before weights.
Best case on this hardware: FP8 weights (70 GB) + FP8 KV (160 KiB = 163,840 B per token). Allow ~15 GB for activations and runtime, leaving ~75 GB for KV: 75e9 / 163,840 ≈ 458k tokens, i.e. about 14 users at full 32k, or 32 users averaging ~14.3k tokens.
Recommendation: measure the real context-length distribution (most chats are far below the maximum), cap context or use admission control, run FP8 weights and KV after an accuracy check, and add replicas (data parallelism) or GPUs if the p95 context really is 32k. Tensor parallelism splits both weights and KV heads across the two GPUs (4 KV heads each) and needs NVLink-class bandwidth.
What prompt caching saves on a shared 6,000-token prefix
An assistant sends a 6,000-token system prompt plus tool definitions on every call, followed by a ~300-token user turn. 100 calls arrive within five minutes. Using cache multipliers of 1.25× for a write and 0.1× for a read, estimate the input-cost saving on the prefix, and the compute a self-hosted 8B model avoids.
Without caching: 100 × 6,000 = 600,000 billed prefix tokens.
With caching: first call writes, 6,000 × 1.25 = 7,500; the other 99 read, 99 × 6,000 × 0.1 = 59,400. Total 66,900 token-equivalents, an ≈89% saving on the prefix.
Self-hosted view: prefill costs ≈ 2 × params × tokens = 2 × 8e9 × 6,000 ≈ 9.6e13 FLOPs per request. At an effective 400 TFLOP/s that is ~0.24 s of GPU time and of time-to-first-token per call saved by a prefix-cache hit.
Design consequence: keep the prefix byte-identical. A timestamp or user name injected at the top of the system prompt makes every request a miss. Check the provider’s minimum cacheable length and read the cache-hit fields in the usage response to confirm hits.
What changed recently
Prefix caching for hybrid recurrent-state models
For Kimi K3, whose Kimi Delta Attention layers keep a fixed-size recurrent state between periodic full-attention layers, vLLM caches prefixes by copying that state at chosen boundaries: snapshots at fixed intervals (such as every 32K tokens) plus prompt ends, or only once a prefix is seen twice; the feature is off by default for K3. Block-hash prefix caching does not carry over to recurrent state, so interviewers ask how you would place snapshots and what they cost.
DeepSeek-V4 shrinks KV for million-token contexts
DeepSeek-V4 combines compressed attention (token groups summarised at 1/4 and 1/128 granularity), top-k sparse selection and a 128-token local window; vLLM estimates about 9.6 GiB of bf16 KV per sequence at 1M tokens versus about 84 GiB for a V3.2-style stack, and the V4 paper reports V4-Pro needing 10% of V3.2’s KV cache at that length. The per-token formula 2 × layers × kv_heads × head_dim no longer describes frontier models, so expect architecture-specific capacity questions.
FP8 KV cache: a long-context accuracy trap and a break-even point
vLLM found that FP8 attention on Hopper dropped 128k needle-in-a-haystack accuracy from 91% to 13% because of imprecise accumulation over long contexts; two-level FP32 accumulation restored 89% at some prefill cost. Even after the fixes, single-request decode with FP8 KV only beat BF16 above roughly 7k tokens for Llama-3.1-8B on an H100. ‘Quantise the KV cache’ now needs long-context evals and a context-length threshold in the answer.
LMCache: a KV layer outside the GPU
LMCache stores KV caches from vLLM and SGLang in CPU memory, local storage or remote stores and shares them across requests and engines, serving both prefix reuse and prefill/decode transfer, with up to 15× throughput reported on multi-round QA and document analysis. KV caches are now a managed data tier with eviction, transfer bandwidth and hit-rate trade-offs.
Mooncake wins FAST '25 with KV-centric disaggregation
Moonshot AI’s Mooncake, the serving platform behind Kimi, separates prefill and decode clusters and pools the cluster’s under-used CPU, DRAM, SSD and NIC resources into a distributed KV cache with a cache-aware scheduler, handling 115% more requests on A800 and 107% more on H800 clusters in production. It is the canonical citation for trading storage for recomputation in long-context serving.
Pitfalls
- Saying the cache stores queries or attention scores; it stores keys and values per layer and KV head.
- Sizing the cache with the number of query heads, or forgetting the factor of 2 for K and V or the layer count.
- Estimating cache size from parameter count; it is set by layers × kv_heads × head_dim, so similar-sized models can differ several-fold.
- Assuming every user sits at maximum context, or mixing GB and GiB in capacity sums.
- Believing the KV cache speeds up prefill of a new prompt; only cross-request prefix caching avoids recomputing a shared prefix.
- Confusing prompt/prefix caching (exact token prefix, same output distribution) with semantic response caching (similar query, reused answer).
How interviewers probe it
- Give a config and ask for the cache size at a stated context and concurrency; then ask what changes with FP8 KV, GQA or a 128k window.
- Why is decode memory-bandwidth-bound, and why does batching help weights but not KV reads?
- Explain PagedAttention: the fragmentation problem, block tables, copy-on-write for beams and shared prefixes.
- How would you structure prompts and tools to maximise provider cache hits, and how do you verify hits in production?
- Coding follow-up: add a KV cache to a generation loop and prove it matches full recomputation (position offsets, causal mask, compare logits within tolerance in eval mode).
- Compare MQA, GQA and MLA for quality, cache size and serving complexity; why did most open-weight models adopt GQA?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Compare multi-head, multi-query and grouped-query attention, and latent attention if you know it. Why did most recent open-weight models adopt GQA, and what does it change when you serve the model?
Model answer, written in a candidate's voice
- MHA: every query head has its own K/V; MQA: one shared K/V for all query heads; GQA: query heads grouped, each group shares one K/V
- KV cache size scales with number of KV heads, so GQA cuts cache memory and per-token decode bandwidth
- MQA is cheapest but can hurt quality; GQA is the quality/efficiency compromise; MHA checkpoints can be up-trained/distilled into GQA
- MLA/latent attention caches a compressed low-rank latent per token and expands it at compute time, shrinking cache further at the cost of extra projections
- Serving: smaller cache means more concurrent sequences and longer contexts; under tensor parallelism KV heads must divide across GPUs or be replicated
What is stored in the KV cache and why does it exist? Estimate the cache memory for a model with 32 layers, 8 KV heads and head dimension 128, in bf16, serving 16 concurrent requests at 8k tokens each.
Model answer, written in a candidate's voice
- Stores each layer’s K and V tensors for all previous tokens so decode computes only the new token’s projections
- Per token: 2 x 32 layers x 8 KV heads x 128 dims x 2 bytes = 131,072 B = 128 KiB
- Per 8k-token sequence ~1 GiB; 16 concurrent sequences ~16 GiB, on top of weights
- Concurrency x context is bounded by memory left after weights; decode is memory-bandwidth-bound because every step reads weights plus cache
- Mitigations: GQA/MQA, KV quantisation (FP8/INT8), paged allocation, prefix sharing, sliding-window/eviction/offloading
What problem does PagedAttention solve, and how does it enable prefix sharing?
Model answer, written in a candidate's voice
- Contiguous per-request KV reservations waste memory and fragment the cache, capping batch size.
- Fixed-size KV blocks plus a per-request block table allocate memory on demand, like virtual memory.
- Shared prefixes are referenced by multiple sequences; copy-on-write splits blocks only when they diverge.
- Block hashes enable automatic prefix caching and reuse across requests.
- Larger batches improve throughput; block size trades metadata/lookup overhead against internal fragmentation and sharing granularity.
You have finished this topic.
Reading
- Transformer Inference ArithmeticThe canonical back-of-envelope treatment of KV memory, capacity and memory- vs compute-bound latency.
- Efficient Memory Management for Large Language Model Serving with PagedAttentionOrigin of paged KV allocation and copy-on-write prefix sharing in vLLM.
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsDefines grouped-query attention and shows how to uptrain it from a multi-head model.
- Fast Transformer Decoding: One Write-Head is All You NeedThe multi-query attention paper; frames decoding cost as memory traffic.
- DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language ModelRead the multi-head latent attention section for the low-rank KV compression design.
- Automatic Prefix Caching (vLLM design docs)Concise description of block hashing and LRU eviction for cross-request prefix reuse.
- Prompt caching (Claude API docs)A concrete hosted prompt-caching contract: prefix rules, TTLs, pricing multipliers and minimum lengths.
- The State of FP8 KV-Cache and Attention Quantization in vLLMReal numbers on FP8 KV: a long-context accuracy collapse traced to accumulation precision, its fix, and the context length below which BF16 is faster.
Practise this topic
- Compare multi-head, multi-query and grouped-query attention, and latent attention if you know it. Why did most recent open-weight models adopt GQA, and what does it change when you serve the model?
- What is stored in the KV cache and why does it exist? Estimate the cache memory for a model with 32 layers, 8 KV heads and head dimension 128, in bf16, serving 16 concurrent requests at 8k tokens each.
- What problem does PagedAttention solve, and how does it enable prefix sharing?
- How do provider prompt caching and self-hosted prefix caching work, how do you structure prompts to benefit, and how is a semantic response cache different?
- Will a 70B dense model serve 32 concurrent users at 32k context on two 80 GB GPUs? Explain tensor, pipeline and data parallelism along the way.
- A PyTorch notebook trains a small transformer, but the loss plateaus high and evaluation numbers look wrong. Find the bugs. Follow-up: add a KV cache to its generation loop and prove it matches full recomputation.
- What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually memory-bandwidth-bound, and describe how grouped-query or multi-query attention changes this.
- Write the attention formula. Explain the time and memory complexity in sequence length, why scaling by √d matters, and how a KV cache changes decoding cost.
- What limits LLM decode throughput, and how do continuous batching, paged KV cache, quantisation and speculative decoding help?
- You are asked to serve a hybrid model with 48 layers: 36 Gated DeltaNet (linear-attention) layers and 12 full-attention layers with 2 KV heads of dimension 256. Estimate KV memory per token in bf16, compare it with an all-attention version, and explain what changes for prefix caching.
- Your team serves a large MoE reasoning model with long prompts and long outputs, and p95 inter-token latency spikes whenever big prompts arrive. Someone proposes disaggregating prefill and decode. When does that pay off, what does it cost, and how would you size it?
- A document-QA product re-sends the same 60k-token contract across many sessions spread over hours, so GPU prefix-cache hits are rare. Would you offload KV cache to CPU memory or SSD and reload it instead of recomputing? Show the arithmetic.
- Several 2025–2026 open models mix linear-attention layers (for example Gated DeltaNet or Kimi Delta Attention) with a minority of full-attention layers. Explain the design, its training and serving trade-offs, and how you would choose the ratio.
- Compare DeepSeek’s Native Sparse Attention and DeepSeek Sparse Attention (in V3.2-Exp). What does each make sparse, where does the speed-up come from, and how would you check that long-context quality survived?
- You are moving about 3,000 concurrent coding agents from a managed API to a self-hosted open model served with vLLM on Kubernetes. Why does a standard Kubernetes Service balance this traffic badly, and what would your routing, scheduling and model-upgrade design look like?
- You must serve a DeepSeek-style mixture-of-experts model (hundreds of billions of parameters, 256 routed experts, MLA attention) for an agentic coding product. Explain why the large public deployments since 2025 use disaggregated prefill and decode with wide expert parallelism and data-parallel attention rather than tensor parallelism, and what new failure modes this design introduces.
- Qwen3-Next and Qwen3.5 follow every three Gated DeltaNet (linear-attention) layers with one gated full-attention layer. What does a linear-attention layer keep instead of a KV cache, what is it bad at, and why ship a 3:1 hybrid rather than a fully linear model?