Lesson 2 · Unit 01
The KV cache
What decode would recompute, and what it stores instead
What you practise
- What attention recomputes without it, what is stored per layer and per token, the memory it takes as arithmetic, prompt caching as the same idea across requests
Try a question from this lesson
Pick one
A model is generating token 501. Under a causal mask, earlier tokens never look at later ones. What does this step really need to compute fresh?
Hint
If a token never sees what comes after it, can a new token change what it computed?
Correct answer
Only the newest token: its query, key and value per layer
Why
Adding a token cannot change what earlier tokens computed, because they never attended to it. Their keys and values are still valid. Only the new token needs a query to look back with, plus a key and a value of its own for the tokens still to come.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
What the cache holds
For every layer, the cache keeps one key vector and one value vector per token seen so far. Split across attention heads, that is two tensors per layer.
A new token appends one slot to each. Nothing already stored is ever rewritten.
cache[layer] = (keys, values)
each: [heads, tokens, head_dim]
heads x head_dim = model widthConcept
Keeping a cache between requests
A KV cache normally dies with its request. Keep it, and a later request that starts with the same tokens can skip prefilling them. That is prompt caching.
Each token's keys and values depend on every token before it, so the match must be exact from the first token up to the first difference.
10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.