Sub topic 10
Tuning memory and concurrency
This chapter assumes you can run vllm serve, know what the KV cache is, and have read the earlier chapters on PagedAttention and continuous batching. It covers the three settings that decide how many requests a vLLM instance can serve at once: gpu_memory_utilization, max_model_len, and max_num_seqs.
The memory budget
At startup vLLM loads the weights and runs a profiling pass with a dummy batch to measure peak activation memory. It then gives the remaining memory, up to the allowed fraction, to the KV cache. The cache is divided into fixed-size blocks, as described in the PagedAttention chapter.
The number of blocks in the KV cache sets how many tokens can be in flight across all requests. Your settings only shape that pool and how requests share it.
gpu_memory_utilization
gpu_memory_utilization is a fraction between 0 and 1, and the default is 0.9. It limits the memory this vLLM instance may use on each GPU. Note that it is a per-instance cap and not a per-process guess about free memory.
- Raising it gives the KV cache more blocks, so more concurrent tokens fit.
- Lowering it leaves headroom for other processes on the same GPU, such as a second model server or a desktop session.
- Setting it too high causes out-of-memory errors at startup or, on some setups, later when memory use spikes.
If another process already holds memory on the GPU, vLLM may refuse to start because the requested fraction is not available. Lower the value or stop the other process.
max_model_len
max_model_len is the longest sequence vLLM accepts, counting the prompt and the generated tokens together. By default vLLM takes it from the model config. Many modern models advertise 32k, 128k, or more.
This setting matters for two reasons.
- At startup vLLM checks that the KV cache can hold at least one sequence of this length. If it cannot, the server fails with an error saying the maximum length is larger than the cache can store. The fix is to lower
max_model_len, raisegpu_memory_utilization, or add GPUs. - A lower limit does not reserve memory per request, because blocks are allocated on demand. It does cap the worst case a single request can consume.
Requests that exceed the limit are rejected with an error. Set the value to what your workload needs, not to the model's maximum.
max_num_seqs
max_num_seqs is the maximum number of sequences the scheduler runs in one step. Think of it as a cap on the batch size. The default depends on the version and the hardware, so check the engine log for the value in use.
The KV cache and max_num_seqs limit concurrency together, and the smaller limit wins.
| Situation | What limits concurrency | Symptom |
|---|---|---|
| Short requests, small cache | KV cache blocks fill first | Waiting requests grow while the cache usage is near 100% |
| Short requests, large cache | `max_num_seqs` | Cache usage stays low while requests wait |
| Long requests | KV cache blocks | Few sequences run even though `max_num_seqs` is high |
A higher max_num_seqs raises throughput until the GPU is saturated. After that it only adds latency per request, because every decode step handles more sequences. It also raises the activation memory used in profiling, which leaves less for the KV cache.
Preemption
If the cache runs out while sequences are running, the scheduler preempts some of them. It frees their blocks and later recomputes them, or in some versions swaps them out. Preemption keeps the server alive but costs throughput, since work is redone. The engine logs a warning when it happens. If you see it often, reduce max_num_seqs, reduce max_model_len, or give the cache more memory.
A worked sizing example
Take a model with 28 layers, 2 KV heads, a head dimension of 128, and 16-bit values. The KV cache holds a key and a value per layer per token. The size per token is:
layers = 28
kv_heads = 2
head_dim = 128
bytes_per_value = 2 # fp16 or bf16
kv_per_token = 2 * layers * kv_heads * head_dim * bytes_per_value
print(kv_per_token) # 28672 bytes, about 28 KiB
cache_gib = 20
tokens_in_cache = cache_gib * 1024**3 // kv_per_token
print(tokens_in_cache) # about 749,000 tokens
avg_request_tokens = 2000
print(tokens_in_cache // avg_request_tokens) # about 374 concurrent requestsWith a 20 GiB cache and 2,000 tokens per request, memory allows roughly 370 concurrent requests. If max_num_seqs is 256, the scheduler limit applies first. If the average request grew to 8,000 tokens, memory would allow only about 93.
Models with more KV heads, or without grouped-query attention, need far more memory per token. Check num_key_value_heads in the model's config.json before you estimate.
Setting the values in practice
Start from the workload, not from the maximums.
- Measure or estimate the longest prompt plus output you must support. Set
max_model_lenslightly above it. - Start
gpu_memory_utilizationat 0.85 to 0.9 if the GPU is dedicated to vLLM. - Read the startup log for the KV cache size and the maximum concurrency vLLM reports for your
max_model_len. - Set
max_num_seqsnear the concurrency your traffic needs and your memory supports. - Load test, and watch preemptions and the waiting queue.
The offline API takes the same arguments as the server flags:
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
gpu_memory_utilization=0.85,
max_num_seqs=128,
)
outputs = llm.chat(
[{"role": "user", "content": "Name three uses of a KV cache."}],
SamplingParams(temperature=0.2, max_tokens=64),
)
print(outputs[0].outputs[0].text)The server equivalent is:
vllm serve Qwen/Qwen2.5-1.5B-Instruct \
--max-model-len 4096 \
--gpu-memory-utilization 0.85 \
--max-num-seqs 128Common errors
- Startup fails with a message that the KV cache cannot hold the maximum length. Lower
max_model_lenor raise memory. Do not just raisemax_num_seqs. - CUDA out of memory at startup. Lower
gpu_memory_utilization, lowermax_num_seqs, or check that no other process is using the GPU. - Out of memory under load. Memory spikes outside vLLM's accounting, for example from another process, can break a tight setting. Leave a margin.
- Low throughput with low cache usage.
max_num_seqsis probably the limit. Raise it and measure. - High latency with a long waiting queue. The server is saturated. Add capacity, shorten requests, or reduce load.
When tuning is not enough, the next options are quantization to shrink the weights and tensor parallelism to spread the model across GPUs. Both are covered in later chapters.
Exercise
A model needs 36 KiB of KV cache per token. Your vLLM instance has a 12 GiB KV cache, requests average 3,000 tokens, and maxnumseqs is 64. Roughly how many requests can run at once, and which setting limits it?
Show answer
The cache holds 12 × 1024³ / (36 × 1024) ≈ 349,525 tokens. At 3,000 tokens per request that is about 116 requests. Because maxnumseqs is 64, the scheduler limit applies first, so about 64 requests run at once. Raising maxnumseqs toward 116 could increase throughput, until the GPU is saturated.
Exercise
The server fails to start and reports that maxmodellen is larger than the KV cache can hold. Give two changes that can fix this and say why they work.
Show answer
Lower maxmodellen, because the cache then only has to hold one shorter sequence. Raise gpumemoryutilization, because more memory goes to the KV cache. Adding GPUs with tensor parallelism or using a quantized model also works, since both free memory for the cache.