Topic 29 of 62 · Generating and serving
KV cache and head sharing
MediumWhy can decoder attention reuse past keys and values during generation, and how do you size the KV cache?
1 · Start with the intuition
In a causal Transformer with frozen weights, earlier tokens never attend to later tokens—so appending token t+1 does not change the hidden states, keys, or values of tokens 1…t. Instead of recomputing projections for the entire prefix on every decode step, we store each past token’s key (K) and value (V) vectors in GPU memory (the KV cache). Only the newly generated token needs a query, key, and value projection; its query then attends over the cached K and V.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Prefill the prompt
Process all prompt tokens in parallel and write their K and V tensors for every layer into the KV cache.
Next, we will look at: Project & append 1 token. Move on when this operation makes sense.
Visualizing the behavior
KV cache for one 4,096-token sequence (32 layers, head dim 128, BF16)
DerivedCache grows linearly with cached tokens
Derived- MHA-32 (512 KiB/token)
- GQA-8 (128 KiB/token)
- MQA-1 (16 KiB/token)
3 · The governing equation
KV cache bytes = 2 × L × B × S × H_kv × d_head × bytes_per_element MHA: H_kv = H_q GQA: 1 < H_kv < H_q MQA: H_kv = 1
Notation: The factor of 2 counts K and V; L is layers, B is batch size, S is cached sequence length, H_kv is the number of key/value heads per layer, and d_head is the dimension per head.
Notice what is absent from the formula: query heads H_q, FFN width, and vocabulary size. Queries are used once at their own position and discarded, so Grouped-Query Attention (GQA) and Multi-Query Attention (MQA) shrink the KV cache by sharing each K/V head across a group of H_q / H_kv query heads. While caching eliminates O(S²·d²) projection recomputation across a generated sequence, every decode step still has to read all cached K and V bytes from HBM—making long-context decoding both a memory-capacity and a memory-bandwidth bottleneck.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)Worked example · Size a serving deployment around the cache
You must serve an 8B GQA decoder on one 80 GB GPU. Product wants 32K-token context. Decide how many concurrent sequences you can promise and what limits you next.
32 layers · 8 KV heads (32 query heads) · head width 128 · bf16 weights and cache · 1 GB = 1e9 bytes · assume 3.35 TB/s HBM bandwidth
- 01
What is fixed before any request arrives?
Weights are resident for every request, so they come off the top. 8e9 parameters × 2 bytes ≈ 16 GB. Activations, workspace, and allocator fragmentation also need room; reserve about 8 GB rather than planning to the last byte.
Cache budget ≈ 80 − 16 − 8 = 56 GB.
Next question: What does one cached token cost? Read the next part of the worked explanation when you are ready; you do not need to guess first.
5 · Common misconception to avoid
Using the total number of query heads H_q instead of H_kv when sizing a GQA model’s cache, or assuming that quantizing model weights to 4-bit automatically makes the KV cache 4-bit (weight precision and KV cache precision are configured separately).
In practice · implementation & engineering rule of thumb
Write a 3-line helper to compute per-token KV bytes for any model card before provisioning GPUs: 2 * layers * kv_heads * head_dim * dtype_bytes.
def kv_cache_gb(layers, kv_heads, head_dim, seq_len, batch_size=1, bytes_per_elem=2):
bytes_per_token = 2 * layers * kv_heads * head_dim * bytes_per_elem
return (bytes_per_token * seq_len * batch_size) / (1024 ** 3)Go one level deeper
Follow-ups that often come after a correct first answer.
- Size capacity from the per-token cost
- Per token: 2·L·H_kv·d_head·bytes = 128 KiB for the GQA-8 config. With 40 GiB left after weights, that is about 327,680 cached tokens across every concurrent sequence. Divide by the expected context length to get the maximum batch.
- Shrinking KV further
- Options include quantizing the cache (FP8/INT8), sliding-window attention for some layers, sharing KV across layers, and low-rank latent KV as in DeepSeek-V2’s MLA. Each trades memory for possible quality loss, so validate on long-context tasks.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumCan two requests that share a 4,000-token system prompt share the same KV cache blocks for that prefix?
Show follow-up reasoning
Yes, provided the model weights, token IDs, and positional indices are identical from index 0 through 3,999. Paged serving engines like vLLM and SGLang hash prefix blocks and use copy-on-write reference counting so multiple requests can read the shared system-prompt KV blocks without recomputing or duplicating them.