All glossary terms

Serving

KV cache

The model's running notes on text it has already read, kept so each new token reuses them. It grows with context length and caps how many users one GPU holds.

A language model reads a conversation token by token. Before it predicts the next token, every layer computes a key and a value vector for each word so far, which is what lets attention look back at earlier text. Those keys and values are the KV cache. If the model kept recomputing them for every new token, a 5,000-token conversation would redo the work of all 5,000 tokens on every single step, and nobody would get an answer.

So servers keep the cache in GPU memory and only compute the key and value for each new token as it arrives. That is the good news and the bad news. The good news: the tenth token of a long reply costs about the same compute as the first. The bad news: the cache grows without bound as the conversation grows, and it has to stay resident for as long as the user might send another message.

The size per token is fixed by the model shape: two vectors (a key and a value) for every layer and every key-value head, times the bytes per element. Multiply that by the context length and you get the memory a single conversation occupies. A 40,000-token context on a typical large model can hold more memory than the model weights themselves.

That is why KV memory, not model size, usually decides how many users one GPU can host. Interviewers like this point because it separates people who think of the model as the only resident data from people who have actually sized a serving stack. Related mechanics: paged-attention for how the cache is allocated, and the roofline-model for why its reads also cost time.

A worked example

Ten users on one 80 GB card, where the model and other allocations leave about 9 GiB free for the KV cache. The model has 40 layers, 8 key-value heads of 128 dims each, and a 16-bit KV cache.

  1. Per token: 2 (a key and a value) x 40 layers x 8 heads x 128 dims x 2 bytes = 163,840 bytes, which is 160 KiB.
  2. One user at 4,096 tokens of context: 160 KiB x 4,096 = 640 MiB.
  3. Ten concurrent users: 640 MiB x 10 = 6,250 MiB, which is 6.25 GiB of cache.
  4. With about 9 GiB free for the cache, the card hosts 9 / 0.625 = about 14 such users, and the fifteenth is the one that fails.

The KV cache is the concurrency ceiling. Weights fit once; cache fits per user, and it scales with the context you allow.

Where this shows up

Test yourself

Related terms