Availit World How AI really works, in your language

Lesson 25 of 4621 minFacts checked October 20, 2026

The KV cache: a model’s working memory

When a model writes word 501 of a reply, it has to look back at all 500 words before it. Recomputing them every time would be hopeless, so it keeps a note of each one: the KV cache. For a long chat this note can grow as big as the model itself, and it decides how many people one GPU can serve at once. Some of the most important ideas in modern AI, from DeepSeek’s attention design to vLLM’s memory pages, exist to make this note smaller, share it, or reuse it.

In this lesson you will

  • Explain what the KV cache stores and why it makes decode fast
  • Calculate the size of a KV cache from a model’s config
  • Compare MHA, MQA, GQA and DeepSeek’s MLA by how much they store
  • Explain how PagedAttention and prefix caching let servers share memory
  • Write prompts and agents that reuse the cache instead of paying for it again
On this page
  1. Why keep a cache
  2. How big it gets
  3. Smaller caches by design
  4. Fewer bits per number
  5. Sharing memory between users: PagedAttention
  6. Reusing the cache: prefix caching
  7. Throwing tokens away
  8. Remember
  9. Check yourself

Why keep a cache

Recall the attention lesson: in every layer, each token makes a query (what it is looking for), a key (what it offers) and a value (what it passes on). To write the next token, its query is compared with the keys of every earlier token, and their values are mixed according to the scores.

Earlier tokens never look at later ones. So once a token’s key and value have been computed in a layer, they never change. Instead of computing them again for every new token, the model stores them: one key and one value, per token, per layer. That store is the KV cache.

One decode step, with the cache
  1. The new token entersOnly this one token goes through the layers
  2. In each layer: make its query, key and valueA small amount of work for a single token
  3. Add its key and value to the cacheThe cache grows by one token in every layer
  4. Compare its query with every cached keyThen mix the cached values by those scores
  5. Choose the next tokenAnd repeat
Work saved, for a 1,000-token reply
without a cache: 1 + 2 + 3 + … + 1,000 ≈ 500,000 token passes

Every step would push the whole text through all the layers again.

with a cache: 1,000 token passes

Each step handles only the new token. That is 500 times less work.

Quick check

Why can the keys and values of earlier tokens be reused safely?

Show the answer

Answer: Earlier tokens never look at later ones, so their keys and values never change Attention in these models is causal: each token only looks backwards. Adding new tokens cannot change what earlier tokens computed.

How big it gets

The size of the cache follows directly from a model’s config file. Each layer stores a key and a value for each token, and each of those has one vector per key-value head.

KV cache for Llama 3.1 8B
bytes per token = 2 × layers × KV heads × head size × bytes per number

The 2 is for keys and values.

2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB

32 layers, 8 KV heads, 128 numbers per head, 2 bytes each in BF16.

128 KiB × 131,072 tokens = 16 GiB

At its full context of 128K tokens, the cache is as big as the model’s 16 GB of weights.

KV cache per token, and at 128K tokens (16-bit)
How attention stores keys and valuesPer tokenAt 131,072 tokens
Llama 3.1 8B8 shared KV heads (GQA)128 KiB16 GiB
The same model, with 32 KV headsOne KV head per query head (MHA)512 KiB64 GiB
Llama 3.1 70B8 shared KV heads (GQA)320 KiB40 GiB
Llama 3.1 405B8 shared KV heads (GQA)504 KiB63 GiB
gpt-oss-120bGQA, and half the layers only look back 128 tokens36 KiB4.5 GiB
DeepSeek-V3 (671B)One compressed vector per layer (MLA)68.6 KiB8.6 GiB

Worked out from each model’s config.json. 1 KiB is 1,024 bytes and 1 GiB is 1,024³ bytes, about 1.07 GB. The largest model here has one of the smallest caches.

And every user has their own cache. Sixty-four people chatting with 8,000 tokens each on Llama 3.1 8B need 64 × 8,000 × 128 KiB, about 62 GiB, on top of the weights. On a server, the cache, not the weights, usually decides how many people fit on one GPU.

Try itWeights and cache, side by side

Pick Llama 3.1 8B on the H100 and move the context from 4,096 to 131,072 tokens: the KV cache overtakes the weights. Then set the KV cache to Q8_0. Try gpt-oss-120b too, whose design keeps the cache small.

