KV Cache and Incremental Decoding
⚡ What is a KV cache? When a language model generates text, each new token attends to every token before it. The keys and values of those earlier tokens never change, so instead of recomputing them at every step, the model stores them in a cache and computes keys and values only for the new token. Generation then costs one token's work per step instead of the whole prefix's.
It is the standard next question after causal attention or decoding: once you can generate, the interviewer asks why generation is slow and how inference servers make it fast.
The Prompt
The cache itself is a few lines, so the interviewer grades whether it is exact (same tokens as without it), the masks and positions for the new tokens, and whether you can reason about memory.
"Here is a small decoder-only model and a greedy generation loop that reruns the whole sequence every step. Add a KV cache so each step only processes the new token, and show the output doesn't change."
Clarifying Questions
You: Does every sequence in the batch have the same prompt length? Padding changes the positions and masks.
Interviewer: Same length for now. We can talk about mixed lengths after.
You: Is the maximum length known up front? Then I can allocate the cache once.
Interviewer: Yes, the model's context length.
You: How are positions encoded? A new token at step t must get position t, not 0.
Interviewer: Learned absolute positions. Same issue as RoPE, so handle the offset.
You: How will you judge "doesn't change"? Exact tokens, or logits within a tolerance?
Interviewer: Same greedy tokens, logits within float tolerance.
What You'll Build
model(idx, caches=None, pos=0) -> (B, T, V): the forward pass, which reads and fills a per-layer cache when given one, for tokens starting at positionpos.ConcatCacheandStaticCache:update(k, v, pos) -> (K, V)returns all keys and values so far,(B, H, pos + T, d_head).generate(model, prompt, n, make_cache=None) -> (B, T + n): greedy decoding, with or without a cache.kv_cache_bytes(...) -> int: the memory a cache needs.