Module 7 · AI infrastructureLesson 78 of 887 minAdvanced

The KV cache

When a model generates text, each new token looks back at all earlier ones. The KV cache saves that earlier work so it isn't redone for every token.

Try it

Generate with the KV cache off and watch the computations pile up as the text grows. Then turn it on and compare.

Language models generate text one token at a time. To choose each new token, the model's attention layers look back at every earlier token using two vectors per token per layer: a key and a value.

Without a cache

At step 100, the model would recompute keys and values for all 99 earlier tokens, even though they haven't changed. Over a whole answer, the total work grows with the square of the length. Long answers would be painfully slow.

With a KV cache

  1. During prefill, the model computes keys and values for every prompt token and stores them.
  2. At each decode step, it computes them only for the newest token, appends them to the cache, and reads the rest.

Work per step stays small, so generation is fast.

The memory bill

The cache has to live in GPU memory for the whole conversation:

2 (K and V) x layers x hidden size x bytes x tokens

For a 7B-class model in 16-bit that's around 0.5 MB per token. A 4,000-token conversation is about 2 GB, per user. Multiply by dozens of concurrent users and the cache can exceed the model's own size.

Shrinking it

  • Grouped-query / multi-query attention: models designed with fewer key-value heads, cutting the cache several times over (many recent models do this).
  • Quantized KV cache: store it in 8 bits.
  • Paged allocation: don't reserve memory you won't use (vLLM, coming up).
  • Prefix caching: share the cache for a common system prompt across requests.
  • Offloading: move idle conversations' caches to CPU memory or disk.

Quick check

What's the main cost of using a KV cache?