Pidoku

CUDA Graphs and Compilation

Module 18 Lesson 18.d 50 min Difficulty 4/5

Prerequisites 5.f, 13.k, 13.m, 18.c


Before you start: words you need#

WordPlain meaning
Launch overheadThe CPU time to start one GPU operation from Python: interpreter, argument checks, dispatch, the launch itself. A few microseconds each.
CUDA graphA recording of a sequence of GPU operations that can be replayed with one call (5.f).
CaptureRecording a CUDA graph by running the code once in a special mode.
torch.compilePyTorch’s compiler. It traces a Python function into a graph of operations and generates faster code for it (13.m).
InductorThe part of torch.compile that generates the kernels.
FusionMerging two or more operations into one kernel so data is not written to memory in between.
PiecewiseRecording the model in pieces, with attention left outside the recordings.
Uniform batchA 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.compile turns 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   dominant

A 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 here

5. 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.compile integration, 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.compile

The 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.*:

PassFuses
fuse_norm_quantRMSNorm with the quantisation that follows it
fuse_act_quantSiLU-and-multiply with quantisation
fuse_attn_quantAttention output with quantisation
fuse_allreduce_rmsThe tensor-parallel all-reduce with the next RMSNorm (through FlashInfer)
enable_qk_norm_rope_fusionQ/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:

ModeWhat is recordedWhen to use
NONENothing; eager executionDebugging
PIECEWISEEach piece between attention calls; attention runs eagerlyMaximum compatibility with any backend
FULLThe whole forward pass, attention included, for every batchSmall models or short prompts, when the backend allows it
FULL_DECODE_ONLYThe whole pass for uniform decode batches only; others run eagerlyDecode instances in prefill/decode disaggregation; saves piecewise graph memory
FULL_AND_PIECEWISEFull graphs for uniform decode, piecewise for the restThe 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:

Python
class BatchDescriptor:
    num_tokens: int
    num_reqs: int | None = None
    uniform: bool = False
    has_lora: bool = False
    num_active_loras: int = 0

Model 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):

Python
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_tokens itself is added if it fits under the top.
  • max_num_seqs is 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#

CostSizeMitigation
Startup timeSeconds to minutes: compilation on a cold cache, capture on every startPersist the compile cache; lower -O level; fewer capture sizes
GPU memoryEach recorded graph keeps its intermediate buffers: hundreds of megabytes to a few gigabytesEstimated and subtracted from the KV budget by default since v0.21.0 (17.h); reduce sizes or use FULL_DECODE_ONLY
PaddingA batch between two rungs computes a few extra rowsNegligible 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#

LevelCompilationCUDA graphsFusionsUse
-O0None (-cc.mode=NONE)NONENone; FlashInfer autotuning offFastest startup; development and debugging
-O1VLLM_COMPILEPIECEWISENorm+quant, act+quant (when a custom kernel is used)Fast startup with the main speedups
-O2As -O1, more compile rangesFULL_AND_PIECEWISEAdds all-reduce+RMSNormDefault. Production.
-O3Currently identical to -O2Reserved 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#

Go
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/vllm or bake the cache into the image. The documentation says you can “directly copy the whole ~/.cache/vllm/torch_compile_cache directory 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.
SymptomLikely causeFirst step
Startup takes minutes every timeCompile cache not persistedMount the cache directory
Out of memory during startup, after the KV cache is createdGraph capture needs more than was estimatedLower --gpu-memory-utilization or reduce capture sizes
Wrong output only with graphs onA backend or custom op is not capture-safeReproduce with -O0, then with -cc.cudagraph_mode=PIECEWISE
Fast at high concurrency, slow at 1 to 3 usersPadding and small-batch overhead--performance-mode interactivity
A stale cache after patching model codeThe hash did not cover the changeVLLM_DISABLE_COMPILE_CACHE=1 once

9. Common mistakes#

  1. Benchmarking a cold start. The first start compiles; later ones load the cache. Measure the steady state.
  2. Setting --enforce-eager in production to “save memory” and losing large decode speedups. Reduce capture sizes instead.
  3. 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.
  4. Forgetting that the backend limits the mode. Asking for FULL does not give full graphs for mixed batches on a backend that cannot record them.
  5. Sharing a compile cache across different configs and expecting hits. The hash includes the configuration; a mismatch simply misses.

10. Hands-on exercise#

  1. In the program, set maxNumSeqs to 64. What is the top of the ladder, and what happens to a batch of 200 tokens?
  2. Start the same model with -O0, -O1 and -O2. Record startup time and tokens per second at 4 concurrent requests. Which level suits a development loop?
  3. Delete ~/.cache/vllm/torch_compile_cache, start a server, stop it, and start it again. Compare the two init engine ... took lines.
  4. With speculative decoding at num_speculative_tokens = 3 and max_num_seqs = 64, list the uniform decode sizes vLLM adds to the ladder.

11. Interview questions#

  1. Why can a CUDA graph be reused for different requests but not for a different batch size?
  2. What makes a batch “uniform”, and why does that case get a full graph?
  3. Why does vLLM compile everything at startup instead of when a new shape appears?
  4. What does FULL_DECODE_ONLY save, and for which deployment is it designed?
  5. How does Model Runner V2’s CudaGraphManager differ from the older dispatcher?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in