AI
KV Cache: How LLMs Reuse Work to Answer Faster
KV cache explained: how LLMs store attention keys and values to skip recomputing, how much memory it takes, and how GQA, paging and quantization shrink it.
A KV cache is the memory where a large language model keeps the keys and values it has already computed for every earlier token, so it doesn't have to compute them again each time it generates a new word. Language models write one token at a time, and each new token has to "look back" at all previous ones through attention. Without the cache, every step would reprocess the whole text so far. With it, each step only processes the newest token and reads the rest from memory.
The KV cache makes generation fast, but it costs memory, a lot of it at long context lengths and many users. That trade-off drives much of how LLMs are designed and served today: grouped-query attention, paged attention, prefix caching, cache quantization and sliding windows all exist to shrink or manage it. This guide explains how the KV cache works, what it means for inference speed, how to calculate its size with real model numbers, and how modern systems keep it under control.
What Is a KV Cache?
Inside each transformer layer, attention turns every token into three vectors:
- a query (Q): what this token is looking for,
- a key (K): what this token offers to be found by,
- a value (V): the information this token passes on if it's attended to.
To produce the next token, the model compares the newest token's query against the keys of all earlier tokens, then mixes their values according to those scores. The keys and values of earlier tokens don't change as generation continues, because a decoder model only looks backwards. So there's no reason to recompute them. The KV cache stores them, layer by layer and head by head, and appends one new key and value per layer for each generated token.
Queries, keys and values come from the attention mechanism at the heart of every transformer; the cache simply keeps the last two around.
What Is KV Cache in LLM Inference?
In LLM inference, the KV cache splits generation into two phases with very different behaviour:
1. Prefill. The model reads your whole prompt at once. It computes keys and values for every prompt token in parallel and writes them into the cache. This phase is compute-heavy and decides the time to first token. Long prompts mean longer prefill.
2. Decode. The model generates the answer one token at a time. For each new token it computes Q, K and V for that token only, appends K and V to the cache, and attends over everything stored. This phase decides the tokens per second you see while text streams.
How much work does the cache save? Without it, generating token number n means recomputing keys and values for all n tokens, so producing a 1,000-token answer redoes the earlier tokens over and over. Total work grows roughly with the square of the length. With the cache, each step does a fixed amount of new projection work plus one pass over the stored keys and values.
The catch is that decode becomes memory-bound. Each step must read the model's weights and the whole KV cache from GPU memory. That's why memory bandwidth, not raw compute, usually limits generation speed. Our guide to LLM memory bandwidth explains the maths.
How Much Memory Does the KV Cache Use?
The size follows directly from the model's shape:
KV cache bytes = 2 × layers × KV heads × head dimension × tokens × batch size × bytes per value
- 2 because you store both keys and values.
- Layers and KV heads come from the model's config.
- Head dimension is usually the hidden size divided by the number of attention heads, often 128.
- Tokens is the context length in use (prompt plus generated tokens).
- Bytes per value is 2 for FP16 or BF16, 1 for 8-bit cache types.
A KV cache calculator with real models
Here's a KV cache calculator table built from each model's published configuration on Hugging Face, at 16-bit precision for a single sequence:
| Model | Layers | Query heads | KV heads | Head dim | Per token | At 8K tokens | At 32K tokens | At 128K tokens |
|---|---|---|---|---|---|---|---|---|
| Llama 2 7B | 32 | 32 | 32 | 128 | 512 KiB | 4 GiB | 16 GiB | 64 GiB |
| Llama 3.1 8B | 32 | 32 | 8 | 128 | 128 KiB | 1 GiB | 4 GiB | 16 GiB |
| Mistral 7B | 32 | 32 | 8 | 128 | 128 KiB | 1 GiB | 4 GiB | n/a (32K max) |
| Qwen2.5 7B | 28 | 28 | 4 | 128 | 56 KiB | 448 MiB | 1.75 GiB | 7 GiB |
| Llama 3.1 70B | 80 | 64 | 8 | 128 | 320 KiB | 2.5 GiB | 10 GiB | 40 GiB |
Calculated with the formula above from each model's config.json. Llama 2 7B's native context is 4K, so the longer figures show what its design would cost, not what it supports.
Three things jump out:
- Llama 2 7B needs four times the cache of Llama 3.1 8B for the same context, purely because it has 32 KV heads instead of 8. More on that below.
- At long contexts the cache rivals the weights. Llama 3.1 8B's weights take about 16 GB in BF16; a single 128K-token conversation adds another 16 GiB of cache.
- Batch size multiplies everything. Serving 32 users at 8K tokens each on Llama 3.1 8B needs about 32 GiB of cache, double the model weights. This is why the KV cache, not the model, often decides how many users one GPU can serve.
You can compute it yourself in a few lines:
def kv_cache_bytes(layers, kv_heads, head_dim, tokens, batch=1, bytes_per_value=2):
return 2 * layers * kv_heads * head_dim * tokens * batch * bytes_per_value
gib = kv_cache_bytes(layers=32, kv_heads=8, head_dim=128, tokens=131_072) / 2**30
print(f"{gib:.1f} GiB") # Llama 3.1 8B at 128K tokens: 16.0 GiBMHA, MQA, GQA and MLA: Designing a Smaller Cache
The biggest lever on cache size is the attention design itself, specifically how many key and value heads each layer keeps.
| Design | KV heads per layer | Cache size | Quality | Used by |
|---|---|---|---|---|
| Multi-head attention (MHA) | One per query head | Largest | Baseline | Original transformer, Llama 2 7B |
| Multi-query attention (MQA) | One shared by all heads | Smallest | Some loss | Introduced by Shazeer in 2019 |
| Grouped-query attention (GQA) | A few groups (for example 8) | 4–8 times smaller than MHA | Close to MHA | Llama 3, Mistral, Qwen and most current open models |
| Multi-head latent attention (MLA) | Compressed into a small latent vector | Much smaller | Strong | DeepSeek-V2 and later |
Multi-query attention was proposed in 2019 precisely because, as its paper puts it, incremental decoding is slowed by the memory-bandwidth cost of repeatedly loading the large key and value tensors. Sharing one key and value head across all query heads cut that cost a lot, with some quality loss.
Grouped-query attention (Ainslie and colleagues, 2023) sits in between: query heads are split into groups that share a key and value head. The paper showed GQA reaches quality close to full multi-head attention with speed close to MQA. That's why Llama 3.1 8B has 32 query heads but only 8 KV heads, and why its cache is a quarter of Llama 2 7B's.
Multi-head latent attention, introduced in DeepSeek-V2, compresses keys and values into a low-rank latent vector. DeepSeek reported that, compared with its earlier 67B model, DeepSeek-V2 cut the KV cache by 93.3% and raised maximum generation throughput to 5.76 times.
KV Cache and Paged Attention
Serving many users raises a second problem: memory fragmentation. A simple server reserves one contiguous block of GPU memory per request, sized for the maximum possible output. Most requests end early, so much of that reserved memory sits empty, and the server can batch fewer requests than the hardware could handle.
KV cache and paged attention go together because paging fixes exactly this. The vLLM team's PagedAttention, inspired by virtual memory in operating systems, splits each request's cache into small fixed-size blocks that can live anywhere in GPU memory, tracked by a block table. The paper reports near-zero waste in KV cache memory and 2–4 times higher throughput than earlier state-of-the-art serving systems at the same latency, with bigger gains for long sequences and large models.
Paging also enables sharing. When many requests start with the same system prompt, their first blocks can point to the same physical memory. That leads directly to prefix caching.
Prefix Caching: Reusing the Cache Across Requests
Normally the KV cache lives only as long as one request. Prefix caching keeps the cache for common prompt beginnings (system prompts, tool definitions, long documents) so the next request that starts the same way can skip its prefill. In vLLM this is the enable_prefix_caching option. Hosted APIs sell the same idea as "prompt caching", usually with a discount on cached input tokens.
KV cache vs prompt cache
| KV cache | Prompt cache (prefix cache) | |
|---|---|---|
| What it is | Keys and values for tokens in the current sequence | Saved KV cache for a repeated prompt prefix |
| Lifetime | One request | Minutes to hours, across requests |
| Who controls it | The inference engine, automatically | The provider or server, often with your cache markers |
| Match rule | Same sequence | Identical prefix, token for token |
| Saves | Recomputing earlier tokens during generation | Prefill time and cost for the shared prefix |
| Visible to you as | Memory use, tokens per second | Lower time to first token, cheaper cached input tokens |
In short: KV cache vs prompt cache isn't a choice. Every modern LLM uses a KV cache; prompt caching is the practice of keeping part of it around for the next request. Our guide to prompt caching covers how the major APIs price and expose it.
Shrinking the Cache: Quantization, Offloading and Windows
When the cache still doesn't fit, there are several more tools.
Quantization. Store keys and values in 8 bits (or fewer) instead of 16. That halves the memory at 8 bits, usually with little quality loss. Examples:
- vLLM has a
kv_cache_dtypesetting that supports FP8 caches. - Hugging Face Transformers offers a quantized cache with
cache_implementation="quantized". - llama.cpp sets cache types with
--cache-type-kand--cache-type-v. - Ollama uses the
OLLAMA_KV_CACHE_TYPEenvironment variable. Its documentation describesq8_0as using about half the memory off16with a very small loss in precision, andq4_0as about a quarter, with more noticeable loss at long contexts. Quantized cache in Ollama requires Flash Attention to be enabled.
Offloading. Move parts of the cache to CPU memory and bring them back when needed. Transformers supports this with cache_implementation="offloaded". It saves GPU memory at the cost of speed.
Sliding windows. Some models only attend to the most recent tokens in some or all layers. Mistral 7B's configuration sets a 4,096-token sliding window. The cache then stops growing beyond the window, but the model can't directly see older tokens.
Eviction and attention sinks. Research systems drop less important tokens from the cache. The StreamingLLM paper found that simple window attention breaks once the text exceeds the cache size. Keeping the keys and values of the first few tokens, which act as "attention sinks", largely restores quality, so models can stream very long conversations with a fixed-size cache.
Faster attention kernels. Kernels such as FlashAttention don't shrink the KV cache, but they avoid materialising the large attention score matrix. That cuts the extra memory used during prefill on long prompts.
Why the KV Cache Matters More for Reasoning Models and Agents
Two recent shifts have made the KV cache a bigger share of serving costs.
Reasoning models write long hidden chains of thought. A model that "thinks" for several thousand tokens before answering keeps every one of those tokens in its cache until the answer is done. A short question can therefore use as much cache memory as a long document, and decode time grows with each extra token read on every step.
Agents run long, growing conversations. An agent that calls tools adds each tool result to the context and then continues. After a few dozen steps the context can reach tens of thousands of tokens, and every step decodes over the full cache. Two techniques help here:
- Prefix caching, so the stable start of the conversation (system prompt, tool definitions, earlier steps) isn't recomputed between calls.
- Context management, meaning summarising or trimming old tool output, so the cache stops growing without limit.
The practical lesson is the same for both: budget memory and latency by tokens in context, not by the length of the visible answer. A product that feels "short" to the user can be long for the KV cache.
Using the KV Cache in Practice
With Hugging Face Transformers, the cache is on by default in generate(). You can turn it off with use_cache=False (to see how much slower generation becomes), switch to a fixed-size StaticCache with cache_implementation="static" (which also enables compilation of the decoding step), or use the offloaded and quantized variants.
With vLLM, the engine reserves a share of GPU memory for the KV cache based on gpu_memory_utilization and the model's size. At startup it logs how many tokens of cache fit. If requests queue up or get preempted, the cache is the bottleneck: lower the maximum context length, quantize the cache, or add GPUs. For how vLLM compares with simpler local tools, see vLLM vs Ollama.
With llama.cpp and Ollama, the context size you set (-c in llama.cpp, num_ctx in Ollama) decides how much cache memory is allocated. Setting a 128K context "just in case" can use more memory than the model itself and push layers off the GPU. Size the context to what you actually use.
Worked Example: How Many Users Fit on One GPU?
Say you serve Llama 3.1 8B in BF16 on a single 80 GB GPU.
- Weights: about 16 GB.
- Runtime overhead and activations: assume about 6 GB.
- Left for KV cache: about 58 GB, or roughly 54 GiB.
- Cache per 8K-token conversation: 1 GiB.
That allows about 54 concurrent 8K-token conversations, before paging overheads. If every user used the full 128K context at 16 GiB each, only 3 would fit. With an FP8 cache, each figure roughly doubles.
The same arithmetic on Llama 2 7B (no GQA) gives about a quarter as many users, which is why the move to grouped-query attention mattered so much for serving costs.
Common Mistakes
- Planning GPU memory for weights only. At long contexts and real concurrency, the KV cache can exceed the model size.
- Setting a huge context window by default. Many engines allocate cache for the maximum context you configure.
- Comparing models by parameter count alone. Two 8B models can have very different cache sizes because of KV heads and layer count.
- Confusing the KV cache with response caching. The KV cache speeds up generating a new answer; it never returns an old answer.
- Ignoring prefill. Long prompts with short answers are dominated by prefill time; prefix caching helps there far more than faster decoding does.
- Quantizing the cache without testing. 8-bit is usually safe; 4-bit can hurt long-context accuracy. Check on your own tasks.
FAQ
Why is it called a KV cache?
Because it caches the K (key) and V (value) vectors from each attention layer. Queries aren't cached, because each new token only needs its own query.
Is the KV cache stored in GPU memory?
Usually yes, in the GPU's high-bandwidth memory, because every decode step reads it. Systems can offload parts of it to CPU memory or storage when GPU memory runs short, at a speed cost.
Does the KV cache change the model's output?
No. With standard precision the output is identical with or without the cache; it only avoids repeated computation. Quantizing or evicting parts of the cache can change outputs slightly.
How does context length affect the KV cache?
Linearly. Doubling the number of tokens in the conversation doubles the cache size, and longer caches also take longer to read on every decode step.
Is the KV cache the same as the context window?
No. The context window is the maximum number of tokens a model can attend to. The KV cache is the memory holding keys and values for the tokens actually in use, up to that limit.