Chapter 313KV Cache › Worked Example: Tracing a 4-Token Generation
Reading section 4 of 14 · Worked Example: Tracing a 4-Token Generation · 5 minSection 4 of 14 · 5 min
Section 4 of 14 · 5 min read
KV Cache › Worked Example: Tracing a 4-Token GenerationOne section · Sections in this chapter4 / 14 ↓
Sections in this chapter14
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
To make the abstract formulas concrete, let's trace through a minimal numerical example from start to finish. We will use a toy model with , one attention head (), and . The prompt is three tokens: "The cat sat." We will then generate one additional token and track every vector and matrix involved.
For the projection matrices, we use simplified illustrative weights. In practice these are dense learned matrices, but here we treat them as identity-like for clarity:
This means the key and value for each token are just that token's embedding, and the query is half the embedding. The simplification does not change the structural argument at all.
Prefill Phase: All Three Prompt TokensLink Copied
We compute the keys and values for all three tokens simultaneously:
We store these in the cache immediately:
(In this toy example the keys and values are equal since ; in real models they differ entirely.)
Decode Phase: Generating Token 4Link Copied
Suppose the model samples token 4 from the distribution produced after the prefill phase, and that token 4 has embedding. To predict token 5, we need to compute attention from position 4 over all previous positions.
Step 1: Compute projections for token 4 only.
The key insight is that we compute exactly three vectors (, , ) for this step, not vectors. The keys and values for tokens 1 through 3 remain exactly as computed during prefill.
Step 2: Append and to the cache.
Step 3: Compute attention scores for token 4's query against all four cached keys.
Notice that token 4's own key (position 4) receives slightly more weight than the others, which is typical for recent tokens in causal attention.
Step 6: Compute the attention output as a weighted sum of cached values.
So .
What did we compute in this decode step? Three vector projections (for token 4 only), four dot products, a softmax over four values, and four weighted additions. Without the cache, we would have recomputed all projections for tokens 1, 2, and 3 as well. That is 9 additional projection operations for a sequence of length 4. For a sequence of length 100, the savings would be 297 additional projections avoided. For length 1000, the savings grow to 2997 projections avoided in that single step alone.