This interactive part needs JavaScript.

Smaller caches by design

The cache is big because every attention head keeps its own keys and values. Four designs, each from a paper, store less and less:

  • Multi-head attention (MHA), the original 2017 design: every head has its own keys and values.
  • Multi-query attention (MQA), Noam Shazeer at Google, 2019: all heads share one key and one value. The cache shrinks enormously, but quality can drop.
  • Grouped-query attention (GQA), Google, 2023: heads share keys and values in groups, for example 32 query heads and 8 KV heads. Quality close to MHA, speed close to MQA. Llama 3, Qwen3 and gpt-oss all use it.
  • Multi-head latent attention (MLA), DeepSeek-V2, 2024: store one small compressed vector per token per layer, and rebuild the keys and values of every head from it when needed.
MLA in DeepSeek-V3
per layer, per token: 512 compressed numbers + 64 numbers for position

From the config: kv_lora_rank 512 and qk_rope_head_dim 64. The position part is kept apart so RoPE still works.

61 layers × 576 × 2 bytes = 70,272 bytes ≈ 68.6 KiB

For a model with 128 attention heads in every layer.

rebuilding the keys can be folded into the query maths

So the GPU rarely has to build full keys and values at all.

The DeepSeek-V2 paper shows that MLA stores about as much as GQA with only 2.25 groups, yet scored better than full MHA in its tests. The new model needed 93.3 % less KV cache than the earlier DeepSeek 67B and could serve up to 5.76 times as many tokens per second. Kimi K2 and other models built on DeepSeek’s design use MLA too. The long-context lesson covers the next steps: sliding windows, linear attention, and DeepSeek’s sparse and compressed attention.

Quick check

A model has 40 layers, 8 KV heads, a head size of 128 and a 16-bit cache. How big is its cache per token?

Show the answer

Answer: 160 KiB 2 × 40 × 8 × 128 × 2 = 163,840 bytes, which is 160 KiB.

Fewer bits per number

Like the weights, the cache can be stored with fewer bits. An 8-bit cache is half the size of a 16-bit one, and a 4-bit cache about a quarter. Less to store also means less to read at every decode step, so long chats get faster too.

An 8-bit KV cache in llama.cppbash
llama-server -hf Qwen/Qwen3-8B-GGUF:Q4_K_M \
  -c 32768 \
  -ctk q8_0 -ctv q8_0
  • -c 32768 sets the context, and so the size of the cache: 36 layers × 8 KV heads × 128 gives 144 KiB per token at 16 bits, 4.5 GiB for 32,768 tokens.
  • -ctk and -ctv set the type for keys and values. q8_0 brings the cache down to about 2.4 GiB.
  • The default is f16. Other choices include q4_0 and q5_1.

Keys and values do not behave the same way. The KIVI paper (2024) found that keys have a few channels with very large numbers, so they should be grouped by channel, while values should be grouped by token. With that, a 2-bit cache kept almost the same quality, used 2.6 times less peak memory, and allowed batches up to 4 times larger.

Sharing memory between users: PagedAttention

A server does not know how long each reply will be. Early systems reserved space for the longest possible reply for every request. The vLLM team measured those systems and found that only 20.4 % to 38.2 % of the KV cache memory held real tokens. The rest was reserved but empty, or lost in gaps between requests.

Their fix, PagedAttention (2023), borrows an old idea from operating systems. The cache is cut into small blocks, 16 tokens each by default in vLLM. A request gets a new block only when it fills the last one, and a block table records where its blocks are, which need not be next to each other. Waste falls to almost nothing, so many more requests fit, and vLLM served 2 to 4 times more requests per second than the systems before it.

Blocks can also be shared. When one prompt gets several answers, such as the group of answers per question that GRPO training samples, all of them point to the same blocks for the prompt and only copy a block when they start to differ.

Reusing the cache: prefix caching

Many requests start the same way: the same system prompt, the same tool descriptions, the same long document with a new question at the end. If the server keeps the cache for that shared start, the prefix, the next request can skip its prefill and start from there. This is prefix caching.

  • SGLang’s RadixAttention (2023) keeps cached prefixes in a tree, so any request can reuse the longest start it shares with an earlier one. SGLang reported up to 6.4 times the throughput of other systems, on tasks that include agents and multi-turn chat.
  • llama.cpp does a simple version by default: cache_prompt is on, so a follow-up in the same chat only processes the new part.
  • DeepSeek keeps caches on disk. In one day in February 2025, 56.3 % of all input tokens to its service were found in that cache, and at DeepSeek-R1’s prices then, cached input cost $0.14 per million tokens instead of $0.55.
  • Kimi’s Mooncake (2024), from Moonshot AI and Tsinghua University, pools the spare CPU memory and SSDs of a whole GPU cluster into one big cache. On real traffic, it let Kimi handle 75 % more requests.

