Forward Deployed EngineeringAI EngineeringLLM Inference
KV-caching in autoregressive decoding: what does it store, why does it cut latency, and how does its memory cost scale?
Question 70 of 73 · Updated
On this page
Interview-ready answer#
A KV cache stores the attention keys and values of previously processed tokens, separately for each Transformer layer. During autoregressive generation, the next token needs to attend to the preceding tokens, but their keys and values do not need to be calculated again under standard causal attention.
Instead of running the entire growing sequence through the model for every generated token, the inference engine processes the new token, appends its K/V tensors and uses its query to attend to the cached history.
This reduces redundant computation and usually improves decoding latency. The trade-off is GPU memory: KV-cache size grows linearly with the number of retained tokens, active sequences, layers, KV heads and head dimension.
1. What actually happens during inference?#
The decode operations shown are conceptual: each Transformer layer has its own cache and performs its own attention. Prefill produces the logits for the first generated token; processing that sampled token on the next forward pass adds its state to the cache.
Queries from earlier tokens are not normally cached because future tokens need their keys and values, not their old queries. The KV cache is also not a cache of model weights or final answers.
Why latency improves: for a prefix of length t, naive full-sequence recomputation performs attention over approximately t² token pairs per layer on each step. Cached decoding evaluates the new query against t retained positions, so the attention work per new token is approximately O(t), for fixed head dimensions. It also avoids repeating the earlier tokens' projections and feed-forward computations. Prefill itself still requires computation, and the cache does not eliminate attention to history.
2. How much memory does it use?#
For a conventional decoder with uniform full-attention layers, each layer stores two tensors with logical shape:
[batch size, KV heads, cached sequence length, head dimension]
Physical layouts may differ across inference engines.
For B equal-length active sequences, each with T cached tokens:
- 2: keys and values.
- L: number of layers; Hₖᵥ: number of KV heads per layer.
- D: dimension of each key/value head.
- S: bytes per stored element (2 for FP16 or BF16).
For unequal sequence lengths, replace B × T with the sum of all retained sequence lengths, assuming no shared blocks. This estimates raw tensor storage, not total GPU allocation.
Worked example: a 32-layer model#
Assume 32 query heads, head dimension 128, BF16 cache and an 8,192-token sequence.
| Attention design | KV heads | Cache per token | Cache at 8,192 tokens |
|---|---|---|---|
| Multi-head attention (MHA) | 32 | 512 KiB | 4 GiB |
| Grouped-query attention (GQA) | 8 | 128 KiB | 1 GiB |
| Multi-query attention (MQA) | 1 | 16 KiB | 128 MiB |
For GQA, the calculation is 2 × 32 × 8 × 128 × 2 = 131,072 bytes per token. Multiply by 8,192 to obtain exactly 1 GiB. Eight independent sequences of that length need 8 GiB of raw GQA cache, before model weights, temporary buffers, allocator overhead or other runtime memory.
The arithmetic was locally checked against NumPy tensor byte counts: all 410 checks passed, including varied lengths, data types, head counts and these worked examples. No implementation code is needed to understand the sizing formula.
3. Why GQA and MQA matter#
MHA gives every query head its own K/V heads. GQA shares one K/V head among a group of query heads. MQA shares a single K/V head across all query heads.
For the same model dimensions, eight KV heads rather than 32 reduce raw cache storage by 4×. This can support more simultaneous users or longer contexts and reduce KV memory traffic. However, attention still has multiple query heads, so a 4× smaller cache does not guarantee a 4× speedup. GQA is a common compromise between cache efficiency and model quality; the architecture must support it, rather than merely dropping heads from an existing checkpoint.
4. Practical FDE considerations#
- Long contexts: every new token may read a growing cache. Decoding can become memory-bandwidth limited even when the cache fits in GPU memory.
- Concurrent users: budget for the sum of active prompt and generated tokens. Paged allocation helps reduce waste and supports sharing, but does not eliminate the memory needed for unique retained tokens.
- Lower precision and limited attention windows: KV quantization can reduce storage with possible quality or performance trade-offs. Sliding-window attention limits retained history only where the architecture supports that behavior.
- Capacity planning: measure time to first token, time per output token, throughput and actual peak GPU memory. Include weights, workspace, cache-block rounding and parallelism layout. Do not use the raw KV formula as a complete VRAM estimate.
The important interview distinction: KV caching avoids recalculating past token states, but it does not make long-context decoding constant-time. FDE-0063 covers reuse across conversation turns; here the focus is the per-token computation and memory cost inside inference.
References
- 1.
- 2.
- 3.
- 4.Hugging Face Transformers — KV cache (not live-verified)huggingface.co
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models