Module 2 · Inside the block

The key-value cache, and the engineering built around it

In this lesson

  • 9 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 10 of 10 in this chapter

This chapter’s goalImplement single-head attention from scratch in NumPy, explain which half of a block holds most of the parameters and which half moves information between positions, and predict how grouped-query attention, key-value caching and a mixture-of-experts design each change memory and speed.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmNot availableNot available
Full audiobookNot availableNot available
One 32,000-token conversation, same eight-billion modelCache: multi-head, 32 kvheads16.8Cache: grouped-query, 8 kvheads4.2Cache: multi-query, 1 kvhead0.52Model weights, shared byall users16gigabytes of memoryPer token the cache costs 2 × layers × kv_heads × head_dim × bytes, so it is proportional to thekey-value head count and nothing else. The weights load once and serve everybody; the cache is peruser and grows with every token. Grouped-query attention exists for this single reason.
Per token the cache costs 2 × layers × kv_heads × head_dim × bytes, so it is proportional to the key-value head count and nothing else. The weights load once and serve everybody; the cache is per user and grows with every token. Grouped-query attention exists for this single reason.

Figure

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 7Free · no account needed
Lesson steps

The waste that had to be removed

Generating token 500 means running attention over 499 earlier positions. Their key and value vectors depend only on the tokens themselves, which have not changed. Recomputing them every step would multiply the cost of a 500-token response by a factor of hundreds.

So they are cached. For each layer, for each position, the keys and values are computed once and kept. Each new token computes only its own query, key and value, appends the latter two to the cache, and attends over everything stored.

This is the single most important optimisation in language model serving, and it is why the second token arrives much faster than the first.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Every lesson here is open. Your progress is recorded once you pass the AI, Actually Explained exam.

Stuck on something?Ask Anjali, your AI tutor

How to cite: Addaly (2026) ‘The key-value cache, and the engineering built around it’, in How a Language Model Actually Works. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/how-llms-work/kv-cache-and-attention-variants (Accessed: 29 November 2026).