Can the server reuse the cache from the previous request?

0 of 6 sorted
  • Same system prompt and chat so far, plus one new message

    Answer: Mostly reused

  • The current time is inserted at the start of the system prompt

    Answer: Starts again from scratch

  • Same long contract, with a different question at the end

    Answer: Mostly reused

  • An agent rewrites its tool list in a new order each time

    Answer: Starts again from scratch

  • The same 20-page document, translated into another language

    Answer: Starts again from scratch

  • The next step of an agent, adding a tool result to the end

    Answer: Mostly reused

Throwing tokens away

Another approach is to keep only the tokens that matter. Attention is uneven: a few tokens get most of it. H2O (2023) keeps those “heavy hitters” plus the most recent tokens. SnapKV (2024) looks at which earlier tokens the end of the prompt pays attention to, and keeps those: with 16,000-token inputs, it generated 3.6 times faster and used 8.2 times less memory, with similar results.

Remember

  • The KV cache stores each token’s key and value in every layer, so each decode step only processes the newest token.
  • Size per token = 2 × layers × KV heads × head size × bytes. Llama 3.1 8B: 128 KiB, so 16 GiB at 128K tokens, as big as its weights.
  • On servers, the cache usually limits how many users fit on a GPU.
  • MQA, GQA and DeepSeek’s MLA store less by design; DeepSeek-V2 reported a cache 93.3 % smaller than its earlier 67B model’s.
  • Quantized caches (8-bit, even 2-bit with KIVI) and PagedAttention (blocks of 16 tokens) fit far more into the same memory.
  • Prefix caching reuses the cache for a shared start. Keep the start of prompts stable and add new things at the end.

Words to know

KV cache
The stored keys and values of every earlier token, in every layer.
Key and value
What each token offers to later tokens in attention: a key to be matched, a value to be passed on.
MHA
Multi-head attention: every head keeps its own keys and values.
MQA
Multi-query attention: all heads share one key and one value.
GQA
Grouped-query attention: heads share keys and values in groups.
MLA
Multi-head latent attention: DeepSeek’s design that stores one small compressed vector per token per layer.
PagedAttention
Storing the cache in small blocks, like pages of memory, so almost none is wasted.
Prefix caching
Keeping the cache for the start of a prompt, so later requests that start the same way skip that work.
Cache hit
When part of a prompt is found already in the cache. Often billed at a lower price.
Eviction
Throwing some tokens out of the cache to save memory.

Go to the source

This lesson is built on these papers and documents. Paper links open arxiv.org, a separate site.

Check yourself

5 questions. Tap the answer you think is right.

0 of 5 answered

What does the KV cache store?

Show the answer

Answer: The keys and values of every earlier token, in every layer It stores what later tokens look up in attention, so it is never recomputed.

Llama 3.1 8B uses 128 KiB of cache per token. About how much for 64,000 tokens?

Show the answer

Answer: About 8 GiB 128 KiB × 64,000 = 8,192,000 KiB, which is about 7.8 GiB.

What did DeepSeek’s MLA change?

Show the answer

Answer: It stores one small compressed vector per token per layer instead of keys and values for every head The keys and values of all heads are rebuilt from the compressed vector, so the cache is tiny.

Why did PagedAttention let servers handle more requests?

Show the answer

Answer: It stopped reserving memory for replies that might never be written, so almost none is wasted Older systems used only 20 % to 38 % of the cache memory for real tokens. Small blocks given out on demand fix that.

An agent’s system prompt starts with the current time, down to the second. What does that do?

Show the answer

Answer: Every request misses the prefix cache, because the very first tokens change A cache matches from the first token and stops at the first difference. Put changing details at the end.

Lesson complete

Answer every question above to complete this lesson.

Your progress is saved on this device only.

Next lessonQuantization: big models in small memory
Previous lesson All lessons

Choose your language