The KV cache keeps the attention keys and values from earlier tokens so a language model can reuse them as it generates the next token. On a local LLM, it can be the difference between a build that fits comfortably and a session that runs out of memory when you paste a long document.
For a standard full-attention model, estimate its size by multiplying the number of cached tokens by the number of attention layers, KV heads, elements in each head, and bytes per element. Multiply by two for keys and values. A real Qwen2.5-7B-Instruct configuration works out to 224 MiB at 4,096 tokens and 1.75 GiB at 32,768 tokens, for one sequence with a 16-bit cache, before runtime overhead. Transformers caching explanation, Qwen2.5-7B-Instruct configuration
- The cache is working state for a sequence. Weight quantization and cache precision are independent choices.
- Use the KV head count in the model config for a traditional grouped-query attention model.
- Estimate your actual prompt and output together, then check what your runtime reserves.
- Test a shorter context first if the model loads and the problem appears only on long requests.

What does the KV cache store?
Each layer that uses self-attention computes queries, keys, and values. The query for a new token helps determine which earlier positions to attend to. The keys and values already computed for those earlier positions can be saved. During generation, the model computes the new token’s state and can reuse the earlier keys and values. The cache is especially helpful because autoregressive decoding adds new output tokens one at a time. Transformers caching explanation
Think of the cache as state the model builds while reading. The weights are fixed for the session, but cached tensors depend on the exact tokens the application has given the model. Tokenized instructions, previous chat turns, retrieved passages, or tool results can all contribute to the same session’s context. Some servers can reuse a prefix shared by multiple requests, depending on their cache implementation. vLLM automatic prefix caching
Prefill is the phase that reads the prompt and populates the initial cache. Decode uses that state to generate output. The cache avoids redoing key and value projections for the entire prompt on every step. In full attention the new token still attends over earlier cached positions, so a longer context can change both memory use and generation speed. Transformers caching explanation
How much memory does a KV cache use?
Use this calculation for one model with full attention in every layer, equal key and value head dimensions, full-precision cache storage at the chosen element width, and no prefix sharing:
cache_bytes =
2 × attention_layers × kv_heads × head_dimension
× bytes_per_element × cached_tokens × sequences
For decoder-only text models with grouped-query attention, the number of query heads can differ from the number of KV heads. Groups of queries share a key-value head. Use num_key_value_heads where the config supplies it. If a conventional model omits an explicit head dimension, check how its implementation derives it before substituting hidden size divided by the query head count. Grouped-Query Attention paper, Qwen2.5-7B-Instruct configuration
A worked example with Qwen2.5-7B-Instruct
The published config lists a hidden size of 3,584, 28 query heads, four KV heads, and 28 layers. The conventional head dimension is 3,584 ÷ 28 = 128. At two bytes per element and one sequence, the formula gives 2 × 28 × 4 × 128 × 2 = 57,344 bytes per token, or 56 KiB. Multiply by your token budget to get the raw KV allocation. Qwen2.5-7B-Instruct configuration
| Cached tokens | Estimated 16-bit KV data |
|---|---|
| 2,048 | 112 MiB |
| 4,096 | 224 MiB |
| 8,192 | 448 MiB |
| 16,384 | 896 MiB |
| 32,768 | 1.75 GiB |
Now suppose the backend has 768 MiB spare for KV tensors after accounting for the weights and other allocations. Divide that by 56 KiB per token, and the arithmetic ceiling is about 14,043 tokens. A 12,288-token starting budget would leave roughly 96 MiB before overhead in this example. A live test still has to account for any padding, static reservations, and workload bursts. The model’s own supported context can impose a separate limit.
If you have two live sessions that both keep 8,192 distinct positions, budget the equivalent of 16,384 positions. A shared-prefix implementation can lower the physical storage for reused blocks. Use its actual reporting to validate the difference. vLLM automatic prefix caching
Check the estimate against a real launch
Run the same model twice with different configured contexts and record the runtime's KV-cache allocation, if it prints one. For example, hold the weight build, backend, cache types, and concurrency steady while comparing 4,096 and 8,192 positions. Subtract the allocations to estimate the cost of the extra 4,096 positions. If the result is close to the Qwen example's extra 224 MiB, the change is consistent with full-length 16-bit cache growth. llama.cpp CLI context and cache settings
Then compare system-wide or device memory at the same stages. This separates the memory the runtime attributes to KV tensors from extra work done while it ingests the prompt. If your app opens several server slots, repeat the check with the production slot count, since a server can divide or reserve its context budget differently. llama.cpp server configuration
Why might the observed cache be bigger or smaller?
Some runtimes allocate cache as tokens arrive. Others reserve enough for the configured context at startup. With static allocation, reducing the actual text in a prompt may save compute without giving the reserved memory back. Try lowering the configured context and reloading the model to find out which behavior applies. Transformers cache strategies
The formula estimates raw tensors for one standard layout. An allocator can pad or round blocks, and quantized blocks need scales or other metadata. Architectures that combine sliding-window or chunked attention with global layers can retain different numbers of positions by layer. A model with compressed latent state can require architecture-specific arithmetic. Check cache documentation and runtime logs when one of those applies. Transformers cache strategies, DeepSeek-V2 technical report
You may also see GPU memory used by intermediate buffers or backend workspaces while reading a long prompt. Compare the reported cache allocation with peak memory during prefill. A large gap is a reason to inspect batch settings and other runtime components. In llama.cpp, the CLI documents context and batch controls alongside separate key and value cache types. llama.cpp CLI documentation
How do you reduce KV cache memory?
Lower the context to fit the job. Keep the system instructions and useful history, and remove unnecessary pasted text or verbose tool output. For retrieval, include the passages you actually need. Leave space for the model’s expected output inside the context limit.
Evaluate a smaller cache type. If your backend supports it, try cache quantization with a representative long prompt. Compare answer correctness and latency against the default cache precision. A result on a short chat is weak evidence for behavior when the model must recover a detail far back in context. KIVI KV-cache study, llama.cpp CLI cache settings
Consider offload under pressure. Some backends can move parts of the cache to CPU memory. This can reduce the device footprint while adding transfer work. Compare first-token latency and generation changes on the contexts you use. Transformers cache strategies
Count concurrent sequences. If you run a local server that accepts multiple sessions or uses parallel outputs, check the total number of live tokens and the runtime’s cache scheduling behavior. A single request may be fine while several concurrent requests reach the limit.
The Edge0 35B runtime documentation gives an example of why the layers of memory accounting matter. It describes expert weights loaded from disk on demand and separately reports runtime memory for fixed or swept prompt sizes. Use the model’s own runtime documentation and measurements for real sizing, especially when the engine uses specialized weight placement. Edge0-35B model guide, Edge0 benchmark methodology
For the rest of the memory budget, see our local LLM RAM guide. Use the GGUF Size Calculator to estimate the weight files you will download.
FAQs
Is a KV cache the same thing as the context window?
The context window is the token span the model or runtime can work with. The KV cache holds attention state used for those tokens. Depending on the implementation, a runtime may reserve capacity up to the configured context window or let the cache grow as tokens arrive. Transformers cache strategies
Does a 4-bit model have a 4-bit cache?
Weight and cache formats are chosen independently. A runtime can load 4-bit weights and still store attention cache elements at 16 bits. Check its cache settings and hardware support before planning around a smaller cache. llama.cpp weight quantization, llama.cpp CLI cache settings
Why does my local model fail on a long prompt after loading?
The model may need more memory for cached tokens or workspaces during prompt processing. Try a shorter context, then compare the reported cache and peak memory for both runs. If the runtime is already close to the limit at startup, compare a smaller model build as well. Transformers cache strategies
To budget your next local LLM session, estimate the KV cache from the model configuration, leave room for the completion, and check the runtime’s real allocation with the longest prompt you expect to send.