LearnTopic guide

KV cache

During autoregressive decoding a transformer stores the key and value vectors of every past token in every layer, so each new token only computes its own projections and attends over the stored ones. The cache turns per-step attention from recomputing the whole prefix into a single read, but it grows linearly with context length and concurrency and usually becomes the binding constraint on how many users a GPU can serve. Interviewers use it to test whether you can do capacity arithmetic from a model config, explain why decode is memory-bandwidth-bound, and reason about GQA/MLA, paged allocation, prefix and prompt caching, and KV quantisation.

Applied LLM · ML engineering · Research8 key concepts17 questions

Start: Key concepts 6 lessons · about 18 min
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

How the KV cache fills during generationA prompt enters prefill, which writes K and V for every prompt token into the KV cache. In the decode loop, the new token computes only its own projections, appends its K and V to the cache, attends over the whole cache and produces the next token, which loops back as the new token.Promptone parallel passPrefillwrites the cacheKV cacheK and V per layer and KV headDecode stepnew token onlyNext tokenbecomes the new tokenwrite K/Vappend K/Vreadproducenext token123InputPrefillMemoryDecode
  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.

Prefill writes K and V for every prompt token in one parallel pass, then each decode step appends one token's K and V and reads the whole cache.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1PrefillPrefill processes the prompt in one parallel pass and writes K and V for every prompt token to the cache.
2Decode stepEach decode step computes only the new token's own projections, appends its K and V to the cache and reads the whole cache.
3LoopThe produced next token becomes the new token of the next decode step.

Source: This page's text

Boxes
BoxGroupDetail
PromptInputone parallel pass
PrefillPrefillwrites the cache
KV cacheMemoryK and V per layer and KV head
Decode stepDecodenew token only
Next tokenDecodebecomes 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 = 2 × Layers × KV heads × Head dim × Bytes per element

Bytes per sequence = Bytes per token × Tokens per sequence

Total KV bytes = Bytes per token × Tokens per sequence × Concurrent sequences

Worked cases
CaseLayersKV headsHead dimBytes per elementTokens per sequenceConcurrent sequencesBytes per tokenBytes per sequenceTotal KV bytes
8B-class GQA, 16 users at 8k32812828,19216128 KiB1 GiB16 GiB
Same load, 32 KV heads323212828,19216512 KiB4 GiB64 GiB
70B bf16, 32 users at 32k808128232,76832320 KiB10 GiB320 GiB
Bytes per token, per sequence and in total for a given layer, KV-head and head-dim configuration.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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

KV cache per token across attention variantsThree side-by-side variants show 32 query heads each, linked down to 32, 8 and 1 KV heads respectively. The highlighted grouped-query variant uses 8 KV heads and is the recommended middle ground.Multi-head attention32 KV headsQuery heads · 32KV heads · 32KV cache per token512 KiBGrouped-query8 KV headsQuery heads · 32KV heads · 8KV cache per token128 KiBMulti-query1 KV headQuery heads · 32KV heads · 1KV cache per token16 KiB
KV cache per token across attention variantsThree side-by-side variants show 32 query heads each, linked down to 32, 8 and 1 KV heads respectively. The highlighted grouped-query variant uses 8 KV heads and is the recommended middle ground.Multi-head attention32 KV headsQuery heads · 32KV heads · 32KV cache per token512 KiBGrouped-query8 KV headsQuery heads · 32KV heads · 8KV cache per token128 KiBMulti-query1 KV headQuery heads · 32KV heads · 1KV cache per token16 KiB
For 32 query heads, GQA with 8 KV heads cuts the per-token cache to 128 KiB, versus 512 KiB for multi-head attention and 16 KiB for multi-query attention.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Variants
VariantQuery headsKV headsKV cache per token (bytes)Computed as
Multi-head attention3232524,2882 × 32 × 32 × 128 × 2
Grouped-query328131,0722 × 32 × 8 × 128 × 2
Multi-query32116,3842 × 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

  1. Each decode step reads the entire KV cache of every sequence in the batch.

  2. Offloading to CPU memory trades capacity for transfer latency.

  3. SSD tiers trade capacity for transfer latency; LMCache stores KV in local storage.

  4. LMCache shares KV across requests and engines; Mooncake pools CPU, DRAM, SSD and NIC resources into a distributed KV cache.

The KV cache moves from GPU memory to CPU memory, local storage or SSD, and remote or pooled stores, trading capacity for transfer latency.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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.

Next: Worked examples Lesson 3 of 6 · about 4 min

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.

Next: What changed Lesson 4 of 6 · about 3 min

What changed recently

  1. 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.

    Source

  2. 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.

    Source

  3. 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.

    Source

  4. 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.

    Source

  5. 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.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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?
Next: Quiz Lesson 6 of 6 · about 3 min

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.

  1. Question 1 of 3 · Applied LLM · Technical · Medium

    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?

  2. Question 2 of 3 · Applied LLM · Technical · Medium

    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.

  3. Question 3 of 3 · Applied LLM · Technical · Hard

    What problem does PagedAttention solve, and how does it enable prefix sharing?

Reading

Practise this topic

  1. 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?Applied LLM · Technical · Medium
  2. 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.Applied LLM · Technical · Medium
  3. What problem does PagedAttention solve, and how does it enable prefix sharing?Applied LLM · Technical · Hard
  4. 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?Applied LLM · Technical · Medium
  5. 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.Applied LLM · Technical · Hard
  6. 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.Applied LLM · Coding · Hard
  7. 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.Research · Technical · Hard
  8. 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.ML engineering · Technical · Hard
  9. What limits LLM decode throughput, and how do continuous batching, paged KV cache, quantisation and speculative decoding help?ML engineering · Technical · Hard
  10. 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.Applied LLM · Technical · Hard
  11. 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?Applied LLM · System design · Hard
  12. 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.Applied LLM · Technical · Hard
  13. 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.Research · Technical · Hard
  14. 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?Research · Technical · Hard
  15. 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?ML engineering · System design · Hard
  16. 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.ML engineering · System design · Hard
  17. 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?Research · Technical · Hard

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.