Running Models YourselfLesson 12 of 82

Module 2 · The memory arithmetic

The KV cache, in depth

In this lesson

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

This chapter’s goalCompute, for any model and any context length, whether it fits on a stated machine and roughly how fast it will run: naming which of weights, KV cache, bandwidth or interconnect is the binding constraint, and choosing the remedy that costs the least quality when it does not fit.

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
Two models of similar size, six times the cacheLlama 2 13B, multi-head,40 KV heads800Llama 3.1 8B,grouped-query, 8 KV heads128That same 8B with an 8-bitcache64KiB of KV cache per token of contextOnly the config file tells you which you have: layers, KV heads and head dimension, doubled for K andV. Grouped-query attention shares one KV head across several query heads, and it was a memory decisionrather than a quality one: it is the reason long context became affordable at all.
Only the config file tells you which you have: layers, KV heads and head dimension, doubled for K and V. Grouped-query attention shares one KV head across several query heads, and it was a memory decision rather than a quality one: it is the reason long context became affordable at all.

Figure

A little at a time

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

Step 1 of 8Free · no account needed
Lesson steps

Why the cache exists at all

Attention needs, for every new token, the key and value vectors of every previous token. Recomputing them would make generation quadratic in length and unbearably slow. So they are computed once and kept. That store is the KV cache, and it is the single term that turns a model which fits into a model which does not.

The size, per token:

Text
bytes = 2 x layers x kv_heads x head_dim x bytes_per_element

The leading 2 is K and V. Nothing else in local inference has a formula this simple with consequences this large.

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 Open Model Ecosystem exam.

Stuck on something?Ask Tri, your AI tutor

How to cite: Addaly (2026) ‘The KV cache, in depth’, in Running Models Yourself. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/running-models-yourself/the-kv-cache-in-depth (Accessed: 27 November 2026).