Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Launch overhead | The CPU time to start one GPU operation from Python: interpreter, argument checks, dispatch, the launch itself. A few microseconds each. |
| CUDA graph | A recording of a sequence of GPU operations that can be replayed with one call (5.f). |
| Capture | Recording a CUDA graph by running the code once in a special mode. |
torch.compile | PyTorch’s compiler. It traces a Python function into a graph of operations and generates faster code for it (13.m). |
| Inductor | The part of torch.compile that generates the kernels. |
| Fusion | Merging two or more operations into one kernel so data is not written to memory in between. |
| Piecewise | Recording the model in pieces, with attention left outside the recordings. |
| Uniform batch | A batch where every request contributes the same number of tokens: 1 for plain decode, 1 + k with k speculative tokens. |
1. What is it?#
A decode step for a small model is thousands of tiny GPU operations, and Python needs a few microseconds to launch each one. For a large model that overhead is lost in the arithmetic; for a small one it can exceed the arithmetic. vLLM removes it in two ways:
torch.compileturns the model’s Python forward function into optimised code once, at startup.- CUDA graphs then record the whole sequence of GPU work for one batch shape and replay it with a single call.
Both are done ahead of time for every batch size the scheduler might produce. That is why a vLLM server takes a minute to start and does not stutter afterwards. The price is startup time, GPU memory and a little padding.
The general ideas belong to 13.k (CUDA graphs in serving) and 13.m (compilers). This lesson is vLLM’s implementation in v0.32.0. Facts checked on 12 November 2026.
2. Why does it exist?#
1,300 operations × 10 µs ≈ 13 ms of pure overhead per step
decode step, large model, large batch arithmetic 30 ms overhead 13 ms noticeable
decode step, 1B model, batch of 4 arithmetic 3 ms overhead 13 ms dominantA CUDA graph removes the overhead but is rigid: same operations, same shapes, same memory
addresses; only the contents of the inputs may change. That rigidity fits vLLM well. Thanks to
the flat batch (18.b), the shape of a step is described by one number, the total token count.
And torch.compile is needed first because vLLM’s graph splitting, fusions and custom passes
all operate on the traced graph.
3. Simple analogy#
A conductor normally cues every instrument by hand, each cue taking a moment. A CUDA graph is a recording of the whole piece: press play once and it runs. But the recording is for one exact number of players. So the orchestra records the piece for 1, 2, 4, 8, … players, and on a night with 37 players it uses the 40-player recording with three empty chairs.
4. Tiny example#
max_num_seqs 256, no speculative decoding, H100
capture ladder 1, 2, 4, 8, 16, 24, ..., 248, 256, 272, ..., 512 (51 sizes)
step with 37 decoding requests uniform -> FULL graph for 40 tokens, 3 rows wasted
step with 30 decodes + 1 prefill not uniform -> PIECEWISE graphs for the padded size
step with an 8,000-token prefill > 512 -> eager, op by op: overhead is negligible here5. Technical explanation#
Compilation: torch.compile#
Compilation is on by default; the design document calls it “a critical part of the framework”.
Three properties differ from ordinary torch.compile use.
Everything is compiled before the first request.
A unique aspect of vLLM’s
torch.compileintegration, is that we guarantee all the compilation finishes before we serve any requests. No requests will trigger new compilations.
Normally torch.compile compiles lazily and recompiles on a new shape, which in a server would
stall some unlucky request for seconds. vLLM compiles with a dynamic token dimension and drops the
shape guards that would trigger recompilation. compilation_config.dynamic_shapes_config lets you
choose between backed (default), unbacked and backed_size_oblivious symbols, trading
guarantees against missed optimisations.
The result is cached on disk.
Using cache directory: ~/.cache/vllm/torch_compile_cache/1517964802/rank_0_0 for vLLM's torch.compileThe directory name is a hash of everything that could change the generated code: the relevant
vLLM configuration (every config class has a compute_hash()), the PyTorch configuration and the
source of the forward function. SchedulerConfig’s hash includes max_num_batched_tokens
because buffers sized from it are baked into the compiled code. If you set TRITON_CACHE_DIR,
copy it too.
The graph is split at attention. Attention often cannot be recorded (its behaviour depends on
the batch). vLLM’s compilation backend splits the traced graph at each attention call into
pieces. This is piecewise compilation, and it is what makes PIECEWISE graphs possible.
Compilation also runs vLLM’s own graph passes, called fusions (13.j), controlled by
-cc.pass_config.*:
| Pass | Fuses |
|---|---|
fuse_norm_quant | RMSNorm with the quantisation that follows it |
fuse_act_quant | SiLU-and-multiply with quantisation |
fuse_attn_quant | Attention output with quantisation |
fuse_allreduce_rms | The tensor-parallel all-reduce with the next RMSNorm (through FlashInfer) |
enable_qk_norm_rope_fusion | Q/K RMSNorm with rotary embedding |
fuse_rope_kvcache* | Rotary embedding with the KV cache write (MLA and ROCm variants) |
vLLM v0.32.0 removed the torch.compile sequence-parallel and AsyncTP passes that earlier releases offered for tensor parallelism.
CUDA graph modes#
CompilationConfig.cudagraph_mode (-cc.cudagraph_mode=...) has five values:
| Mode | What is recorded | When to use |
|---|---|---|
NONE | Nothing; eager execution | Debugging |
PIECEWISE | Each piece between attention calls; attention runs eagerly | Maximum compatibility with any backend |
FULL | The whole forward pass, attention included, for every batch | Small models or short prompts, when the backend allows it |
FULL_DECODE_ONLY | The whole pass for uniform decode batches only; others run eagerly | Decode instances in prefill/decode disaggregation; saves piecewise graph memory |
FULL_AND_PIECEWISE | Full graphs for uniform decode, piecewise for the rest | The default. “Generally the most performant setting … but also requires the most memory and takes the longest to capture.” Pooling models default to PIECEWISE. |
If the attention backend cannot be recorded for a mode, vLLM downgrades to the closest supported
mode (18.c). A backend that supports full graphs only for uniform batches turns FULL into
FULL_AND_PIECEWISE (or FULL_DECODE_ONLY without piecewise compilation).
Choosing a graph each step#
The older runner uses CudagraphDispatcher (vllm/v1/cudagraph_dispatcher.py) with a key from
vllm/forward_context.py:
class BatchDescriptor:
num_tokens: int
num_reqs: int | None = None
uniform: bool = False
has_lora: bool = False
num_active_loras: int = 0Model Runner V2 (18.a) replaces the dispatcher with an explicit CudaGraphManager
(vllm/v1/worker/gpu/cudagraph_utils.py). Its key, BatchExecutionDescriptor, also holds the
graph mode, the uniform token count, the maximum query length and the number of microbatches.
The design document’s reason: V1’s graph handling “is implicit and hard to reason about”; MRV2
“explicitly captures and launches full CUDA graphs through standard PyTorch APIs”. The LoRA
fields exist because a batch with adapters runs different operations and needs its own
recordings (18.g).
Which sizes are captured#
A graph is valid for one token count, so vLLM records a ladder and pads each batch up to the next
rung. From VllmConfig._set_cudagraph_sizes (v0.32.0):
cudagraph_capture_sizes = [i for i in [1, 2, 4] if i <= max_cudagraph_capture_size]
if max_cudagraph_capture_size >= 8:
# Step size 8 for small batch sizes, up to 256(not included)
cudagraph_capture_sizes += list(range(8, min(max_cudagraph_capture_size + 1, 256), 8))
if max_cudagraph_capture_size >= 256:
# Step size 16 for larger batch sizes
cudagraph_capture_sizes += list(range(256, max_cudagraph_capture_size + 1, 16))The top of the ladder defaults to:
max_cudagraph_capture_size = min(max_num_seqs × decode_query_len × 2, 512)
(1,024 on Blackwell data-centre GPUs)and never more than max_num_batched_tokens. Three additions in v0.32.0:
max_num_batched_tokensitself is added if it fits under the top.max_num_seqsis added if it fits, so a full decode batch never pads.- With speculative decoding (
decode_query_len = 1 + k), exact multiples of the query length are added, because a uniform decode batch must be an exact multiple to replay a full graph. With dynamic speculative decoding each draft-length tier gets its own multiples.
--performance-mode interactivity replaces the bottom of the ladder with every size from 1
to 32. (throughput and the default balanced are the other modes.)
6. Under the hood#
What it costs#
| Cost | Size | Mitigation |
|---|---|---|
| Startup time | Seconds to minutes: compilation on a cold cache, capture on every start | Persist the compile cache; lower -O level; fewer capture sizes |
| GPU memory | Each recorded graph keeps its intermediate buffers: hundreds of megabytes to a few gigabytes | Estimated and subtracted from the KV budget by default since v0.21.0 (17.h); reduce sizes or use FULL_DECODE_ONLY |
| Padding | A batch between two rungs computes a few extra rows | Negligible above a few dozen tokens; interactivity mode for tiny batches |
The startup log reports two of them: Graph capturing finished in 9 secs, took 0.31 GiB.
Optimisation levels#
| Level | Compilation | CUDA graphs | Fusions | Use |
|---|---|---|---|---|
-O0 | None (-cc.mode=NONE) | NONE | None; FlashInfer autotuning off | Fastest startup; development and debugging |
-O1 | VLLM_COMPILE | PIECEWISE | Norm+quant, act+quant (when a custom kernel is used) | Fast startup with the main speedups |
-O2 | As -O1, more compile ranges | FULL_AND_PIECEWISE | Adds all-reduce+RMSNorm | Default. Production. |
-O3 | Currently identical to -O2 | Reserved for slower or experimental optimisations |
Any flag you set explicitly overrides the preset. -O0 is the first thing to try when a model
fails during startup: if it then works, the problem is in compilation or capture, not the model.
Breakable CUDA graphs#
v0.32.0 also has an alternative to splitting the traced graph at attention:
vllm/compilation/breakable_cudagraph.py. It captures the whole forward in one context and,
when an attention or KV-cache operation is reached, ends the capture, runs that operation eagerly
and resumes. The idea is credited in the source to an SGLang change. MRV2 picks between compiled
piecewise graphs and breakable ones when it runs a PIECEWISE step.
The ladder and its padding#
package main
import "fmt"
// captureSizes reproduces the default ladder in VllmConfig._set_cudagraph_sizes.
func captureSizes(maxSize int, interactivity bool) []int {
var sizes []int
if interactivity {
for i := 1; i <= min(maxSize, 32); i++ {
sizes = append(sizes, i)
}
} else {
for _, i := range []int{1, 2, 4} {
if i <= maxSize {
sizes = append(sizes, i)
}
}
}
for i := 8; i < min(maxSize+1, 256); i += 8 {
if !contains(sizes, i) {
sizes = append(sizes, i)
}
}
for i := 256; i <= maxSize; i += 16 {
sizes = append(sizes, i)
}
return sizes
}
func contains(xs []int, x int) bool {
for _, v := range xs {
if v == x {
return true
}
}
return false
}
// padTo returns the smallest captured size >= n, or 0 if none (eager execution).
func padTo(sizes []int, n int) int {
best := 0
for _, s := range sizes {
if s >= n && (best == 0 || s < best) {
best = s
}
}
return best
}
func main() {
const maxNumSeqs = 256
maxSize := min(maxNumSeqs*1*2, 512) // decode_query_len = 1 without speculative decoding
def := captureSizes(maxSize, false)
inter := captureSizes(maxSize, true)
fmt.Printf("max_num_seqs=%d -> max capture size %d\n", maxNumSeqs, maxSize)
fmt.Printf("default ladder: %d sizes: %v ... %v\n", len(def), def[:8], def[len(def)-3:])
fmt.Printf("interactivity ladder: %d sizes\n\n", len(inter))
fmt.Printf("%8s %10s %8s %14s %8s\n", "batch", "default", "waste", "interactivity", "waste")
for _, n := range []int{1, 3, 5, 9, 17, 33, 100, 250, 300, 600} {
d, i := padTo(def, n), padTo(inter, n)
row := func(p int) (string, string) {
if p == 0 {
return "eager", "-"
}
return fmt.Sprint(p), fmt.Sprintf("%.0f%%", 100*float64(p-n)/float64(p))
}
ds, dw := row(d)
is, iw := row(i)
fmt.Printf("%8d %10s %8s %14s %8s\n", n, ds, dw, is, iw)
}
// Average waste if every batch size from 1 to maxSize were equally likely.
total := func(sizes []int) float64 {
w := 0.0
for n := 1; n <= maxSize; n++ {
p := padTo(sizes, n)
w += float64(p-n) / float64(p)
}
return 100 * w / float64(maxSize)
}
fmt.Printf("\naverage padding over all batch sizes: default %.1f%%, interactivity %.1f%%\n",
total(def), total(inter))
}Output:
max_num_seqs=256 -> max capture size 512
default ladder: 51 sizes: [1 2 4 8 16 24 32 40] ... [480 496 512]
interactivity ladder: 76 sizes
batch default waste interactivity waste
1 1 0% 1 0%
3 4 25% 3 0%
5 8 38% 5 0%
9 16 44% 9 0%
17 24 29% 17 0%
33 40 18% 40 18%
100 104 4% 104 4%
250 256 2% 256 2%
300 304 1% 304 1%
600 eager - eager -
average padding over all batch sizes: default 3.3%, interactivity 2.3%The waste is largest for small batches (nine requests padded to sixteen is 44%) and below 5% by a hundred. That is the whole case for the interactivity ladder: it spends capture time and memory on 25 extra sizes to remove padding exactly where it is proportionally worst.
7. Performance implications#
- Small models gain most. Launch overhead is a fixed cost per operation, so the smaller the model and batch, the larger the share CUDA graphs remove.
- Full graphs matter for decode. Piecewise graphs still launch attention eagerly once per layer. On a uniform decode batch, a full graph removes even that, which is why the default mode records both.
- Padding is cheap above small batches. A few percent on average; up to tens of percent for one to sixteen requests.
- Fusions save memory traffic. Norm+quant and act+quant fusions matter most for FP8 and FP4 models (13.j), where the quantise step would otherwise be a separate pass over activations.
- Graph memory comes out of the KV cache. Thousands of megabytes of captured graphs mean fewer KV blocks and so less concurrency.
8. Production implications#
- Persist the compile cache. In a container, mount a volume at
/root/.cache/vllmor bake the cache into the image. The documentation says you can “directly copy the whole~/.cache/vllm/torch_compile_cachedirectory in your deployment scenario to save a great amount of compilation time”. Every pod starting cold pays the full compile. - Capture happens every start. Even with a warm compile cache, graphs are captured on every start. Fewer capture sizes means faster autoscaling (20.g).
- Same configuration, same cache. Changing
max_num_batched_tokens, the model revision or vLLM version produces a new hash and a cold compile.
| Symptom | Likely cause | First step |
|---|---|---|
| Startup takes minutes every time | Compile cache not persisted | Mount the cache directory |
| Out of memory during startup, after the KV cache is created | Graph capture needs more than was estimated | Lower --gpu-memory-utilization or reduce capture sizes |
| Wrong output only with graphs on | A backend or custom op is not capture-safe | Reproduce with -O0, then with -cc.cudagraph_mode=PIECEWISE |
| Fast at high concurrency, slow at 1 to 3 users | Padding and small-batch overhead | --performance-mode interactivity |
| A stale cache after patching model code | The hash did not cover the change | VLLM_DISABLE_COMPILE_CACHE=1 once |
9. Common mistakes#
- Benchmarking a cold start. The first start compiles; later ones load the cache. Measure the steady state.
- Setting
--enforce-eagerin production to “save memory” and losing large decode speedups. Reduce capture sizes instead. - Assuming every batch uses a graph. Steps above the top rung run eagerly; that is fine for large prefills but not if your decode batches exceed it.
- Forgetting that the backend limits the mode. Asking for
FULLdoes not give full graphs for mixed batches on a backend that cannot record them. - Sharing a compile cache across different configs and expecting hits. The hash includes the configuration; a mismatch simply misses.
10. Hands-on exercise#
- In the program, set
maxNumSeqsto 64. What is the top of the ladder, and what happens to a batch of 200 tokens? - Start the same model with
-O0,-O1and-O2. Record startup time and tokens per second at 4 concurrent requests. Which level suits a development loop? - Delete
~/.cache/vllm/torch_compile_cache, start a server, stop it, and start it again. Compare the twoinit engine ... tooklines. - With speculative decoding at
num_speculative_tokens = 3andmax_num_seqs = 64, list the uniform decode sizes vLLM adds to the ladder.
11. Interview questions#
- Why can a CUDA graph be reused for different requests but not for a different batch size?
- What makes a batch “uniform”, and why does that case get a full graph?
- Why does vLLM compile everything at startup instead of when a new shape appears?
- What does
FULL_DECODE_ONLYsave, and for which deployment is it designed? - How does Model Runner V2’s
CudaGraphManagerdiffer from the older dispatcher?
12. Further reading#
Checked on 12 November 2026.
- CUDA Graphs (design, vLLM v0.32.0)
torch.compileintegration (design)- Optimization levels
- Fusions (design)
vllm/config/vllm.py:_set_cudagraph_sizesvllm/config/compilation.py:CUDAGraphMode,PassConfigvllm/v1/worker/gpu/cudagraph_utils.py:CudaGraphManagervllm/compilation/breakable_cudagraph.py- Introduction to
torch.compileand how it works with vLLM (vLLM blog)