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.
- The new token entersOnly this one token goes through the layers
- In each layer: make its query, key and valueA small amount of work for a single token
- Add its key and value to the cacheThe cache grows by one token in every layer
- Compare its query with every cached keyThen mix the cached values by those scores
- Choose the next tokenAnd repeat
without a cache: 1 + 2 + 3 + … + 1,000 ≈ 500,000 token passesEvery step would push the whole text through all the layers again.
with a cache: 1,000 token passesEach step handles only the new token. That is 500 times less work.
Quick check
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.
bytes per token = 2 × layers × KV heads × head size × bytes per numberThe 2 is for keys and values.
2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB32 layers, 8 KV heads, 128 numbers per head, 2 bytes each in BF16.
128 KiB × 131,072 tokens = 16 GiBAt its full context of 128K tokens, the cache is as big as the model’s 16 GB of weights.
| How attention stores keys and values | Per token | At 131,072 tokens | |
|---|---|---|---|
| Llama 3.1 8B | 8 shared KV heads (GQA) | 128 KiB | 16 GiB |
| The same model, with 32 KV heads | One KV head per query head (MHA) | 512 KiB | 64 GiB |
| Llama 3.1 70B | 8 shared KV heads (GQA) | 320 KiB | 40 GiB |
| Llama 3.1 405B | 8 shared KV heads (GQA) | 504 KiB | 63 GiB |
| gpt-oss-120b | GQA, and half the layers only look back 128 tokens | 36 KiB | 4. |
| DeepSeek-V3 (671B) | One compressed vector per layer (MLA) | 68. | 8. |
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.
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.
per layer, per token: 512 compressed numbers + 64 numbers for positionFrom 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 KiBFor a model with 128 attention heads in every layer.
rebuilding the keys can be folded into the query mathsSo 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
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.
llama-server -hf Qwen/Qwen3-8B-GGUF:Q4_K_M \
-c 32768 \
-ctk q8_0 -ctv q8_0
-c 32768sets 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.-ctkand-ctvset the type for keys and values.q8_0brings the cache down to about 2.4 GiB.- The default is
f16. Other choices includeq4_0andq5_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_promptis 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?
-
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.
-
Fast Transformer Decoding: One Write-Head is All You Need
Multi-query attention. Short, and clear about why decode is limited by reading keys and values from memory.
-
GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints
Grouped-query attention, now in most open models. Figure 2 shows MHA, GQA and MQA side by side.
-
DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model
Introduces MLA. Section 2.1 builds it step by step, and Table 1 compares the cache per token of MHA, GQA, MQA and MLA.
-
Efficient Memory Management for Large Language Model Serving with PagedAttention
The vLLM paper. Figure 2 shows how much memory older systems wasted.
-
SGLang: Efficient Execution of Structured Language Model Programs
RadixAttention for reusing prefixes, plus faster structured output.
-
Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving
How Kimi is served: prefill and decode on separate machines, and a cluster-wide cache in CPU memory and SSDs.
-
KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache
Why keys and values need different treatment when squeezed to 2 bits.
-
SnapKV: LLM Knows What You are Looking for Before Generation
Choosing which tokens to keep by watching where the end of the prompt looks.
Check yourself
5 questions. Tap the answer you think is right.
0 of 5 answered
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