Large Language ModelsInference & Performance Optimization
How do CUDA Graphs reduce CPU launch overhead in LLM decode, and how should production serving systems manage graph capture, replay, and dynamic batch shapes?
Question 295 of 309 · Updated
On this page
- The short answer
- 1. Why kernel launch overhead matters in autoregressive decode
- A simple numerical illustration
- 2. What CUDA Graph capture and replay do
- A mental model
- 3. Why decode is a strong candidate—and why it is not universal
- 4. The dynamic-batch problem
- Example: capture buckets
- Do not assume all batches can be padded
- 5. Full graphs versus piecewise graphs
- Full CUDA Graph
- Piecewise CUDA Graph
- Runtime mode selection
- 6. Stable memory addresses are a core requirement
- 7. Capture and warmup safely
- 8. The memory and startup trade-off
- Numerical memory example
- 9. How to choose graph buckets
- Example
- 10. Why CUDA Graphs do not solve CPU starvation
- 11. Correctness hazards and failure modes
- Incorrect buffer lifetime
- Stale input values
- Stream-ordering errors
- Unsupported operator capture
- Excessive padding
- Too many graph variants
- Graph miss storms
- Captured assumptions become invalid
- False performance attribution
- 12. A production dispatch design
- A graph registry should record
- 13. Benchmark the benefit correctly
- Performance metrics
- Example of a misleading result
- 14. Rollout checklist
- 15. Interview-ready answer
The short answer#
CUDA Graphs reduce repeated host-side launch overhead by capturing a sequence of GPU operations and replaying that sequence as a graph. Instead of asking the CPU runtime to dispatch many individual kernels for every decode iteration, the serving engine can submit a graph replay for a compatible batch shape. This is particularly useful when decode consists of many short kernels and the GPU can finish them faster than the host can dispatch them.
The benefit is not “CUDA Graphs make GPU kernels faster.” They primarily reduce launch and orchestration overhead. They do not remove the work performed by the kernels, eliminate all CPU responsibilities, or guarantee lower end-to-end latency for every model and workload.
Production use requires careful handling of stable memory addresses, tensor shapes, batch composition, warmup, graph-pool memory, capture compatibility, and fallback execution. Dynamic batching makes this a dispatch and resource-management problem: choose a compatible captured graph when one exists, otherwise use a safe eager or piecewise path.
1. Why kernel launch overhead matters in autoregressive decode#
An autoregressive model generates one or a small number of tokens per sequence at each decode step. A forward pass may execute many operations:
- normalization and residual operations
- query, key, and value projections
- attention and KV-cache reads/writes
- output projections
- MLP projections and activations
- logits processing and sampling
- communication operations in distributed configurations
A framework such as PyTorch normally orchestrates these operations through host-side dispatch. Each operation can involve Python/framework work, runtime bookkeeping, kernel launch setup, and synchronization or dependency management.
For a large prefill matrix multiplication, the GPU may execute a long kernel. A few microseconds of host dispatch overhead are relatively small compared with milliseconds of useful GPU work.
For a small decode batch, many kernels can be short. If the host takes a meaningful fraction of the time preparing and launching them, the GPU can spend time waiting for the next operation. The problem is especially visible with small models, small batches, and latency-sensitive decode.
A simple numerical illustration#
Assume one decode step launches 120 kernels. Suppose host-side launch and dispatch work costs an average of 5 microseconds per kernel, while the GPU work for each kernel averages 4 microseconds.
Without graph replay, the rough serial launch-plus-execution budget is:
- Host dispatch: 120 × 5 µs = 600 µs
- GPU execution: 120 × 4 µs = 480 µs
- Total illustrative time: 1,080 µs
If a captured graph reduces the repeated host submission cost to an illustrative 30 µs for the whole replay, the rough budget becomes:
- Graph submission: 30 µs
- GPU execution: 480 µs
- Total illustrative time: 510 µs
This is an intentionally simplified example. Real execution is asynchronous; CPU work and GPU work can overlap, launch costs vary, and graph replay itself has overhead. The point is that reducing repeated dispatch can matter when the kernels are short.
2. What CUDA Graph capture and replay do#
A CUDA Graph represents a dependency graph of GPU work. During capture, supported CUDA operations are recorded into a graph. The runtime instantiates an executable graph, which can then be launched repeatedly.
Conceptually:
- Prepare input and output buffers.
- Warm up the execution path.
- Capture the sequence of GPU operations.
- Instantiate the graph executable.
- For each compatible iteration, update the contents of stable input buffers.
- Replay the graph.
- Read or consume outputs through the normal asynchronous execution path.
The graph captures GPU work and dependencies; it does not automatically capture the entire serving system. Request arrival, tokenization, scheduler decisions, request cancellation, dynamic sequence bookkeeping, and many CPU-side operations still need to happen outside the graph unless the engine explicitly moves or represents them in a graph-compatible way.
A mental model#
Without graph replay, the CPU repeatedly says:
- launch normalization
- launch projection
- launch attention
- launch MLP
- launch output operation
With graph replay, the CPU submits a previously captured dependency structure. The GPU executes the recorded sequence.
The graph does not change the mathematical model. It changes how the work is submitted.
3. Why decode is a strong candidate—and why it is not universal#
Decode often repeats a similar operation structure from token to token. The model weights and execution topology remain fixed, while the active batch and token state evolve.
This repeated structure makes graph replay attractive. But the graph must be compatible with the current execution shape and memory addresses. A serving engine therefore commonly captures multiple graphs for different batch sizes or token budgets.
Graph replay can be especially useful when:
- The model is small enough that kernel execution is short.
- The decode batch is stable or belongs to a manageable set of shapes.
- The backend's attention and other operators support graph capture.
- Host dispatch overhead is visible in traces.
- The graph's memory footprint does not materially reduce KV-cache capacity.
It may offer less benefit when:
- Large kernels dominate the step.
- The workload is dominated by long prefill operations.
- Dynamic shapes cause frequent graph misses.
- The attention backend has graph-capture restrictions.
- The graph pool consumes too much memory.
- CPU-side scheduling or tokenization remains the actual bottleneck.
4. The dynamic-batch problem#
Online LLM serving does not have a fixed batch size. Requests arrive, finish, get cancelled, and are admitted continuously. A decode batch may contain 13 active sequences at one step and 17 at another.
A graph captured for one exact shape may not be reusable for a different shape. Capturing every possible shape is expensive and can consume excessive memory.
A practical strategy is to capture a finite set of supported batch sizes or token budgets. At runtime, the engine chooses a compatible graph.
Example: capture buckets#
Suppose a service captures graphs for batch sizes:
If the current decode batch contains 13 sequences, the dispatcher may choose the graph for 16 and pad or mask the unused lanes, if the model runner and attention backend support that behavior.
The trade-off is wasted work and memory bandwidth on padded lanes versus avoiding an eager fallback or a new graph capture.
For this example:
- Active requests: 13
- Captured graph size: 16
- Extra lanes: 3
- Padding fraction relative to captured capacity: 3/16 = 18.75%
This does not mean 18.75% of end-to-end throughput is lost. Some lanes may be masked efficiently, and actual overhead depends on the kernels and data layout. It is a simple measure of shape slack.
A smaller bucket gap reduces padding but requires more graph variants. More variants increase capture time, graph memory, and dispatch complexity.
Do not assume all batches can be padded#
Some attention implementations support only specific graph modes or batch structures. A mixed prefill/decode batch may need a different graph from a uniform decode batch. Variable sequence lengths, speculative decode, multimodal inputs, and custom operators can impose additional constraints.
The dispatcher must use the backend's actual compatibility rules rather than treating graph replay as a generic shape-independent operation.
5. Full graphs versus piecewise graphs#
Two broad patterns are useful.
Full CUDA Graph#
A full graph captures the whole supported model forward path as one graph. It can reduce more host dispatch overhead, but every operation in the captured path must be compatible with the capture assumptions.
This is attractive for stable execution shapes and supported attention backends. It can be difficult when an operation depends on dynamic metadata, uses unsupported capture behavior, or requires changing control flow.
Piecewise CUDA Graph#
Piecewise capture records compatible portions of the model while leaving unsupported or highly dynamic operations outside the captured sections.
This provides flexibility: attention or another dynamic operation can execute eagerly while surrounding operations use graph replay. The trade-off is that the uncaptured boundaries still incur some host-side orchestration.
Runtime mode selection#
A production engine may support several modes:
- no graph, for debugging or compatibility
- piecewise graph
- full graph
- full graph for decode only
- a hybrid mode using full graphs for uniform decode and piecewise graphs for other batch types
The best mode depends on the attention backend, batch composition, model architecture, startup budget, memory budget, and target SLO. It is not safe to copy a graph mode from another model and assume the same result.
6. Stable memory addresses are a core requirement#
CUDA Graph replay relies on the addresses and dependencies established during capture. A common implementation pattern is to allocate long-lived input and output buffers, copy new values into those buffers, and replay the graph using the same addresses.
The graph does not mean that the engine can freely replace tensors, reallocate memory, or change pointer arguments on every replay.
A robust graph runner should:
- Allocate persistent buffers for graph-compatible inputs and outputs.
- Keep their addresses stable for the lifetime of the graph.
- Copy or write new runtime values into those buffers.
- Ensure asynchronous copies and graph replay are ordered on the correct streams.
- Prevent a buffer from being overwritten while a previous replay still consumes it.
- Manage graph lifetime and memory-pool lifetime explicitly.
- Destroy and recapture graphs when their underlying execution assumptions are invalidated.
A subtle bug occurs when a graph references a buffer that the allocator later reuses for an unrelated tensor. The graph may then read stale or unexpected data. Stable ownership and lifetime rules are therefore correctness requirements, not merely performance details.
7. Capture and warmup safely#
Capture is not simply “run once and save.” The path may need warmup to initialize libraries, compile kernels, allocate internal workspaces, and establish stable execution behavior.
A safe capture sequence is:
- Select a representative model, batch shape, attention backend, and execution mode.
- Allocate persistent buffers and workspaces.
- Run warmup iterations outside capture.
- Synchronize only where required to establish a known state.
- Capture the supported operations.
- Instantiate the executable graph.
- Replay it with known inputs.
- Compare outputs against eager execution within appropriate numerical tolerances.
- Verify that the replay path does not allocate unexpectedly or violate stream ordering.
- Record capture duration, memory consumption, and graph compatibility metadata.
Capture should not silently swallow failures and then claim the graph is active. If capture fails, the engine should record the reason and use a compatible fallback.
8. The memory and startup trade-off#
Captured graphs and their associated buffers consume device memory. If an engine captures many batch sizes, token budgets, model variants, or attention modes, the total memory cost can become material.
That memory competes with:
- model weights
- KV cache
- activation and workspace buffers
- communication buffers
- temporary allocations
- memory fragmentation and safety headroom
Numerical memory example#
Suppose a serving worker has 80 GiB of usable device memory after reserving the necessary runtime headroom. Model weights and persistent runtime allocations consume 48 GiB. The KV cache initially receives 28 GiB, leaving 4 GiB of remaining headroom.
If graph capture and its associated buffers consume an additional 3 GiB that was not included in the original estimate, only 1 GiB remains. If the allocator instead sizes the KV cache after graph capture, the graph's memory is accounted for, but the cache becomes smaller.
A smaller KV cache may reduce active concurrency or increase preemption. Thus a graph optimization can improve per-step execution time while reducing overall throughput by reducing cache capacity.
Measure the whole worker memory budget after warmup and capture. Do not optimize decode latency in isolation.
9. How to choose graph buckets#
A useful design objective is not to capture every possible batch size. It is to choose a small set of graph shapes that cover most production decode steps with acceptable padding and memory cost.
Collect a histogram of actual active decode batch sizes and token shapes. Then:
- Identify the high-frequency batch sizes.
- Identify the shapes that contribute most to latency-sensitive traffic.
- Estimate padding waste for candidate capture sets.
- Estimate capture time and graph memory for each additional variant.
- Include graph misses and eager fallback frequency.
- Choose a set that meets the SLO without exhausting memory.
- Re-evaluate when traffic mix or model configuration changes.
Example#
Suppose observed decode batch sizes are concentrated around 1–8 and 24–40. Capturing every size from 1 to 64 may waste memory. A candidate set such as 1, 2, 4, 8, 16, 32, and 48 may cover most traffic, but the correct choice depends on the measured distribution and the engine's padding rules.
Do not optimize the average batch size alone. A graph set that is efficient for high-volume traffic may be poor for the latency-critical low-volume tail.
10. Why CUDA Graphs do not solve CPU starvation#
CUDA Graphs reduce repeated host launch overhead for captured work. They do not eliminate the host responsibilities that happen around each decode step.
The CPU may still need to:
- receive requests and tokenize prompts
- update scheduler state
- decide which requests enter or leave the active batch
- handle cancellation and deadlines
- update input buffers and metadata
- coordinate multiple GPU workers
- launch graph replay
- process outputs and stream tokens
- manage memory and runtime state
In multi-GPU inference, one delayed host process can also delay a rank's launch or synchronization and stall the collective group.
A 2026 study of CPU-induced slowdowns in multi-GPU LLM inference reports that CPU underprovisioning can delay kernel launches, stall communication, and increase tokenization latency. It also notes that CUDA Graphs cannot capture all dynamic scheduling decisions. Therefore, graph replay is not a substitute for adequate CPU capacity and efficient scheduler design.
If GPU utilization is low, inspect CPU run queues, engine-core scheduling latency, tokenization time, per-rank launch delay, and collective stalls before concluding that graph capture is missing.
11. Correctness hazards and failure modes#
Incorrect buffer lifetime#
A graph replays against a pointer whose storage has been freed or reused. Keep graph-owned buffers alive and prevent unsafe allocator reuse.
Stale input values#
A buffer is not fully overwritten before replay, so the graph consumes data from a previous request. Define exact buffer update rules and test partial batches.
Stream-ordering errors#
A copy or metadata update is not complete before graph replay begins. Use correct stream dependencies and avoid unnecessary global synchronization.
Unsupported operator capture#
A custom operation allocates memory, performs unsupported host interaction, or uses an incompatible runtime path during capture. Isolate it outside the graph or use a supported implementation.
Excessive padding#
A batch is repeatedly rounded up to a much larger graph shape. This wastes compute or memory bandwidth and can reduce throughput.
Too many graph variants#
Capture time, memory use, and dispatch complexity grow until graph optimization harms startup or cache capacity.
Graph miss storms#
The live workload frequently produces shapes that have no compatible graph. The engine falls back to eager execution or triggers costly capture behavior. Monitor graph-hit and fallback rates.
Captured assumptions become invalid#
Changing model weights, kernel configuration, attention backend, parallelism topology, or buffer layout may invalidate a graph. Associate graph artifacts with the exact configuration that produced them.
False performance attribution#
A benchmark compares a warmed graph path with an eager path that includes compilation or initialization. Separate cold-start and steady-state measurements.
12. A production dispatch design#
A simplified dispatcher can be described as follows:
PYTHONdef run_decode(batch, graph_registry, eager_runner): descriptor = describe_batch(batch) graph = graph_registry.find_compatible( batch_kind=descriptor.kind, token_count=descriptor.token_count, request_count=descriptor.request_count, attention_backend=descriptor.attention_backend, model_revision=descriptor.model_revision, ) if graph is None: return eager_runner.run(batch) update_persistent_graph_inputs(graph, batch) if not graph.inputs_are_ready(): raise RuntimeError("Graph input buffers are not ready") return graph.replay()
This is conceptual pseudocode, not a drop-in vLLM API. A real implementation must coordinate streams, buffer ownership, graph concurrency, output lifetime, and backend-specific compatibility.
A graph registry should record#
- model and weight revision
- runtime and kernel build
- GPU architecture and device identity
- attention backend and supported graph mode
- parallelism topology
- input/output buffer layout
- batch descriptor and token budget
- graph memory footprint
- capture timestamp and warmup status
- correctness-validation result
This prevents a graph captured for one execution environment from being reused under incompatible assumptions.
13. Benchmark the benefit correctly#
Run paired experiments under the same model, hardware, traffic trace, and concurrency conditions.
Compare at least:
- eager execution
- piecewise graph execution
- full graph execution where supported
- hybrid or decode-only graph execution where available
Measure both cold-start and steady-state behavior.
Performance metrics#
- graph capture time
- graph memory consumption
- graph hit and fallback rate
- host dispatch time per decode step
- GPU idle gaps between kernels
- kernel execution time
- decode time per output token
- TBT/ITL p50, p95, and p99
- TTFT and end-to-end latency
- output tokens per second and SLO-compliant goodput
- KV-cache capacity and preemption rate
- CPU utilization and scheduler delay
Use traces to confirm that host launch gaps actually shrink. A higher aggregate GPU utilization percentage alone does not prove that graph replay improved user-visible latency.
Example of a misleading result#
A benchmark reports 25% lower decode-step time after enabling graphs. But graph capture consumes enough memory to reduce KV-cache capacity, causing more preemptions under realistic concurrency. End-to-end p99 latency gets worse.
The correct conclusion is not “graphs do not work.” It is that the graph configuration must be evaluated jointly with cache capacity, active batch size, and request-level SLOs.
14. Rollout checklist#
- [ ] Confirm profiling shows meaningful host launch overhead.
- [ ] Verify that the target model and attention backend support the selected graph mode.
- [ ] Warm up before capture and test capture failures.
- [ ] Keep graph input/output addresses stable.
- [ ] Validate stream ordering and asynchronous buffer updates.
- [ ] Capture a bounded set of common batch shapes.
- [ ] Measure padding and graph miss rates.
- [ ] Include graph pools in the device memory budget.
- [ ] Validate eager-versus-graph numerical parity.
- [ ] Test cancellations, partial batches, and changing request counts.
- [ ] Benchmark cold-start and steady-state separately.
- [ ] Compare TTFT, TBT, goodput, preemption, and cost.
- [ ] Preserve a safe eager or piecewise fallback.
- [ ] Re-capture when model, runtime, backend, or topology assumptions change.
15. Interview-ready answer#
“CUDA Graphs reduce repeated CPU launch overhead by capturing a supported sequence of GPU operations and replaying it with a single graph launch. They are useful for autoregressive decode because many short kernels repeat every token step, so host dispatch can become a significant fraction of latency. In a dynamic serving system, I would capture a bounded set of compatible batch shapes, select a graph at runtime, and fall back to eager or piecewise execution when no graph matches. I would preserve stable input and output buffers, warm up before capture, validate stream ordering and numerical parity, and include graph memory in the KV-cache budget. Finally, I would measure host launch gaps, graph hit rate, TBT, TTFT, goodput, and preemption under realistic traffic. Graphs reduce launch overhead, but they do not eliminate scheduler work or fix CPU starvation.”
References
- 1.vLLM — CUDA Graphs: Design and Runtime Modesdocs.vllm.ai
- 2.NVIDIA — Getting Started with CUDA Graphsdeveloper.nvidia.com
- 3.
- 4.vLLM — Optimization and Tuningdocs.vllm.ai
Related questions
Explore other topics:Deep LearningRetrieval-Augmented GenerationAI Agents