# Chapter 7: KV cache

Part of the course “AI from Zero to Autonomous Agents” (https://llm.yoga/en). Page for humans: https://llm.yoga/en/07-kv-cache

*The model’s notebook: why it makes generation fast, what it costs in memory, and what it has to do with the prompt caching that providers offer.*

About 20 min to read · about 15 min hands-on exercise

**Start with the missions**

This chapter also comes as 3 short missions with a case, a decision and feedback, about 10 minutes each:

- [7.1 I only typed „Hallo“ (hello), so why so much memory?](https://llm.yoga/en/einsatz-7-1.md)
- [7.2 Why does Qwen3-8B have only 8 KV heads?](https://llm.yoga/en/einsatz-7-2.md)
- [7.3 50 questions about the same manual: what does prompt caching save?](https://llm.yoga/en/einsatz-7-3.md)

For agents, this page is split into 2 parts so that each part can be fetched in full. Read the parts the question needs.

## Parts

### Part 1: https://llm.yoga/en/07-kv-cache-1.md

- **Getting started**: Imagine you’re reading a crime novel and have to say after every new sentence who the culprit might be.
- **Why the model stores anything at all**: A reminder of how attention works: in every layer, each token forms three vectors (lists of numbers).
- **What exactly is in the cache**: To calculate memory requirements, you need to know how many numbers are stored per token.
- **Worked example: Qwen3-8B and Llama 3.1 8B**: Let’s work this out for two widely used models with about eight billion parameters each.
- **Why there are only 8 KV heads: grouped-query attention**: Qwen3-8B has 32 attention heads for the queries but only 8 KV heads.
- **My own measurement: memory grows with the context window**: You can check the math on a Mac.

### Part 2: https://llm.yoga/en/07-kv-cache-2.md

- **How to make the cache smaller**: Because the cache needs so much memory, there are several levers.
- **Prompt caching by providers: the same trick across requests**: So far, we have considered the cache within one request.
- **Exercise: watch the cache grow**: Goal: you see with your own eyes that the context length setting alone costs memory, and you compare that with your own math.
- **Common misconceptions**: The KV cache stores earlier answers so the model can reuse them.
- **Review questions**: 1. Why can a language model safely keep the keys and values of earlier tokens instead of recomputing them?
- **Go further**: Ainslie et al.: GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023), the paper on grouped-query attention.
