Making the next token cheap: a KV-cache from scratch

Last week I built a GPT-2 forward pass by hand and ended on an embarrassing inefficiency: to
generate each new token, it re-ran the entire model over the entire sequence so far. Token 500
did 500 tokens’ worth of work to produce one word. This week I fixed it — and the fix, the KV-cache,
is the first real piece of inference serving, the thing that sits between “a model that works” and
“a model you can actually run.”

What I built

A cached decoder on top of last week’s model. The insight is almost embarrassingly simple: in
attention, every past token contributes a Key and a Value, and those never change once the
token exists. So compute them once, keep them, and let each new token do O(1) work instead of O(T).

prefill (once):  [ prompt: N tokens ] ──▶ compute K,V for all layers ──▶ fill cache ──▶ token 1
decode (per tok):      [ 1 new token ] ──▶ its Query attends over the cached K,V ──▶ next token ─┐
                            ▲                                                                     │
                            └──────────────────── append its K,V, repeat ◀───────────────────────┘

Same output as last week, token-for-token (that’s the test). The speed, measured:

context recompute everything with the cache
32 tokens 147 ms 105 ms
512 tokens 676 ms 113 ms

Uncached climbs with the conversation; cached stays flat. By 512 tokens it’s ~6× faster, and the
gap only grows.

The concepts that made it work

  • Prefill and decode are two different regimes. The expensive pass over the whole prompt happens
    once (prefill, which fills the cache). After that, every generated token is a cheap one-token
    step. Real serving systems schedule these two phases completely differently — now I see why.
  • The cache is carried state, not a trick. This is the same move as last series’ database:
    instead of recomputing a result, you keep it and carry it forward. The forward pass becomes
    stateful across tokens, and the KV-cache is that state.
  • You trade compute for memory — and memory becomes the real limit. The cache is
    2 × layers × tokens × d_model floats: ~36 MB at 512 tokens for tiny GPT-2, and it grows linearly
    with every token of context. At real model sizes this is what runs out first. It’s why vLLM’s
    PagedAttention manages the cache in pages, like an OS paging virtual memory — the exact same idea,
    one level up the stack.

The thing that bit me

Positional embeddings. In the uncached version I embedded the whole sequence at once — position 0,
1, 2, … Here a new token is not at position 0; it’s at position cache.length(). Miss that
offset and you add position zero’s embedding to every single generated token — so the model thinks
each new word is the first word of the sentence. The tell is nasty and specific: the first
generated token is perfectly correct, and then it drifts into plausible-looking nonsense. I’d never
have trusted “looks fine” here — the only reason I caught it cleanly is that the done-bar pins the
cached output to the uncached one, token for token. A subtle bug that produces readable garbage is
exactly the kind that hides from a human eyeballing the output.

Tradeoffs & the road not taken

  • Memory, deliberately unbounded. My cache just grows; a real system caps context and evicts.
    That’s a feature of the next layer, not this one.
  • No continuous batching yet. The other half of serving throughput is running many sequences at
    once and letting new requests join the batch as others finish — a scheduling problem I’m leaving
    for a focused pass (it’s where a small Go service would earn its place).
  • Still numpy on CPU. This is for understanding the mechanism, not for speed records.

Where this sits in the system

Last week: the forward pass, one token, ending on an O(T²) decode cost. This week: the cache that
removes it — the first brick of inference serving, and a straight line toward how production systems
(paged caches, batching schedulers) are built. Next I change domains and build a vector index for
retrieval. Same spine as always: one system, revealed a layer at a time.


Part of a series building a modern AI stack from scratch, told visually. (Last time: one token, from scratch.)