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.
Theme reported publicly: Mistral AI, Speechmatics
Answer
Model answer, written in a candidate's voice
In short
- 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
In full
The KV cache stores, for every layer, the key and value tensors for all tokens seen so far, so during autoregressive decoding each new step only computes that token’s projections and attends to the cached K/V instead of recomputing the whole prefix. For this model, each token costs 2 (K and V) x 32 layers x 8 KV heads x 128 head dims x 2 bytes (bf16) = 131,072 bytes = 128 KiB. An 8k-token sequence therefore needs about 8192 x 128 KiB = 1 GiB, and 16 concurrent 8k-token requests need roughly 16 GiB of KV cache, excluding weights and activations. That is why concurrency x context is bounded by the memory left after the weights are loaded, and why decode is memory-bandwidth-bound: every generated token reads the weights plus the relevant cache. Common mitigations include GQA/MQA to shrink the number of KV heads, KV quantisation to FP8/INT8, paged allocation to reduce fragmentation, prefix sharing for common prompts, and sliding-window attention, eviction, or offloading to bound the cache—though some of these trade off quality, semantics, or latency rather than eliminating the memory cost.
What a strong answer covers
- Caches each layer’s keys and values for all previous tokens so a decode step only computes the new token’s projections
- Per token: 2 (K and V) × 32 layers × 8 heads × 128 dims × 2 bytes = 131,072 B = 128 KiB. Per 8k-token sequence ≈ 1 GiB; 16 sequences ≈ 16 GiB, on top of the weights
- Concurrency × 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 attention, offloading/eviction
Common mistakes
- Forgetting the factor of two for K and V or the layer count
- sizing the cache from the parameter count