Building a Fast Key-Value Cache for LLM Token Generation
Machine LearningModel answerLast updated
Explain and design a per-layer key/value cache for decoder-only LLM generation, covering batching, branching, long contexts, memory and kernel performance, precision, and common correctness bugs.
You are building the token-generation path of a decoder-only Transformer that serves many users at once. Generating token by token is wasteful unless earlier work is reused, so the system keeps a key/value cache.
Answer the following as you would in a design discussion.
-
Concept. What is the key/value cache? Which tensors are stored for each layer, and how does the work done per generation step change compared with having no cache?
-
Design. Outline how you would implement the cache so that it handles:
- batches whose sequences have different lengths,
- branching sequences, as in beam search or speculative decoding,
- very long contexts (roughly 32k to 128k tokens).
-
Performance. Discuss:
- memory layout, and the cost of writing and reading when new keys and values are appended,
- how to avoid reallocating or copying the cache,
- how the cache works with fused attention kernels of the FlashAttention family,
- the numeric precision of the stored cache (fp16, bf16, int8).
-
Pitfalls. Which bugs and correctness traps commonly appear when a cache is added (masking, rotary position encodings, shape mismatches, and so on)?
State any assumptions about model size and traffic, and include rough memory numbers where they help your argument.
Hints
Hint 1
Work out the cache size per token from layers, KV heads, head dimension and bytes per element, then scale it to 32k and 128k contexts. This shows why memory, not compute, is the limiting resource.
Hint 2
Think about branching as an ownership problem: if branches share a long common prefix, how can they share storage and only copy what they modify? Also ask what a rollback of rejected speculative tokens should cost.
Hint 3
For correctness, ask which values must be computed once and never changed (what exactly is cached, and at what stage relative to position encoding), and which absolute positions the new token and the mask must use at each step.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and sizing
Assume a decoder-only model of about 8B parameters: 32 layers, 32 query heads, 8 KV heads (grouped-query attention), head dim 128, bf16 cache. Serving is online with continuous batching, mixed prompt lengths from 32k to 128k, and decoding modes including greedy, sampling, beam search and speculative decoding. The goal is high tokens/s per GPU under an inter-token latency target of about 50 ms at p99.
Cache bytes per token = 2 (K and V) x layers x KV heads x head dim x bytes = 2 x 32 x 8 x 128 x 2 = 128 KB. That is about 4 GB for a 32k context and 16 GB for 128k. With full multi-head attention (32 KV heads) it would be four times larger. The cache, not the weights, caps batch size and context length, so each design choice below tries to waste less of it or read it faster.
2. What the cache is
Under a causal mask, a token's key and value depend only on that token and its predecessors, so once computed they never change. Recomputing them at every step is pure waste.
Stored per layer: K and V, each shaped [batch, kv_heads, seq, head_dim]. K is stored after the projection and after rotary embedding is applied. Queries are not cached, because each query is used exactly once.
Computation change:
- Prefill. Process the whole prompt in one pass with causal attention (compute-bound, quadratic in prompt length) and write all K and V to the cache.
- Decode step. Compute q, k, v only for the newest token, append k and v, and attend one query against all cached keys. Attention costs O(t x d) per step instead of recomputing the whole prefix. Without a cache, total attention work over a generation grows cubically in length; with it, quadratically.
- Bottleneck shift. Decode becomes memory-bandwidth-bound: each step streams the weights and the whole cache to emit one token per sequence. Batching amortizes weight reads, but cache reads grow with total tokens in the batch.
3. Design
Use a paged cache (the PagedAttention idea):
- Preallocate one pool per layer, shaped
[num_blocks, 2, block_size, kv_heads, head_dim], with a block size around 16 tokens. - Each sequence has a block table mapping logical blocks to physical ones, plus its length. Each physical block has a reference count.
- Operations:
allocate,append,fork,truncate,free. - Per step, pass the kernel a
slot_mapping(where each new token's K/V goes), sequence lengths, and block tables.
Variable lengths. Do not pad to [B, max_len]. Pack all new tokens into one flat dimension and use a variable-length attention kernel with cumulative sequence lengths and block tables. Under continuous batching, sequences enter and leave at every step and finished ones release blocks immediately. Chunked prefill splits long prompts so they do not stall decode latency for others.
Beam search. fork copies the block table and increments reference counts, so the shared prompt is never duplicated. If a beam writes into a shared, partly filled last block, copy-on-write that one block. Beam reordering becomes a permutation of block tables rather than an index-select over gigabytes. Prefix caching uses the same mechanism: hash full blocks of a shared system prompt and reuse them.
Speculative decoding. The draft model proposes k tokens and the target verifies them in one pass, writing k entries. If only j are accepted, truncate to the accepted length: this is just a length update, stale slots are overwritten later, and unused blocks are freed. The draft model's cache must be rolled back identically.
Long contexts.
- Shrink the cache with GQA/MQA (4-8x) and KV quantization.
- Use split-K decoding (FlashDecoding-style): with one query and a very long key sequence, parallelize across sequence chunks and merge partial softmax results, otherwise the GPU idles.
- Shard KV heads with tensor parallelism; for very long prompts use sequence/context parallelism (e.g. ring attention) in prefill.
- Quality-trading options: sliding-window layers, attention sinks plus a recent window, or offloading cold blocks to CPU with prefetch.
4. Performance
Layout and writes/reads. Keep head_dim innermost and contiguous for coalesced loads, and keep a head's data contiguous within a block so a thread block reads one tile. Appending is a scatter of new K/V into slot positions; fuse it into the RoPE or QKV-projection kernel to avoid an extra trip through HBM. Reads dominate: at 128k context each step streams about 16 GB per sequence, with arithmetic intensity near 1 FLOP/byte, so attention runs at memory bandwidth.
No reallocation or copies. Never grow the cache with concatenation: it copies everything each step, giving quadratic total traffic. Preallocate the pool once (for example ~90% of memory left after weights and activations). Paging bounds waste to one partial block per sequence rather than reserving max length. Stable addresses also allow CUDA Graph capture of decode steps per batch-size bucket, removing launch overhead.
Fused kernels. FlashAttention-style tiling with online softmax is ideal for prefill since it never materializes the T x T score matrix. For decode, the kernel must read K/V through the block table, handle query length 1 (or k for verification), and use split-K. Dequantization of low-precision K/V must happen inside the kernel's load path; dequantizing into a temporary tensor throws away the bandwidth savings.
Precision.
| Format | Size vs bf16 | Notes |
|---|---|---|
| bf16/fp16 | 1x | Safe default; bf16 avoids overflow |
| fp8 | 0.5x | Per-tensor or per-head scales; small quality loss |
| int8/int4 | 0.5x/0.25x | Needs fine-grained scales; keys have outlier channels, so quantize K per channel and V per token; validate on long-context tasks |
Always accumulate attention in fp32 regardless of storage format.
5. Common bugs
- Wrong positions. The new token must use its absolute position for RoPE. Restarting at 0, or mis-offsetting after truncation or with left padding, silently degrades output.
- Caching K before RoPE (then rotating again at read time), or rotating twice.
- Mask errors. With q_len = 1 no causal mask is needed, but for chunked prefill or speculative verification (q_len = k) the mask must be offset by the cached length. Padding positions must be masked out.
- Shape mismatches with GQA: cache stores KV heads, not query heads; expand or group at read time, not in storage.
- Stale entries after rollback: length updated but readers still use the old length, or a shared block mutated without copy-on-write, corrupting sibling beams.
- Reference-count leaks or double frees, causing pool exhaustion or cross-request contamination.
- Cache not reset between requests, or slot mapping off by one.
- Numerics: fp16 overflow, missing quantization scales, or low-precision softmax accumulation.
A good validation: compare cached incremental decoding against a full no-cache forward pass and require near-identical logits at every step, including with forks and rollbacks.