What is the KV cache, and why does it speed up inference?

Learning path, stage 1 of 5: How LLMs work · question 9 of 10

During generation, each new token has to attend to every earlier token. The KV cache stores the attention keys and values already computed for earlier tokens, so each step only computes Q, K and V for the newest token instead of reprocessing the whole sequence.

Why it matters

  • Without a cache, generating n tokens repeats a growing amount of work at every step.
  • With a cache, each step is roughly constant work plus one pass of attention over the stored keys and values.
  • This is why inference has two phases. Prefill processes the prompt in parallel and is compute-bound. Decode produces one token at a time and is memory-bandwidth-bound.

The catch: memory

  • The cache grows with layers × heads × head size × sequence length × batch size. For long contexts it can be larger than the model weights.
  • Ways to shrink it:
    • Multi-query and grouped-query attention share K/V across heads.
    • PagedAttention (vLLM) stores the cache in pages, like virtual memory, so it isn't fragmented.
    • Quantising the cache to 8 or 4 bits.

Link to prompt caching

Provider "prompt caching" uses the same idea across requests. The processed state of a repeated prefix is reused, which is why cached input tokens are cheaper and faster.

Sources

Code example

tsx
1// Toy decode loop showing what the KV cache saves.
2interface KV { keys: number[][]; values: number[][] }
3
4declare function project(token: number, pos: number): { q: number[]; k: number[]; v: number[] };
5declare function attend(q: number[], keys: number[][], values: number[][]): number[];
6declare function nextToken(hidden: number[]): number;
7
8export function generate(prompt: number[], steps: number): number[] {
9 const cache: KV = { keys: [], values: [] };
10 const out = [...prompt];
11
12 // prefill: process the prompt once and fill the cache
13 let hidden: number[] = [];
14 prompt.forEach((t, pos) => {
15 const { q, k, v } = project(t, pos);
16 cache.keys.push(k);
17 cache.values.push(v);
18 hidden = attend(q, cache.keys, cache.values);
19 });
20
21 // decode: one new token per step, reusing every cached K/V
22 for (let s = 0; s < steps; s++) {
23 const t = nextToken(hidden);
24 out.push(t);
25 const { q, k, v } = project(t, out.length - 1);
26 cache.keys.push(k);
27 cache.values.push(v);
28 hidden = attend(q, cache.keys, cache.values);
29 }
30 return out;
31}

To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.

Open in study app