What is a KV cache?
A KV cache is the memory where a transformer keeps the key and value vectors it has already computed for every token in a sequence, at every layer, so each new output token reuses them instead of recomputing attention inputs for the whole prefix. It lives inside one generation request and grows by one entry per token. Its size scales with sequence length times the number of sequences in flight, which is why it limits how many long requests a GPU can serve at once.
What does the KV cache store?
Attention compares each token's query against the keys of the tokens before it, then takes a weighted sum of their values. A decoder model generates one token at a time, and without a cache it would recompute the keys and values for the entire prefix on every step. The Hugging Face Transformers documentation describes the KV cache as storing those calculations so they can be reused without recomputing them.
The cache holds one key tensor and one value tensor per layer, per key-value head, per token. The prefill pass fills it for the whole prompt in one go. Each decode step then appends one token's worth of entries and reads all of the earlier ones. When the request ends, the server frees the memory.
The term gets used two ways. In product copy, "caching" usually means prompt caching: a provider keeps the cache for a repeated prefix and bills those input tokens at a lower rate on the next request. In inference code, the KV cache is the per-request structure that exists on every call whether or not anything is reused across requests. On a hosted API you never see it. On your own GPU you size it.
How big does it get?
Bytes per token are 2 (one key, one value) times layers times key-value heads times head dimension times bytes per number. Multiply by sequence length and by the number of sequences running at once. Unlike the weights, which are a fixed cost, this number grows with every token of context you allow and every request you batch.
The architecture sets the per-token figure. Grouped-query attention, described by Ainslie et al. in 2023, gives the model fewer key-value heads than query heads, and the cache shrinks in proportion. Qwen2.5-7B-Instruct has 28 query heads and 4 key-value heads, so its cache is one seventh of what full multi-head attention would need, as the example below works out from the model's published config.
Why does it limit how many requests a server can run?
Throughput on a GPU comes from batching many requests together, and each request in the batch needs its own cache. Kwon et al. found that earlier serving systems wasted much of this memory through fragmentation and duplicate copies, which kept batches small. Their PagedAttention algorithm stores the cache in fixed-size blocks, the way an operating system pages virtual memory, and vLLM is built on it. The paper reports near-zero KV cache waste and 2 to 4 times the throughput of FasterTransformer and Orca at the same latency.
When the cache still runs out, vLLM preempts a request, frees its blocks, and recomputes it later. Its log prints a warning that the sequence group was preempted because there is not enough KV cache space. The vLLM tuning guide lists the knobs: give the cache more GPU memory with gpu_memory_utilization, admit fewer concurrent requests with max_num_seqs or max_num_batched_tokens, or split the weights across more GPUs with tensor_parallel_size so more memory is left for the cache.
What can you change in your code?
- Cap the context. A lower maximum sequence length is the direct way to shrink the worst-case cache per request.
- Pick a cache layout. In Transformers,
DynamicCacheis the default and grows as tokens arrive.cache_implementation="static"preallocates a fixed size so the decoding step can be compiled withtorch.compile. - Trade speed for memory.
cache_implementation="offloaded"keeps only the current layer's cache on the GPU and the rest on the CPU.cache_implementation="quantized"stores keys and values at lower precision through thehqq,quantoorfp8backends. The documentation warns both can cost speed. - Reuse a prefix. Fill a cache once for a shared system prompt, copy it, and generate from the copy for each user prompt. The Transformers docs call this prefix caching.
Sizing the KV cache for Qwen2.5-7B-Instruct from its config
$ cat kv.py
import json, urllib.request
url = "https://huggingface.co/Qwen/Qwen2.5-7B-Instruct/raw/main/config.json"
c = json.load(urllib.request.urlopen(url))
layers, kv_heads = c["num_hidden_layers"], c["num_key_value_heads"]
head_dim = c["hidden_size"] // c["num_attention_heads"]
per_token = 2 * layers * kv_heads * head_dim * 2 # K and V, bf16 = 2 bytes
print(f"layers={layers} kv_heads={kv_heads} head_dim={head_dim}")
print(f"per token: {per_token / 1024:.0f} KiB")
for n in (4_096, 32_768):
print(f"one {n:>6}-token sequence: {per_token * n / 2**30:.2f} GiB")
mha = 2 * layers * c["num_attention_heads"] * head_dim * 2
print(f"same model without GQA: {mha / 1024:.0f} KiB per token")
$ python3 kv.py
layers=28 kv_heads=4 head_dim=128
per token: 56 KiB
one 4096-token sequence: 0.22 GiB
one 32768-token sequence: 1.75 GiB
same model without GQA: 392 KiB per token
The script reads the layer and head counts from the model's published config.json and assumes a bf16 cache, the model's stored dtype. At its 32,768-token maximum, one sequence needs 1.75 GiB of cache on top of the weights, so ten such requests in flight need 17.5 GiB. The last line shows what the same model would need per token with one key-value head per query head.
Common questions
KV caches: frequently asked
Is a KV cache the same thing as prompt caching?
No. The KV cache exists inside every generation request and is thrown away when the request ends. Prompt caching is a provider feature that keeps the KV cache for a repeated prefix so the next request can skip that part of prefill. Prompt caching depends on the KV cache, but you get a KV cache on every call either way.
Do I need to do anything about the KV cache when I call a hosted API?
Not directly. The provider allocates and frees it, and you see its effects only as context limits, rate limits and the price of long prompts. It becomes your problem when you serve an open-weight model yourself, where it decides how many concurrent long requests one GPU can hold.
Why does my self-hosted model slow down under load without running out of memory?
Check the server log for preemption. When vLLM runs short of KV cache space it evicts a running request and recomputes it later, which the vLLM docs say can affect end-to-end performance; no error is raised. Giving the cache more memory or admitting fewer concurrent sequences reduces how often it happens.
Can I turn the KV cache off?
In Transformers, yes: pass use_cache=False to generate(). The model then recomputes keys and values for the whole prefix at every step, which is the work the cache exists to save. vLLM manages memory around the cache through PagedAttention, so on a serving engine the useful settings are how much memory the cache gets and how many sequences share it.
Sources
Where these facts come from
- Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023): KV cache fragmentation limiting batch size, block-based PagedAttention, and the 2 to 4 times throughput result for vLLM
- Hugging Face Transformers docs: Cache strategies: what the KV cache stores, DynamicCache, StaticCache, offloaded and quantized caches, use_cache=False and prefix reuse
- vLLM docs: Optimization and tuning: preemption when KV cache space runs out, the warning it logs, and the gpu_memory_utilization, max_num_seqs and tensor_parallel_size knobs
- GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints (Ainslie et al., 2023): grouped-query attention: fewer key-value heads than query heads, which shrinks the cache
- Qwen2.5-7B-Instruct config.json: layer count, attention heads, key-value heads and dtype used in the worked example