Why AI Models Run Out of GPU Memory as Chats Get Longer (KV Cache Explained)
Why AI Models Run Out of GPU Memory as Chats Get Longer (KV Cache Explained)
A KV cache stores the key and value vectors (lists of numbers the model keeps about each word piece, explained below) a transformer, the design almost every modern language model uses, computed for tokens (chunks of text, about three quarters of a word each) it has already read. When the model writes the next token, it reads those stored vectors instead of recomputing them. Memory replaces repeated work. The size of that memory decides how many users and how much context (text the model looks at) one GPU, the graphics chip models run on, can serve.
New to these terms? Every word is explained in the series glossary.
The short version
Think of reading a long book and taking notes in the margin as you go. When you write the next sentence of your summary, you glance at your notes. You do not reread the whole book.
A KV cache is those margin notes. Every token the model has read gets a key vector and a value vector, saved in GPU memory (VRAM, the memory on the graphics card). The next token is written by attending to the notes, not by rereading the past. The notes grow with every token. That growth is what limits serving, meaning running the model to answer users.
What the cache actually holds
A transformer layer, one stage in the model's stack, turns each token into three vectors. A vector is just a list of numbers. The query vector asks a question. The key vector answers whether a past token is relevant. The value vector carries what that past token means.
Attention is the matching step. It scores each past token by matching the new query against the stored keys. Then it blends the stored values by those scores. The result shapes the next token.
Without a cache, generating token number 1,000 would mean recomputing keys and values for all 999 earlier tokens, in every layer. With a cache, the model computes keys and values for the one new token only. It reads the rest from memory. The saving is large. The cost is memory that grows by a fixed amount per token.
The query vector is not cached. Only keys and values are stored. That is why the formula has a factor of 2 and not 3.
Animation: Without a cache every step recomputes K and V for all earlier tokens. With it, only the new token's K and V are added.
Prefill and decode are two different jobs
Serving a language model has two phases. The cache behaves differently in each.
Prefill is the first phase. The model reads your whole prompt, the text you sent, at once. It computes keys and values for every prompt token. This phase is compute heavy. The GPU is busy doing matrix math, multiplying big grids of numbers, and the cache fills up fast.
Decode is the second phase. The model writes one token at a time. Each step reads the whole cache for that request, computes one new token, and appends one new entry. This phase is memory heavy. The math per step is small. The bottleneck is moving the cache from GPU memory to the compute units, the parts of the chip that do arithmetic. That is why decode is often described as memory bound.
Memory bound means the speed limit is moving data, not doing arithmetic. Compute bound means the speed limit is the arithmetic itself. Prefill is compute bound. Decode is memory bound.
| Phase | What happens | Bottleneck | Cache behaviour |
|---|---|---|---|
| Prefill | Whole prompt processed at once | Compute | Fills fast, all at once |
| Decode | One token per step | Memory bandwidth | Grows by one entry per step |
sequenceDiagram autonumber participant U as User participant M as Model participant C as KV cache (VRAM) U->>M: Whole prompt Note over M: Prefill: compute bound M->>C: Keys and values for every prompt token Note over C: Fills fast, all at once loop Decode: one token per step C->>M: Read the whole cache M->>M: Compute one new token M->>C: Append one new K and V entry M-->>U: Stream the new token end Note over M,C: Decode is memory bound: moving the cache is the limit
Diagram: Prefill fills the cache for the whole prompt at once. Decode reads it all and appends one entry per token.
How big is the cache? The formula, worked line by line
The formula is simple. It has six parts.
KV cache bytes = 2 x layers x KV heads x head dimension x sequence length x bytes per number
The 2 is for keys and values. Layers is the number of transformer layers. KV heads is the number of key-value head sets per layer. Head dimension is the length of each key and value vector. Sequence length is the number of tokens stored. Bytes per number is the precision, how many bytes (units of 8 bits) each number takes. It is 2 bytes for 16-bit formats like bfloat16.
Bfloat16 is a 16-bit floating point format, the way computers store decimals. It stores each number in 2 bytes. Most open models ship in bfloat16.
Here is the worked example for Llama-3-8B. It is an open 8-billion-parameter model (8 billion learned numbers, called parameters) released by Meta in 2024. Its public config file, the settings file published with the model, gives every number needed. The assumptions are stated here so you can check them.
- Layers: 32
- Query heads: 32 (attention heads are parallel attention units inside each layer)
- KV heads: 8, because Llama-3-8B uses grouped-query attention
- Head dimension: 128, from hidden size 4096 (the length of each token's main vector) divided by 32 query heads
- Precision: bfloat16, 2 bytes per number
- Context length in this example: 8,192 tokens
Grouped-query attention means several query heads share one set of keys and values. Llama-3-8B has 32 query heads and 8 KV heads. Four query heads share each set of notes. The technique is covered in full later in the article.
Step 1, one token in one layer. Keys and values for one token in one layer take 2 x 8 KV heads x 128 numbers x 2 bytes. That is 2 x 8 = 16, 16 x 128 = 2,048, 2,048 x 2 = 4,096 bytes. So one token costs 4 KiB (1 KiB is 1,024 bytes) per layer.
Step 2, one token across all layers. Every layer keeps its own notes, so multiply by 32 layers. 4,096 x 32 = 131,072 bytes. That is 128 KiB per token.
Step 3, the full sequence. Multiply by 8,192 tokens. 131,072 x 8,192 = 1,073,741,824 bytes. That is exactly 1 GiB, or 1.07 GB in decimal units.
Running the same arithmetic in Python, a common programming language, for several context lengths, with the config numbers above, gives this output. The five-line function further down reproduces it.
seq=4096: per-token=131072 bytes, total=536870912 bytes = 0.537 GB
seq=8192: per-token=131072 bytes, total=1073741824 bytes = 1.074 GB
seq=32768: per-token=131072 bytes, total=4294967296 bytes = 4.295 GB
seq=131072: per-token=131072 bytes, total=17179869184 bytes = 17.180 GB
At 128K tokens, one request carries about 17 GB of cache. The model weights are about 16 GB in bfloat16. At full context, the notes weigh more than the book.
Batching multiplies everything. A batch is a group of requests the GPU handles together. Sixteen requests at 8,192 tokens each need about 17.2 GB of cache, before weights or anything else. On an 80 GB GPU, weights take about 16 GB and this cache takes about 17 GB, which still fits. Double the context or double the batch and the picture changes fast.

Llama-3-8B keeps a key and a value for every token, in each of 8 KV heads, in each of 32 layers.
Why the cache decides what you can serve
Serving is a memory budget problem. The cache is the biggest variable line in that budget. Longer context and more users both eat the same GPU memory.
The PagedAttention paper behind vLLM, a popular open-source program for running models, measured how badly earlier serving systems handled this budget. They wasted 60 to 80 percent of KV cache memory on fragmentation (free memory broken into gaps too small to reuse) and space reserved for tokens that never arrived. With paged blocks the waste fell to under 4 percent. How the cache is managed decides how many requests fit on the same GPU.
Three limits follow from the arithmetic.
First, context length is a serving decision, not only a feature. Every extra token of context costs 128 KiB per request for Llama-3-8B in bfloat16. A 128K context window sounds free in a product announcement. In GPU memory it costs about 17 GB per request.
Second, concurrency is capped by cache, not by compute. Concurrency is how many requests run at the same time. A GPU can compute far more tokens per second than it can hold in cache. When the cache fills, new requests wait or get evicted. Eviction means throwing a request out of memory. That means recompute, doing the work again, which means latency. Latency is delay.
Third, the cache is why providers behave differently on the same model. How a provider (a company that runs models for you) pages the cache, shares prefixes between requests, and quantises stored values changes how many requests fit. Quantising means storing numbers in fewer bytes. Two providers running the same model can have very different throughput and cost. Throughput is how much work gets done per second. The cache is a large part of the reason.
What shrinks the cache
Five techniques matter. Each one trades something for memory.
Grouped-query attention shares one key-value head across several query heads. Llama-3-8B has 32 query heads and 8 KV heads, so four query heads share each set of notes. That cuts the cache four times compared with giving every query head its own keys and values. Multi-query attention goes further. It shares one KV head across all query heads.
Quantised cache stores keys and values in fewer bytes. The same arithmetic shows the effect. At 8,192 tokens, bfloat16 cache is 1.07 GB. The same cache in 8-bit precision, one byte per number, is 0.54 GB. The trade is a small quality loss. That loss must be measured, not assumed away. It depends on the model and the method, so this article gives no accuracy figure.
Prefix caching reuses the cache for a shared prompt prefix across requests. A prefix is the shared start of a prompt, often a long system prompt, the hidden instructions an app sends first. If a thousand users send the same long system prompt, the provider computes its keys and values once and shares them. vLLM calls this Automatic Prefix Caching. Its docs note that it speeds up the prefill step for repeated prefixes, such as many questions about one long document, but does not speed up decode.
Paged attention stores the cache in fixed-size blocks instead of one continuous chunk per request. This removes wasted space from reserving maximum context for every request. vLLM introduced this approach, and it is now standard in serving frameworks. A serving framework is the software that runs a model behind an API, the doorway programs use to send requests.
Sliding window attention, used by Mistral 7B (an open model from Mistral AI), keeps only the most recent tokens and drops older ones. Mistral 7B uses a window of 4,096 tokens and a rolling buffer cache, a store that overwrites its oldest entry, of that fixed size. It caps cache growth. The trade is that the model can no longer attend directly to the dropped past in that layer. Stacked layers pass some of that information forward, so the loss is softer than it sounds. But the direct view of old tokens is gone.
| Technique | How it shrinks the cache | What you give up |
|---|---|---|
| Grouped-query attention | Fewer KV heads to store | Small quality cost, fixed at training |
| Quantised cache | Fewer bytes per number | Small quality loss to measure |
| Prefix caching | Shared prefixes stored once | Only helps when prompts repeat |
| Paged attention | No wasted reserved space | Extra bookkeeping in the server |
| Sliding window attention | Old tokens dropped | Model cannot see the dropped past directly |
Copy-paste: estimate any model in five lines
This is the calculator logic in its simplest form. Paste your model config numbers in and run it.
pythondef kv_cache_gb(layers, kv_heads, head_dim, seq_len, bytes_per=2, batch=1): per_token = 2 * layers * kv_heads * head_dim * bytes_per return per_token * seq_len * batch / 1e9 print(kv_cache_gb(32, 8, 128, 8192)) # Llama-3-8B, 8K tokens: 1.07 GB print(kv_cache_gb(32, 8, 128, 131072)) # same model, 128K tokens: 17.18 GB print(kv_cache_gb(32, 8, 128, 8192, batch=16)) # 16 requests at 8K: 17.18 GB
Run it with Python 3 on any machine. No libraries needed. The three printed lines match the numbers worked out above.
Try this
Pick a model you use and find its config file on Hugging Face, the site that hosts open models. Read off layers, KV heads, and head dimension. If head dimension is not listed, divide hidden size by query heads. Plug the numbers into the five-line function with your real context length. Then double the context length and double the batch, one at a time, and watch which change hurts more.
What to read next
Worked out your cache size? See how much VRAM a full local setup needs, in the GPU and VRAM guide on blogllm.com. Then read the next article in this cluster, on speculative decoding, a trick for writing tokens faster, which is the other half of serving cost. The cache decides how much fits. Speculative decoding decides how fast it comes out.
FAQs
What is a KV cache in simple terms? It is the stored keys and values from tokens the model has already read. The model reads them instead of recomputing them when writing the next token.
How much KV cache does Llama-3-8B need? 128 KiB per token in bfloat16. That is 1 GiB at 8,192 tokens and about 17 GB at 131,072 tokens, for one request.
Why does the KV cache grow with context length? Every new token adds one key vector and one value vector per layer. Longer context means more stored tokens, and the cost per token is fixed.
Does a bigger batch need more KV cache? Yes. Each request in the batch has its own cache. Sixteen requests at 8K tokens need about 17 GB for Llama-3-8B.
What is prefix caching? It stores the keys and values for a shared prompt prefix once and reuses them across requests, instead of computing the same prefix for every user.
Sources
- Meta, Llama 3 model card. Llama 3 8B uses grouped-query attention. https://raw.githubusercontent.com/meta-llama/llama3/main/MODEL_CARD.md
- Meta, Meta-Llama-3-8B config file on Hugging Face: 32 layers, 32 attention heads, 8 KV heads, hidden size 4096, bfloat16.
- Kwon and colleagues, "Efficient Memory Management for Large Language Model Serving with PagedAttention", SOSP 2023. The vLLM paper; 60 to 80 percent KV memory waste in earlier systems versus under 4 percent. Summary: https://www.runpod.io/blog/introduction-to-vllm-and-pagedattention
- vLLM documentation, Automatic Prefix Caching. https://docs.vllm.ai/en/latest/features/automatic_prefix_caching/
- vLLM documentation, prefix caching design. https://docs.vllm.ai/en/latest/design/prefix_caching/
- Ainslie and colleagues, "GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints", EMNLP 2023. https://aclanthology.org/2023.emnlp-main.298.pdf
- Jiang and colleagues, "Mistral 7B", Mistral AI, 2023. Sliding window attention with a 4,096-token window and a rolling buffer cache.
