Sub topic 3
The KV cache and why memory limits throughput
This chapter assumes you know the prefill and decode phases from the previous chapter, and that you can do basic arithmetic with bytes and GPU memory sizes. By the end you should be able to estimate how many tokens of KV cache fit on your GPU, and explain why that number caps the number of concurrent requests.
What the KV cache stores
A transformer computes attention at every layer. Each token produces a query, a key, and a value vector at each layer. The new token's query is compared against the keys of all earlier tokens, and the result weights their values.
The keys and values of earlier tokens never change during generation. Recomputing them for every new token would make each decode step cost more as the sequence grows. So the server computes them once and keeps them in GPU memory. This stored data is the KV cache (key-value cache).
- During prefill, the model processes the whole prompt in parallel and fills the cache for all prompt tokens.
- During decode, each step reads the whole cache for the sequence, appends one new key and value per layer, and produces one token.
The cache is per sequence. Two requests never share cache entries unless prefix caching applies, which a later chapter covers.
How big is the cache per token?
The size per token follows from the model's configuration:
bytes per token = 2 × num_layers × num_kv_heads × head_dim × bytes_per_elementThe leading 2 counts keys and values. For bf16 or fp16, bytes_per_element is 2.
The term num_kv_heads matters most. Older models use multi-head attention (MHA), where it equals the number of attention heads. Many newer models use grouped-query attention (GQA), where several query heads share one key/value head. GQA shrinks the cache by that grouping factor.
| Model | Layers | KV heads | Head dim | KV per token (bf16) |
|---|---|---|---|---|
| Llama-2-7B (MHA) | 32 | 32 | 128 | 512 KiB |
| Qwen2.5-32B (GQA) | 64 | 8 | 128 | 256 KiB |
| Qwen2.5-1.5B (GQA) | 28 | 2 | 128 | 28 KiB |
A 4,096-token sequence on Llama-2-7B holds 2 GiB of cache. That is a large share of a 24 GiB GPU, for one request. The same context on Qwen2.5-1.5B takes 112 MiB.
You can read these numbers from the model's config.json as num_hidden_layers, num_key_value_heads, and hidden_size / num_attention_heads. If num_key_value_heads is missing, the model uses MHA and the value equals num_attention_heads.
The GPU memory budget
vLLM does not allocate cache one request at a time. At startup it measures what is left after loading the model, then reserves that space as a pool. The budget works like this:
KV cache pool = gpu_memory_utilization × total GPU memory
− model weights
− peak activation memory
− other overheadPeak activation memory is measured by a profiling run during startup. The gpu_memory_utilization setting is the fraction of the GPU that this vLLM instance may use in total, and its default is 0.9. It is not the fraction used for cache.
The following script estimates the pool for a 24 GiB GPU using the settings from the offline example in this tutorial. The weight and overhead figures are approximations. Real values appear in the vLLM startup log.
GIB = 1024 ** 3
def kv_bytes_per_token(layers, kv_heads, head_dim, dtype_bytes=2):
# 2 = one key vector and one value vector per layer per KV head
return 2 * layers * kv_heads * head_dim * dtype_bytes
per_token = kv_bytes_per_token(layers=28, kv_heads=2, head_dim=128)
total_gpu = 24 * GIB
utilization = 0.85
weights = 2.9 * GIB # about 1.54B parameters in bf16
overhead = 1.5 * GIB # activations, CUDA context, buffers (estimate)
pool = utilization * total_gpu - weights - overhead
capacity_tokens = int(pool // per_token)
max_model_len = 4096
print(f"KV bytes per token: {per_token}")
print(f"KV pool: {pool / GIB:.1f} GiB")
print(f"Token capacity: {capacity_tokens:,}")
print(f"Full-length sequences that fit: {capacity_tokens // max_model_len}")This gives a pool of about 16 GiB and a capacity near 599,000 tokens. That is room for about 146 sequences of 4,096 tokens each. When vLLM starts, it logs a line of the form GPU KV cache size: N tokens and a maximum concurrency estimate for max_model_len. Compare those against your own estimate.
Why this limits throughput
Decode is bound by memory bandwidth, not by arithmetic. Each decode step must read all the model weights and the cache of every running sequence from GPU memory, and it does little math per byte read.
Batching helps because the weights are read once per step no matter how many sequences are in the batch. With 32 sequences in the batch, the weight-reading cost is shared across 32 new tokens. Throughput in tokens per second rises with batch size, until compute or cache reads become the bottleneck.
The cache pool sets the maximum batch size. Each running sequence holds cache for its prompt and everything generated so far. The sum over all running sequences must fit in the pool. Several things follow from that:
- A small pool caps concurrency. Extra requests wait in a queue, and queueing delay raises latency for them.
- Long contexts consume cache faster. One 32,000-token request can use as much cache as eight 4,000-token requests.
- Large per-token cache sizes (MHA models, many layers) reduce capacity directly.
- Cache reads grow with context length, so long-context decode is slower per token even with free memory.
When the pool fills during generation, the scheduler must preempt some sequences. It frees their cache and recomputes it later (or swaps it out, depending on version and configuration). This works, but wastes GPU time, and it shows up as latency spikes. Chapter 9 on memory tuning covers how to avoid it.
Common errors and misreadings
- Treating
gpu_memory_utilizationas the cache fraction. Weights come out of it first. On a small GPU with a large model, little may remain for cache. - Estimating with
num_attention_headsinstead ofnum_key_value_heads. For GQA models this overestimates the cache by the grouping factor, 6x for Qwen2.5-1.5B. - Forgetting the dtype. An fp8 KV cache (
--kv-cache-dtype fp8) halves the bytes per token compared with bf16, at some accuracy risk. Check support for your model and hardware before relying on it. - Setting
max_model_lenfar above what you need. vLLM refuses to start if the pool cannot hold at least one sequence of that length, and a high value also lowers the estimated concurrency. - Running other processes on the same GPU. The profiling step assumes it can use the fraction you set. Another process that holds memory can cause out-of-memory errors at startup.
Putting it to use
Use the budget as a first-pass sizing tool. Work out the per-token cache from config.json, subtract weights from your usable memory, and divide. If the capacity is too low for your expected concurrency times average context length, the options are a smaller context limit, a quantized model, an fp8 cache, or more GPUs. The later chapters on quantization and tensor parallelism cover each of those.
Exercise
A model has 40 layers, 8 KV heads, and a head dimension of 128, and uses a bf16 cache. How many bytes of KV cache does one token need? If 20 GiB remain for the cache pool, about how many 2,048-token sequences can run at once?
Show answer
Bytes per token = 2 × 40 × 8 × 128 × 2 = 163,840 bytes (160 KiB). One 2,048-token sequence needs 2,048 × 163,840 = 335,544,320 bytes (320 MiB). 20 GiB is 20,480 MiB, and 20,480 / 320 = 64 sequences.
Exercise
Why does a larger KV cache pool usually raise decode throughput, and what happens when the pool is exhausted mid-generation?
Show answer
Decode reads all model weights on every step, and that cost is shared across every sequence in the batch. A larger pool allows more concurrent sequences, so each weight read yields more tokens. When the pool is exhausted, the scheduler preempts some sequences, frees their cache, and recomputes it later, which wastes GPU time and increases latency.