A KV cache is the memory an autoregressive transformer keeps so it does not reprocess the entire conversation for every new token. It stores the key and value tensors produced by every attention layer for the tokens already in the sequence, letting the model reuse that layer-specific state instead of recomputing the complete prefix at each step. The reason it consumes so much VRAM is that it is not a fixed buffer: it grows by one entry per token, per layer, and it is usually held in the same 16-bit format as the model’s activations.
This explainer covers what is actually stored, how to estimate the cost for a specific model before you load it, how to tell whether the cache is what is exhausting your GPU, and which levers reduce it. It assumes you run models locally through a runtime such as llama.cpp or Ollama and have seen a model that loads fine fail once the conversation gets long.
What the KV cache holds, and why queries are not in it
Generation happens in two phases. During prefill, the model processes the prompt tokens together and stores their keys and values at every cache-producing layer. The final prompt representation produces logits for the next token. Suppose the decoding rule selects a new token. On the next model call, the input can be just that new token together with the cache for the original prompt. Each layer computes a query, key, and value for the new token; its query attends to the cached keys and values plus the new pair, and the new key and value are appended to the cache.
Without caching, that second call would run the entire prompt plus the new token through the whole model again, repeating the hidden states and attention projections for tokens that were already processed. The same redundancy would grow at every later step.
Queries are deliberately absent from the growing cache. A query represents the token whose attention output is being computed at the current step. Future tokens need earlier keys and values as the items they can attend to, but they never reuse earlier queries, so there is nothing worth storing.
One consequence is easy to miss. Caching removes repeated prefix projections and repeated processing of earlier token states, but it does not remove the attention work or the memory traffic over the retained prefix. The new query still has to interact with every retained key and value in a full-attention layer. That remaining cost is exactly what becomes painful at long context lengths.
Why the cache grows with every token
A basic implementation keeps cache_k and cache_v tensors in each attention block, with a sequence dimension that grows as generation proceeds. The size follows directly from that structure:
KV bytes = 2 × n_layers × n_kv_heads × head_dim × seq_len × bytes_per_elementThe leading 2 accounts for the key and value tensors. n_kv_heads is the number of key/value heads, which is smaller than the number of attention heads in models that use grouped-query attention (GQA). bytes_per_element is 2 for float16 or bfloat16, the usual default.
Separate the fixed terms from the variable one. Layers, KV heads, and head dimension are properties of the model. Sequence length is a property of your session, and it only increases. That is why the same model can run comfortably in a short chat and fail after a long one, with no change to the model file.
Sizing it for a real local model
The NVIDIA KVPress write-up provides a useful anchor: handling 1M tokens with Llama 3-70B in float16 demands 330 GB for the KV cache, which the authors describe as rendering it infeasible for many applications.
That figure is reproducible from the formula. Llama 3-70B uses 80 layers, 8 key/value heads, and a head dimension of 128:
2 × 80 × 8 × 128 × 1,000,000 × 2 bytes ≈ 327.7 GBwhich rounds to the 330 GB in the source. This is arithmetic, not a measurement, but it confirms the order of magnitude and shows how completely the sequence term dominates once context gets large.
The same arithmetic at ordinary context lengths is more useful for planning. The table below is computed from the formula using published architecture parameters for two common configurations, at float16. Nothing in it is measured on hardware.
| Configuration | Layers | KV heads | Head dim | Per token | 8K context | 32K context |
|---|---|---|---|---|---|---|
| 8B-class (32/8/128) | 32 | 8 | 128 | 128 KiB | 1.0 GiB | 4.0 GiB |
| 70B-class (80/8/128) | 80 | 8 | 128 | 320 KiB | 2.5 GiB | 10.0 GiB |
Two caveats matter when you compare these numbers to what a monitoring tool reports. First, they cover the KV cache only. Total VRAM also includes model weights, the compute buffer, activations, and runtime overhead, so a 4 GiB cache will not fit on a 4 GB card. Second, many llama.cpp-based runtimes reserve the cache for the configured context size when the model loads rather than growing it gradually, which is why raising a context setting can push a previously stable setup over the limit immediately. Watching VRAM at load time in your own runtime will tell you which behavior you have.
Why it rivals the weights in VRAM terms
Three multipliers do the damage. Every layer keeps its own copy of the cache, so the cost scales with depth. Every token adds an entry, so the cost scales with conversation length. And the cache is normally stored at 16 bits per element, the same precision as the activations flowing through the model.
Weights, by contrast, are a fixed cost that you can shrink once with quantization. A 4-bit quantized 8B model occupies roughly 5 GB of weights, and that number does not change whether you send one token or thirty thousand. A 32K float16 KV cache adds about 4 GiB on top of it, and it is the part that grows with use. In long-context sessions the cache can approach or exceed the weight footprint, which is why fitting the model and fitting the session are two different questions.
Diagnosing a KV-cache VRAM problem
The cache is the likely culprit when the failure pattern looks like this:
- The model loads without error, then fails with a CUDA out-of-memory error during generation rather than at load.
- VRAM usage climbs steadily as a conversation continues.
- Reducing the context setting fixes the failure without changing the model or quantization.
- A shorter prompt succeeds where a longer one fails on the same model.
Work through these checks in order, cheapest first:
- Compare load-time VRAM at two context sizes. Same model, same quantization, one small context and one large. If the difference roughly tracks the table above, the cache is the cost you are paying.
- Watch VRAM across a long generation. A monotonic climb points at a per-token structure, which is the cache.
- Halve the context size and rerun the failing prompt. If the failure disappears, the sequence term is implicated.
- Check for partial CPU offload. If some layers are running on the CPU, the cache problem can present as a slowdown rather than an error, and the VRAM reading will understate what the model needs.
If none of these change anything, the cache is probably not your bottleneck and the weights, the compute buffer, or another process on the GPU deserve attention instead.
Practical levers, ordered by cost to you
- Reduce context size. The most direct control. Halving sequence length halves the cache.
- Quantize the KV cache. Storing keys and values at 8-bit or 4-bit instead of 16-bit cuts the cache by roughly 2× or 4×. Quality effects depend on the model and the task, so measure on your own workload rather than assuming.
- Choose a model with fewer KV heads. GQA already reduces
n_kv_heads; multi-query attention reduces it further. This is a model-selection decision, not a runtime flag. - Use attention variants or cache compression. Sliding-window attention caps how far back the cache must reach, at the cost of changing what the model can attend to. Toolkits such as KVPress implement KV cache compression specifically for long-context work.
- Offload the cache to CPU RAM or disk. Trades VRAM pressure for latency.
- Use memory-efficient attention kernels. Paged attention and similar implementations reduce fragmentation and overhead, but they do not change the fundamental per-token size.
In llama.cpp-based runtimes the relevant knobs are typically the context size flag (--ctx-size or -c), the KV cache data type flags (--cache-type-k and --cache-type-v), and flash attention (--flash-attn). Ollama exposes context length as the num_ctx parameter. Flag names and defaults change between versions, so confirm them against the documentation for the build you are running before relying on them.
Limits and tradeoffs
Every lever above costs something. KV quantization is a lossy change and its effect is workload-dependent. Sliding-window attention and cache compression alter which tokens the model can see, which can matter for retrieval over long documents. Cutting context length can break a RAG pipeline that depends on a large window.
Concurrency multiplies the problem. Each active sequence keeps its own cache, so serving several requests in parallel multiplies the memory requirement even when each request is short. If you are sizing a machine for a shared local endpoint, plan for the number of simultaneous sequences, not just the maximum context of one.
What to do next
Estimate before you load. Take the model’s layer count, KV head count, and head dimension, run them through the formula at the context size you actually intend to use, and compare the result to your available VRAM after subtracting weights and overhead. If the estimate is close to your limit, set the context deliberately, then try KV quantization, then consider compression or offload. If you have measured numbers from your own hardware, sharing the model, quantization, context size, and observed VRAM is far more useful to other readers than a general impression of what fits.
FAQ
Does the KV cache store queries as well as keys and values?
No. A query represents the token whose attention output is being computed at the current step. Future tokens need earlier keys and values as the items they can attend to, but they never reuse earlier queries, so queries are not retained in the growing cache.
Is the KV cache included in a model's stated VRAM requirement?
Usually not. Weight size is reported separately from the cache, which depends on the context length you configure and on how long the session runs. Total VRAM also includes the compute buffer, activations, and runtime overhead, so a cache that fits on paper may still not fit in practice.
Does quantizing the KV cache change output quality?
It is a lossy change, and the effect depends on the model and the task. It cuts cache memory by roughly 2x at 8-bit and 4x at 4-bit relative to float16, but the quality impact should be measured on your own workload rather than assumed.
Why does VRAM jump as soon as the model loads, before I generate anything?
Many llama.cpp-based runtimes reserve the cache for the configured context size at load time rather than growing it dynamically. That makes the full context cost visible immediately, and it explains why increasing a context setting can push a previously stable setup over the limit.