KatInterview

Building a Fast Key-Value Cache for LLM Token Generation

Machine LearningModel answer
MediumModel answerMachine Learningtransformerskv-cachellm-inference

Last 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.

  1. 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?

  2. 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).
  3. 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).
  4. 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.