An autoregressive decoder generates one token at a time. Each new token needs attention over earlier tokens, but recomputing their key and value vectors at every step wastes work. A key-value (KV) cache stores those vectors after they are computed so later steps can reuse them. section 9.3
At each generation step:
- Compute a query for the new token and use stored key and value pairs for earlier tokens. section 9.3
- Compute the new token’s key and value vectors and append them to the cache for subsequent steps. section 9.3
- Budget for a cache that grows with sequence length and model layers; long contexts and large batches can make memory use substantial. section 3.2 section 9.3
Measure the trade-off
In Hugging Face Transformers, call model.generate with use_cache=True and then use_cache=False while keeping the prompt and max_new_tokens fixed. A Llama 3.2 3B Instruct benchmark generating 256 tokens took about 8.5 seconds with caching versus 17.7 seconds without it. The speedup comes with additional memory use, so production deployment also calls for cache management. section 9.3 section 3.2
Figure 9.4 At each step, the query is computed for the new token, while past key and value vectors are cached and reused. This avoids recomputation of the entire attention context, dramatically reducing inference time.
The diagram tracks the newly computed query and the growing set of stored key-value pairs across generation steps. section 9.3
