- Derive the KV-cache size formula from the attention equations, including the batch term.
- Calculate cache memory for MHA, GQA, MQA and multi-head latent attention designs.
- Explain, using arithmetic intensity, why decode attention is memory-bound and how long context lowers tokens per second.
- Estimate the quadratic prefill cost of long prompts and compare it with the weight FLOPs.
- Implement a calculator for cache size and maximum context under a memory budget, and choose mitigations such as cache quantization and paging.
Before this: Parameters and Model Size, Transformers: A Deep Dive
A model that fits easily with a short chat can run out of memory when you paste in a long document. The reason is the KV cache, and knowing how to estimate it tells you how much context your hardware can really handle.
What the KV cache is
Language models write one token at a time. Through the attention mechanism, each new token looks back at every earlier token in the context. To do that, each layer turns every token into two vectors (lists of numbers): a key, which describes what the token offers, and a value, the information it carries.
Those keys and values do not change once computed, so instead of recalculating them for the whole conversation at every step, the model stores them. That store is the key-value (KV) cache. It makes generation fast, but it grows with every token in the context.
An analogy: a reader who keeps a sticky note for every sentence so far, instead of rereading the whole book before each new sentence. The notes save enormous time, but a long book means a big pile of notes.
The formula
For a standard transformer:
KV cache (bytes) = 2 × layers × KV heads × head dimension × bytes per value × tokens
- 2: one key and one value.
- Layers: how many transformer layers the model has.
- KV heads: attention is split into parallel "heads"; this is how many distinct key/value sets each layer keeps.
- Head dimension: the length of each key or value vector, often 128.
- Bytes per value: 2 at 16-bit, 1 at 8-bit.
- Tokens: the length of the context, including the reply being written.
These numbers are in a model's configuration file, usually named config.json.
Worked example: a 70B model at long context
Llama 3 70B has 80 layers, 8 KV heads and a head dimension of 128 (from its published configuration). At 16-bit:
- Per token: 2 × 80 × 8 × 128 × 2 bytes = 327,680 bytes, about 0.33 MB.
- At 8,000 tokens: about 2.6 GB.
- At 32,768 tokens: about 10.7 GB.
- At 131,072 tokens (a "128K" context): about 43 GB.
At full 128K context, the KV cache alone (about 43 GB) is larger than the 4-bit weights (about 41 GB). Using this site's method, total memory is weights + KV cache + about 1.5 GB of overhead, so roughly 86 GB, nearly double the roughly 45 GB the same model needs for an 8,000-token chat. That is why 128K context can need tens of gigabytes on its own.
Why it is not even worse: grouped-query attention
Llama 3 70B has 64 attention heads but only 8 KV heads. That is grouped-query attention (GQA): several query heads share one set of keys and values. If every head kept its own (the original "multi-head attention" design), the cache would be 8 times larger, about 340 GB at 128K. GQA is now standard in most open models, with only a small effect on quality.
Other ways designers shrink the cache
- Sliding-window attention. Some layers only look at the most recent tokens, say the last 1,024, so their cache stops growing. Google's Gemma 3 interleaves five such local layers for every one full "global" layer; only the global layers keep the whole context.
- Multi-head latent attention (MLA). Introduced by DeepSeek, MLA compresses keys and values into a smaller shared "latent" vector and reconstructs them when needed. DeepSeek reported that DeepSeek-V2 cut KV cache size by 93.3% compared with its earlier 67B model.
- Hybrid and linear-attention layers. Some models replace most attention layers with layers that keep a fixed-size running summary instead of a growing cache. Qwen3-Next, for example, uses three such "Gated DeltaNet" layers for every standard attention layer, so only a quarter of its layers keep a KV cache. The trade-off is that a fixed-size summary can forget fine details, which is why a few full-attention layers are kept.
The formula above applies to standard attention layers; for these designs, read the model card or let your runtime report the cache size.
Quantizing the KV cache
Just as weights can be quantized, so can the cache. Runtimes such as llama.cpp and vLLM can store keys and values at 8-bit (and llama.cpp lower still). At 8-bit, the 128K example drops from about 43 GB to about 21 GB. The vLLM documentation notes that FP8 cache works best with calibration, and some sensitive layers may need to stay at full precision. Test quality on long documents before relying on it.
Context also costs time
Two separate costs grow with context:
- Prefill: reading the prompt. The model processes every prompt token, so a 100,000-token document takes far longer to start answering than a short question.
- Decode: writing each new token. Every step reads the whole KV cache as well as the weights, so generation slows as the context fills.
Hosted services feel this too, which is one reason long prompts cost more and why many offer discounted "cached" input for repeated prompt prefixes.
Going deeper
Deriving the cache from attention
In one attention head of one layer, token with hidden vector produces a query, key and value:
and the head's output is a weighted average of all earlier values:
where is the head dimension. Because the model is causal, and depend only on tokens up to , so they never change once computed. Without a cache, step would recompute keys and values in every layer, and generating tokens would redo projections. With a cache, each step computes one new key and value per KV head and appends them.
What is stored per token, per layer, is one key and one value vector for each KV head: numbers. Multiply by layers, bytes per number, tokens and sequences served together (the batch):
This is the formula from earlier in the lesson, with the batch term that matters for servers: a server holding 16 conversations of 8K tokens needs as much cache as one 128K conversation.
Attention variants as choices of . Multi-head attention (MHA) has ; grouped-query attention (GQA) has for group size ; multi-query attention (MQA) has . For an 80-layer model with at 16-bit, the per-token cache is 2.62 MB with 64 KV heads, 0.33 MB with 8 and 41 KB with 1.
Multi-head latent attention stores something else entirely: a compressed latent vector of size plus a small decoupled positional key of size per token per layer. DeepSeek-V2 uses and , so it caches 576 numbers per token per layer. With 60 layers at 16-bit that is bytes per token, against about 3.9 MB for full multi-head attention with its 128 heads of size 128.
Why decode is memory-bound
At each decode step, every layer reads its whole cache. For one sequence the attention computation does about FLOPs per layer ( for the scores and the same for the weighted sum of values), while reading bytes. The ratio, the arithmetic intensity, is
With GQA group size at 16-bit this is 8 FLOPs per byte. Modern accelerators can do hundreds of FLOPs per byte of bandwidth, so attention during decode is limited by memory reads, not arithmetic. Batching does not help here, because each sequence has its own cache.
That means long context slows decoding in the same way bigger weights do. Extending this site's speed formula so bytes per token include the cache (an extension of the AI Index method, not part of it): Llama 3 70B at about 4.5 bits on a 500 GB/s machine reads 39.4 GB of weights per token. At a full 128K context it also reads about 42.9 GB of cache, so the estimate falls from to tokens per second.
Prefill grows quadratically
During prefill, attention scores are computed for every pair of prompt tokens. With causal masking about half the pairs are needed, giving roughly FLOPs for scores and value sums together, on top of about FLOPs per token for the weights. For Llama 3 70B at : the attention term is FLOPs, larger than the weight term . At 8K tokens the attention term is 256 times smaller, under a tenth of the weight term. Kernels such as FlashAttention reduce memory traffic for this step but not the quadratic FLOP count.
Serving: paging the cache
Servers do not know in advance how long each reply will be. Reserving the maximum context for every request wastes memory that could serve other users. PagedAttention, introduced with vLLM, stores each sequence's cache in fixed-size blocks allocated on demand, like virtual-memory pages, and lets sequences that share a prompt prefix share blocks. Reusing a cached prefix in this way is also what makes discounted cached-input pricing possible: the prefix's keys and values need not be recomputed.
Sliding windows in the formula
For a layer that attends only to the last tokens, the cache holds tokens instead of . Gemma 3's pattern of five local layers (window 1,024) per global layer therefore stores, on average per layer, tokens. At that is about 22,700 tokens per layer, roughly 17% of what the same model would need if every layer were global.
Code: a cache calculator
def kv_cache_bytes(n_layers, n_kv_heads, head_dim, tokens, batch=1,
bytes_per_elem=2):
"""Standard (GQA/MHA) attention: one key and one value vector per
KV head, per layer, per token, per sequence in the batch."""
return 2 * n_layers * n_kv_heads * head_dim * bytes_per_elem * tokens * batch
def max_context(budget_gb, n_layers, n_kv_heads, head_dim, bytes_per_elem=2,
batch=1):
per_token = kv_cache_bytes(n_layers, n_kv_heads, head_dim, 1, batch,
bytes_per_elem)
return int(budget_gb * 1e9 // per_token)
llama3_70b = dict(n_layers=80, n_kv_heads=8, head_dim=128)
for ctx in (8_192, 32_768, 131_072):
gb16 = kv_cache_bytes(**llama3_70b, tokens=ctx) / 1e9
gb8 = kv_cache_bytes(**llama3_70b, tokens=ctx, bytes_per_elem=1) / 1e9
print(f"{ctx:>7} tokens: {gb16:5.1f} GB at 16-bit, {gb8:5.1f} GB at 8-bit")
# How much context fits in 20 GB of spare memory, at 16-bit and 8-bit?
print(max_context(20, **llama3_70b), max_context(20, **llama3_70b,
bytes_per_elem=1))
The output reproduces the worked example (about 2.7, 10.7 and 42.9 GB at 8K, 32K and 128K tokens at 16-bit) and shows that 20 GB of spare memory holds about 61,000 tokens of Llama 3 70B context at 16-bit, or about 122,000 with an 8-bit cache.
Common pitfalls
- Using query heads instead of KV heads. With GQA, plugging in overstates the cache by the group factor (8 times for Llama 3 70B).
- Forgetting the batch. Serving many users multiplies the cache; it, not the weights, usually limits concurrency.
- Applying the formula to MLA, sliding-window or hybrid layers. Use the architecture's own accounting or the runtime's report.
- Reserving maximum context by default. Many runtimes allocate the configured context up front.
- Ignoring speed. A long context costs decode speed (cache reads) and time-to-first-token (quadratic prefill), not just memory.
In practice
- Before loading a long document, estimate the KV cache from the formula and add it to the model's file size and about 1.5 GB of overhead.
- Set your local runtime's context length to what you actually need; reserving 128K when you use 8K wastes memory.
- If memory is tight, try an 8-bit KV cache before dropping to a smaller or more heavily quantized model.
- When choosing a model for long documents, look for GQA, sliding-window, MLA or hybrid designs, which keep the cache small.
Key takeaways
- The KV cache stores each earlier token's keys and values so the model does not recompute them, and it grows with every token of context.
- KV cache size is 2 times layers times KV heads times head dimension times bytes per value times tokens.
- For a Llama-3-70B-style model at 16-bit, a 128K context needs about 43 GB of KV cache, more than its 4-bit weights.
- Grouped-query attention, sliding windows, latent attention (MLA) and hybrid linear layers all shrink the cache.
- Quantizing the KV cache to 8-bit roughly halves it, but quality should be checked on long-context tasks.
Terms in this lesson
- Attention
- The mechanism that lets each token draw on information from earlier tokens in the context.
- Key and value
- Vectors computed for each token; keys describe what a token offers and values carry its information.
- KV cache
- Stored keys and values for all tokens so far, kept so they need not be recomputed.
- Attention head
- One of several parallel attention computations in a layer, each with its own view of the context.
- Grouped-query attention (GQA)
- A design where several query heads share one set of keys and values to cut cache size.
- Sliding-window attention
- Attention that only looks back over a fixed number of recent tokens.
- Multi-head latent attention (MLA)
- DeepSeek's method of compressing keys and values into a smaller latent vector.
- Prefill
- The phase where the model reads and processes the whole prompt before writing.
- Multi-query attention (MQA)
- An attention design where all query heads share a single key and value head, minimising the KV cache.
- Arithmetic intensity
- FLOPs performed per byte read from memory; low values mean a computation is limited by memory bandwidth rather than compute.
- PagedAttention
- A serving technique that stores the KV cache in fixed-size blocks allocated on demand, reducing wasted memory and allowing prefix sharing.
Check your understanding
- 1.
A model has 32 layers, 8 KV heads and head dimension 128, stored at 16-bit. Roughly how large is its KV cache for 8,192 tokens?
- 2.
Why does grouped-query attention reduce memory use?
- 3.
Your model fits for short chats but runs out of memory on a 100,000-token document. What is the most direct fix to try first?
- 4.
A model has 60 layers and uses multi-head latent attention that caches 576 numbers per token per layer at 16-bit. How large is its KV cache per token?
- 5.
During decode with grouped-query attention (8 query heads per KV head) and a 16-bit cache, attention does about 8 FLOPs per byte of cache read. What does this imply?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
Llama 3 8B has 32 layers, 8 KV heads and head dimension 128. At 16-bit, compute (a) the cache per token, (b) the cache for one 131,072-token conversation, and (c) the cache for a server batch of 8 conversations of 8,192 tokens each.
Show solution
(a) bytes, 128 KiB per token. (b) GB, more than three times the roughly 5 GB 4-bit weights. (c) GB.
- Exercise 2Core
For an 80-layer model with 64 query heads of dimension 128, compute the 16-bit cache per token and at 128K tokens for MHA (), GQA () and MQA ().
Show solution
Per token bytes.
- MHA: 2,621,440 bytes (2.6 MB); at 131,072 tokens about 344 GB.
- GQA: 327,680 bytes (0.33 MB); about 42.9 GB.
- MQA: 40,960 bytes (41 KB); about 5.4 GB.
GQA is the common compromise: an 8-fold saving over MHA with a much smaller quality impact than going all the way to MQA.
- Exercise 3Core
Write a function that, given GPU memory, model size, bits per weight and the attention shape, returns the longest context that fits under this site's rule (need at most 85% of memory; file size plus 5%; 1.5 GB overhead). Apply it to Llama 3 8B (8.03B parameters) at 4.8 bits on a 24 GB GPU with a 16-bit and an 8-bit cache.
Show solution
def max_tokens(gpu_gb, n_params, bits, n_layers, n_kv_heads, head_dim, kv_bytes=2, overhead_gb=1.5, fit=0.85): file_gb = n_params * bits / 8 / 1e9 * 1.05 spare_gb = fit * gpu_gb - file_gb - overhead_gb per_token = 2 * n_layers * n_kv_heads * head_dim * kv_bytes return max(0, int(spare_gb * 1e9 // per_token)) print(max_tokens(24, 8.03e9, 4.8, 32, 8, 128)) # 105599 print(max_tokens(24, 8.03e9, 4.8, 32, 8, 128, kv_bytes=1)) # 211198Budget GB; file GB; spare GB. Dividing by 131,072 bytes per token gives about 105,600 tokens at 16-bit and about 211,200 at 8-bit, though the model's own maximum context (128K for Llama 3.1) caps the second figure.
- Exercise 4Challenge
Using the extended speed estimate tok/s ≈ 1 ÷ ((weight bytes + cache bytes) ÷ (0.55 × bandwidth) + 1.5 ms), estimate decode speed for Llama 3 8B at 4.8 bits on a 1,000 GB/s GPU with (a) a near-empty context, (b) 32,768 tokens of 16-bit cache, (c) the same context with an 8-bit cache. What does this say about cache quantization?
Show solution
Weights: GB per token; effective bandwidth 550 GB/s. The 32K cache is GB at 16-bit, 2.15 GB at 8-bit.
(a) ms, plus 1.5 ms = 10.2 ms, about 98 tok/s. (b) ms, plus 1.5 = 18.0 ms, about 55 tok/s. (c) ms, plus 1.5 = 14.1 ms, about 71 tok/s.
At long context the cache is as large as the 4-bit weights, so it halves speed; quantizing the cache to 8-bit recovers much of that, as well as saving memory, provided long-document quality holds up in your tests.
Further reading
- paperShazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019)
- paperAinslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023)
- paperKwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023)
- paperDeepSeek-AI, DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (2024)
- docsvLLM, Quantized KV Cache (documentation)
Go further
Sources
- Llama 3 70B Instruct (AWQ) config.json (Hugging Face)
- Gemma 3 Technical Report (arXiv)
- DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (arXiv)
- Qwen3-Next-80B-A3B-Thinking-GGUF model card (Hugging Face)
- Quantized KV Cache (vLLM documentation)
- Shazeer, Fast Transformer Decoding: One Write-Head is All You Need (2019)
- Ainslie et al., GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (2023)
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention (2023)
- DeepSeek-AI, DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (2024)
Fact-checked and last reviewed 2026-11-05