Start with the same sentence from the first two posts: A triangle has…
The model picks " three". Then it picks " sides". Then ".".
In Why Does the First LLM Token Take Longer?, we saw that prefill processes the prompt and produces the scores for the first output token. Now you’ve just picked " three" and need to decide what comes next. How much work can you reuse from processing A triangle has?
A label and a note for each token
Imagine keeping a stack of index cards as you read. Each card has a label you can match against a question and a note you can use in your answer. When a new question arrives, you can search the same stack and use a different mix of notes.
An attention layer works with three sets of numbers:
- Query (Q): What the current position is looking for.
- Key (K): What the query compares against to score each position.
- Value (V): What that position contributes to the result. A higher score gives its value more weight.
Each new position brings its own query. Earlier queries already did their work. The earlier keys and values still have a job because the new query uses them to decide what information to draw from the sequence. That’s why this is called a KV cache.
Reuse works because of causal attention. Each position can attend only to itself and earlier positions. Appending " three" can’t change what has was allowed to see, so the keys and values already computed for those earlier positions are still valid. Hugging Face guide to the KV cache
Follow the cache through three predictions
These are simplified token boundaries. Watch when each chosen token enters the cache.
Process [A] [ triangle] [ has] → pick " three" Process [ three] → pick " sides" Process [ sides] → pick "." | Prediction | Rebuild every K/V pair | Compute with a cache |
|---|---|---|
Pick " three" | 3 prompt pairs | 3 prompt pairs |
Pick " sides" | 4 pairs | 1 new pair for " three" |
Pick "." | 5 pairs | 1 new pair for " sides" |
| Total pairs computed | 12 | 5 |
On the last row, the model creates one new pair and uses all five for attention. The cache saves the work of running the earlier positions through the model again. The new query still scores the available keys.
Scale that up to a 1,000-token prompt and a 200-token reply. Counting through the prediction of the 200th token, rebuilding the prefix takes 219,900 pair computations per layer and KV head (1,000 + 1,001 + … + 1,199). Caching takes 1,199 (1,000 + 199). Those counts track how many pairs the model computes. The cached pairs are still used during attention.
Verify it in plain Python
A real model computes keys and values from each position’s representation at each layer. In deeper layers, that representation can already contain information from earlier tokens. Causal attention keeps later tokens from changing that earlier work.
The demo uses one scalar key and value per position so the arithmetic is easy to follow. It supplies the chosen token IDs and checks that cached attention produces the same result as rebuilding the prefix.
from math import exp, isclose def project(token_id): return token_id + 1, token_id * 2 def attend(query, pairs): weights = [exp(query * key) for key, _ in pairs] weighted_sum = sum( weight * value for weight, (_, value) in zip(weights, pairs) ) return weighted_sum / sum(weights) prefix = [] cache = [] rebuilt_count = 0 cached_count = 0 for new_ids in ([1, 2, 3], [4], [5]): prefix.extend(new_ids) rebuilt = [project(token_id) for token_id in prefix] new_pairs = [project(token_id) for token_id in new_ids] cache.extend(new_pairs) query = prefix[-1] / 10 assert isclose(attend(query, rebuilt), attend(query, cache)) rebuilt_count += len(rebuilt) cached_count += len(new_pairs) assert (rebuilt_count, cached_count) == (12, 5) print("K/V pairs computed without cache:", rebuilt_count) print("K/V pairs computed with cache: ", cached_count) Try it. Add [6] to process the period and make one more prediction. The uncached path computes six more pairs. The cached path computes one. Change the final assertion to (18, 6) and check that the attention results still match.
The trade-off is memory. With full attention, a longer sequence leaves more keys and values to store and more data for each new query to use. That raises the next practical question. How much GPU memory does the KV cache take as a conversation grows?
Adapted from Why Cache Keys and Values?, which includes an interactive stepper that shows the cache growing one token at a time. AI assisted with drafting this adaptation.
