What is the KV cache in transformer inference?
Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
The KV cache stores the keys and values of every prior token so each new decode step only needs one new K and V, turning O(n^2) attention into O(n) per step.
Imagine writing a long essay where every sentence has to reference all previous sentences. Without notes, you would reread the whole essay before writing each new sentence. The KV cache is your scratchpad, you jot down a short note for every sentence you have already written (the key) and a copy of its content (the value). When writing the next sentence, you just glance at the notes instead of rereading. Each new sentence only adds one row to the scratchpad. Reading gets faster as the essay grows, because the work per new word stays small even though the essay gets long.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
3 min: prefill versus decode + what's cached (K, V) + cache size formula with num_layers + GQA and MLA + paged attention serving.
Real products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Saying the KV cache stores Q (queries) or attention weights. Past Qs are never reused, and weights are recomputed every step; only K and V from prior tokens persist.
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.