KatInterview

Why LLM Servers Store Past Keys and Values During Decoding

Machine LearningModel answer
MediumModel answerMachine Learningtransformersllm-inferencekv-cache

Last updated

Describe how attention-state caching works in decoder-only LLM serving: what is stored, why it speeds up generation, memory costs, and the production techniques that manage it.

You are reviewing the serving stack for a decoder-only language model that generates text one token at a time (causal self-attention) on GPUs. A colleague asks why the server keeps a large block of GPU memory for "past keys and values" for every active request, and whether it is worth the cost.

Give a systems-level explanation of this mechanism, the key-value (KV) cache.

Notation

  • $L$: number of layers
  • $B$: batch size
  • $P$: prompt length
  • $S$: current sequence length (prompt plus generated tokens)
  • $n_q$: number of query heads
  • $n_{kv}$: number of key/value heads
  • $d_h$: per-head dimension

Your answer should cover

  1. What is stored. Which tensors are kept, their rough shapes, and which parts of the network hold them.
  2. Why it helps. What redundant work it removes during autoregressive generation, and how the asymptotic cost changes.
  3. Prefill vs. decode. How processing the prompt differs from producing tokens one by one, and how the performance profile of each phase differs.
  4. Trade-offs and pitfalls. Memory growth, batching requests of different lengths, MHA vs. MQA vs. GQA, consistency of positional information, and very long contexts.
  5. Optimizations. At least two techniques used by real serving systems, with the mechanism behind each (for example paged attention, KV quantization, sliding-window or streaming attention, GQA).

Assumptions

  • This is inference only: weights are frozen and there is no backward pass.
  • "Production" means a multi-tenant system with many concurrent requests of different lengths, not a single-sequence demo script.
  • You may state and justify any scoping assumptions you need, such as the positional scheme (RoPE, learned absolute, ALiBi), the optimization target (time-to-first-token, per-token latency, or concurrency), and typical context lengths.

Hints

Hint 1

Ask which quantities in attention depend on earlier tokens and which depend only on the newest token. Think about which of Q, K, V must be reused at each later step.

Hint 2

Separate the cost of projecting a token into K and V from the cost of scanning all cached keys. The cache removes the first kind of repeated work but not the second. Then compare arithmetic intensity in the prompt pass with that of a single-token step.

Hint 3

Write the memory formula as 2 x L x B x S x n_kv x d_h x bytes_per_element, and note what each term lets you change: GQA lowers n_kv, quantization lowers bytes, a sliding window caps S, and paged allocation reduces waste from fragmentation.