This post introduces CUDA Graphs, and how they are being used by LLM inference engines or frameworks to cut CPU kernel-launch overhead and speed up inference. Motivation An LLM, or more generally a deep learning model, consists of a cascade of layers implemented behind the scenes using CUDA or
This post introduces CUDA Graphs, and how they are being used by LLM inference engines or frameworks to cut CPU kernel-launch overhead and speed up inference.
An LLM, or more generally a deep learning model, consists of a cascade of layers implemented behind the scenes using CUDA or GPU kernels, including general matrix multiplications or GEMMs. During a forward pass, for example, during inference, if one naively launches these short-running kernels individually, the GPU may finish executing the previously launched kernel before the next one is dispatched. Because the CPU cannot keep up with feeding it work, the GPU sits idle and cannot remain saturated, thereby reducing GPU utilization. This issue is further exacerbated because, during autoregressive inference and continuous batching, the same model is executed repeatedly across prefill and decode steps. This bottleneck is known as kernel launch overhead (source of overhead [6] includes jumping from Python to C++, GIL acquire/release, scavenging/reference counting, torch dispatching, hardware submission… ) and is particularly pronounced when kernel execution times are short relative to CPU-side launch latency; in this case, significant fraction of the total time can be attributed to CPU launch overhead. To address the CPU-side kernel launch latency bottleneck, which becomes increasingly apparent as GPUs become faster, CUDA Graphs [4] were introduced.

If we look at a deep learning model, its computation can be represented as an execution graph (forward computational graph), where kernels are interconnected through their dependencies.

The CUDA Graph API provides a way to construct or capture such execution graph. Instead of interacting with the CUDA driver (via CUDA Runtime API) for each individual kernel launch, one can define the graph once and subsequently execute or replay it with different input data (by modifying the memory the data points to), thereby reducing the overall launch overhead, increasing GPU utilization, and enhancing performance. In other words, multiple kernel launches are consolidated into a single graph launch.
CUDA Graphs are different from kernel fusion. The idea behind kernel fusion is to exploit function composition at the kernel level. In its simplest form, given two functions \(f\) and \(g\), instead of computing \(y = g(x), z = f(y)\) where the intermediate result \(y\) is written to memory and subsequently loaded by the second kernel, one directly computes \( z = (f \circ g)(x) = f(g(x))\) and avoids materializing intermediate results in global memory (eliminating the need for separate kernel launches) thereby reducing memory traffic (and thus increasing arithmetic intensity). A naive example is the sigmoid activation function, defined as
\(\sigma(x) = \frac{1}{1 + e^{-x}}\)
The sigmoid function can be expressed as a composition of elementary
functions: \(\sigma = f_4 \circ f_3 \circ f_2 \circ f_1\)
where
\( f_1(x) = -x, \qquad f_2(x) = e^x, \qquad f_3(x) = 1 + x, \qquad f_4(x) = \frac{1}{x}\)
Without kernel fusion, a naive implementation in PyTorch would be:
a = -x
b = torch.exp(a)
c = 1 + b
y = torch.reciprocal(c)This would require four separate kernel launches and global memory round-trips.
With kernel fusion, one can instead implement the entire computation within a single kernel e.g when using torch.sigmoid(x) (again very simple form of operation fusion):
void sigmoid_kernel_cuda(TensorIteratorBase& iter) {
...
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, common_dtype, "sigmoid_cuda", & {
gpu_kernel(iter, []GPU_LAMBDA(scalar_t a) -> scalar_t {
using opmath_t = at::opmath_type<scalar_t>;
const auto one = opmath_t{1};
return static_cast<scalar_t>(one/(one + std::exp(-opmath_t{a})));
});
});
}
}
If we look at the gated activation used in the MLP of Qwen3, given by
\(Y = \operatorname{SiLU}(G) \odot U\)
where \(\odot\) denotes element-wise multiplication, and \(G\) and \(U\) denote the outputs of the gate and up projections, respectively, instead of launching one kernel for the SiLU activation and another for the element-wise multiplication, a fused kernel computes the SiLU activation and performs the multiplication directly. This increases arithmetic intensity by loading the elements of \(G\), applying SiLU, and multiplying the results directly by the corresponding elements of \(U\), without writing the intermediate SiLU outputs to global memory and reading them back i.e less traffic generated.
@CustomOp.register("silu_and_mul")
class SiluAndMul(CustomOp):
"""An activation function for SwiGLU.
The function computes x -> silu(x[:d]) * x[d:] where d = x.shape[-1] // 2.
Shapes:
x: (num_tokens, 2 * d) or (batch_size, seq_len, 2 * d)
return: (num_tokens, d) or (batch_size, seq_len, d)
"""
def init(self, *, compile_native: bool = True):
...
self.op = torch.ops._C.silu_and_mul
....
@staticmethod
def forward_native(x: torch.Tensor) -> torch.Tensor:
"""PyTorch-native implementation equivalent to forward()."""
d = x.shape[-1] // 2
return F.silu(x[..., :d]) * x[..., d:]
def forward_cuda(self, x: torch.Tensor) -> torch.Tensor:
d = x.shape[-1] // 2
output_shape = x.shape[:-1] + (d,)
out = torch.empty(output_shape, dtype=x.dtype, device=x.device)
self.op(out, x)
return outKernel fusion reduces memory traffic while maintaining the same number of floating-point operations, thereby increasing arithmetic intensity. Now if we look at CUDA Graphs, they optimize how the workload is submitted to the GPU. In CUDA Graphs, operations (e.g. kernel launches, memory transfers...) are represented as nodes, while edges represent dependencies between these operations. Formally, a CUDA Graph can be represented as \( \mathbb{G} = (\mathbb{V}, \mathbb{E})\) where \(\mathbb{V}\) denotes the set of operations and \(\mathbb{E}\) denotes the set of dependencies between them.
There are two ways to constructing a CUDA Graph; explicit API calls and stream capture. The first consists of manually constructing the graph by explicitly adding nodes and specifying their dependencies using the CUDA Graph API.

The second consists of letting the CUDA runtime dynamically capture the execution graph through CUDA stream capture (cudaStreamBeginCapture and cudaStreamEndCapture are positioned before and after a code block). In the latter case, operations submitted can be captured into a unified execution graph. We will look at both approaches and how PyTorch facilitates the capture and replay of CUDA Graphs.

There is no free lunch, CUDA Graphs come with several constraints. For example, CUDA Graphs have a static graph topology, and kernel parameters (e.g., virtual addresses of all tensors, KV cache) are captured by value at definition time [2] and reused during replay; this means persistent input buffers must be used.
Data shapes must stay constant across all graph launches. However, during LLM inference, the batch size changes as completed requests leave the continuous scheduling pipeline while new requests get scheduled, which breaks CUDA graph capture (e.g \( \texttt{input_ids = self.input_ids.gpu[:num_tokens_padded]}\). During graph replay, the captured kernel configurations and memory addresses are reused regardless of actual input shapes, which would lead to leading to crashes, data corruption or incorrect results. There are ways to cope with this. For example, vLLM uses padding to a fixed size and binning; capturing multiple graphs for common shape configurations and selecting the appropriate graph at runtime. Another approach is to use Graph Update APIs (graph updates can be performed with cudaGraphExecUpdate, which e.g., llama.cpp uses [3]), which can modify kernel arguments and launch configurations without necessitating full recapture. Note, though, that the complexity of cudaGraphExecUpdate is roughly proportional to the number of changes made to CUDA graph nodes, so it becomes less efficient if the bulk of the nodes change [1] (making the graph update expensive).
Additionally, it is sometimes not possible to associate each set of parameters with a CUDA graph (so first approach is not always possible) and CUDA Graphs can sometimes hurt performance[5]. Finally not all ML workloads are compatible with CUDA Graphs (e.g attention).
Now consider the following computation graph:

We can use the CUDA Graph API to construct the execution graph manually by adding nodes along with their dependencies. First, we use cudaGraphCreate(&graph,...) to create a graph. We then create kernel execution nodes and add them to the graph using cudaGraphAddKernelNode, explicitly specifying their dependencies. Next, we instantiate the graph using cudaGraphInstantiate and launch it using cudaGraphLaunch. The function cudaStreamSynchronize then serves as a synchronization barrier, blocking the calling CPU thread until all previously submitted operations in the specified stream, including the graph execution, have completed. Finally, we copy the resulting data from device memory to host memory using cudaMemcpy. This is what the resulting code looks like.
cudaKernelNodeParams p1 = {};
p1.func = (void*)matmul;
p1.gridDim = grid2d;
p1.blockDim = block2d;
p1.kernelParams = args1;
cudaGraphNode_t node1;
CUDA_CHECK(cudaGraphAddKernelNode(&node1, graph, nullptr, 0, &p1));
// Node 2: H = sigmoid(Y)
void* args2[] = {&dY, &dH, &count};
cudaKernelNodeParams p2 = {};
p2.func = (void*)sigmoid;
p2.gridDim = grid1d;
p2.blockDim = block1d;
p2.kernelParams = args2;
cudaGraphNode_t node2;
CUDA_CHECK(cudaGraphAddKernelNode(&node2, graph, &node1, 1, &p2));
// Node 3: Z = W2 * X
void* args3[] = {&dW2, &dX, &dZ, &n};
cudaKernelNodeParams p3 = {};
p3.func = (void*)matmul;
p3.gridDim = grid2d;
p3.blockDim = block2d;
p3.kernelParams = args3;
cudaGraphNode_t node3;
CUDA_CHECK(cudaGraphAddKernelNode(&node3, graph, nullptr, 0, &p3));
// Node 4: L = H + Z
void* args4[] = {&dH, &dZ, &dL, &count};
cudaKernelNodeParams p4 = {};
p4.func = (void*)add;
p4.gridDim = grid1d;
p4.blockDim = block1d;
p4.kernelParams = args4;
cudaGraphNode_t deps[] = {node2, node3};
cudaGraphNode_t node4;
CUDA_CHECK(cudaGraphAddKernelNode(&node4, graph, deps, 2, &p4));
CUDA_CHECK(cudaGraphDebugDotPrint(graph,"cuda_graph.dot",cudaGraphDebugDotFlagsKernelNodeParams));
CUDA_CHECK(cudaGraphInstantiate(&graphExec, graph, 0));
CUDA_CHECK(cudaGraphLaunch(graphExec, stream));
We can also print the resulting graph using the API:

Now, let us consider the second approach; stream capture. We essentially wrap our kernel launches or code block between cudaStreamBeginCapture and cudaStreamEndCapture. The former initiates stream capture, while the latter ends the capture and produces a CUDA Graph representing the captured operations and their dependencies. We can then instantiate and launch the resulting graph just as we would with a manually constructed graph, using cudaGraphInstantiate and cudaGraphLaunch.
CUDA_CHECK(cudaStreamBeginCapture(stream, .));
// you can imagine having a library call here and the stream is surfaced
matmul<<<blocks, threads, 0, stream>>>(dW1, dX, dY, N);
sigmoid<<<blocks, threads, 0, stream>>>(dY, dH, SIZE);
matmul<<<blocks, threads, 0, stream>>>(dW2, dX, dZ, N);
add<<<blocks, threads, 0, stream>>>(dH, dZ, dL, SIZE);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaStreamEndCapture(stream, &graph));
CUDA_CHECK(cudaGraphDebugDotPrint(graph,"captured_graph.dot",cudaGraphDebugDotFlagsKernelNodeParams));
CUDA_CHECK(cudaGraphInstantiate(&graphExec, graph, 0));
Here is what the resulting graph looks like. Since all kernels are launched on the same CUDA stream during capture, the resulting graph is linear, introducing an execution dependency between nodes 1 and 2, even though there is no actual dependency between them.

As you can see, there is no magic involved, the API is relatively straightforward to use. However, manually constructing and maintaining dependencies can become considerably more complex as the graph grows. Stream capture simplifies this process, although little care is needed when multiple streams are involved.
Now consider the same computation graph. We can similarly capture the CUDA Graph using PyTorch's CUDA Graph API. First, we create an empty graph using graph = torch.cuda.CUDAGraph() . We then wrap the model's forward pass in a with torch.cuda.graph(graph) context manager to capture the CUDA operations executed during the first invocation. Once the graph has been captured, we can replay it using graph.replay(), without launching each kernel individually from Python. Here is what the resulting code looks like:
class LModel(nn.Module):
def init(self, n):
super().init()
self.register_buffer("W1", torch.randn(n, n))
self.register_buffer("W2", torch.randn(n, n))
def forward(self, x):
y = self.W1 @ x
h = torch.sigmoid(y)
z = self.W2 @ x
return h + z
model = LModel(N).to(device)
model.eval()
static_input = torch.randn(N, N, device=device)
# warm up on a side stream similar to https://pytorch.org/blog/accelerating-pytorch-with-cuda-graphs/
s = torch.cuda.Stream()
s.wait_stream(torch.cuda.current_stream())
with torch.cuda.stream(s):
with torch.no_grad():
for _ in range(3):
warmup_output = model(static_input)
torch.cuda.current_stream().wait_stream(s)
# capture
g = torch.cuda.CUDAGraph(keep_graph=True)
g.enable_debug_mode()
with torch.no_grad():
with torch.cuda.graph(g):
static_output = model(static_input)
...
static_input.copy_(data)
g.replay()
Here is what produced graph looks like (using g.debug_dump()):

If we look at vLLM, given an LLM implemented using PyTorch, a CUDAGraphWrapper is used to wrap the model invocation and manage CUDA Graph capture and replay. Specifically, a cache key, represented by a BatchDescriptor, is used to identify the CUDA Graph entry corresponding to a particular batch configuration; the descriptor captures relevant features of the batch, like the number of tokens and the number of requests.
@dataclass(frozen=True)
class BatchDescriptor:
"""Batch descriptor for cudagraph dispatching.
We should keep the number of items as minimal as possible
to properly and uniquely describe the padded batch.
"""
num_tokens: int
num_reqs: int | None = None
uniform: bool = False
has_lora: bool = False
num_active_loras: int = 0
If a CUDA Graph has not yet been captured for the corresponding descriptor, vLLM captures the execution of the wrapped model using PyTorch's CUDA Graph API (it uses a dedicated stream per process). The CUDA Graph entry is retrieved using the batch descriptor. If the graph has not yet been captured, the wrapped model is executed inside a CUDA Graph capture context:
def __call__(self, *args: Any, **kwargs: Any) -> Any | None:
forward_context = get_forward_context()
batch_descriptor = forward_context.batch_descriptor
cudagraph_runtime_mode = forward_context.cudagraph_runtime_mode
if (
cudagraph_runtime_mode == CUDAGraphMode.NONE
or cudagraph_runtime_mode != self.runtime_mode
):
# CUDAGraphMode.NONE could mean the profile run, a warmup run, or
# running without cudagraphs.
# We do not trigger capture/replay if the runtime mode is not
# matches. This enables properly dispatching to the correct
# CUDAGraphWrapper when nesting multiple instances with different
# runtime modes.
return self.runnable(*args, **kwargs)
entry = self.concrete_cudagraph_entries[batch_descriptor]
if entry.cudagraph is None:
...
with torch.cuda.graph(
cudagraph,
pool=graph_pool,
stream=current_stream(),
):
# `output` is managed by pytorch's cudagraph pool
output = self.runnable(*args, **kwargs)
...
return output
...
entry.cudagraph.replay()
return entry.output
Once the graph has been captured, it is stored in the corresponding cache entry and can be reused for subsequent invocations matching the same batch descriptor. Instead of executing the wrapped model again through the regular PyTorch dispatch path, vLLM replays the previously captured CUDA Graph.
So we avoid repeatedly dispatching the individual CUDA kernels from the CPU, reducing launch overhead during inference. The captured graph reuses its recorded kernel parameters and device memory addresses, so the input data must be updated in the appropriate buffers before replay.
vLLM additionally supports Piecewise CUDA Graphs, where only the linear operators or projections and MLP networks are captured into CUDA Graphs, while attention uses eager execution; that is, a CUDA Graph performs all the operations before attention, control returns to PyTorch and then a second CUDA Graph handles the post-attention MLP and the pre-attention projections in the subsequent layer. This is achieved using a nested wrapper design.

As listed below, if runtime_mode does not match the mode of the outer wrapper, the runnable is called directly, which in turn invokes the nested wrappers ( wrapping a PiecewiseBackend ):
class CUDAGraphWrapper:
def __call__(self, *args: Any, **kwargs: Any) -> Any | None:
if not is_forward_context_available():
# No forward context means we are outside the normal
# inference path (e.g. a vision encoder forward pass).
# Just run the underlying function without cudagraphs.
return self.runnable(*args, **kwargs)
forward_context = get_forward_context()
batch_descriptor = forward_context.batch_descriptor
cudagraph_runtime_mode = forward_context.cudagraph_runtime_mode
if (
cudagraph_runtime_mode == CUDAGraphMode.NONE
or cudagraph_runtime_mode != self.runtime_mode
):
# CUDAGraphMode.NONE could mean the profile run, a warmup run, or
# running without cudagraphs.
# We do not trigger capture/replay if the runtime mode is not
# matches. This enables properly dispatching to the correct
# CUDAGraphWrapper when nesting multiple instances with different
# runtime modes.
return self.runnable(*args, **kwargs)
def wrap_with_cudagraph_if_needed(
piecewise_backend: Any,
vllm_config: VllmConfig,
compilation_config: CompilationConfig,
is_first_graph: bool,
is_last_graph: bool,
) -> Any:
"""Wrap a piecewise backend with CUDA graph wrapper if needed.
This function is shared between VllmBackend and
construct_serializable_fn_from_inductor_cache.
Args:
piecewise_backend: The backend to wrap
vllm_config: The vLLM configuration
compilation_config: The compilation configuration
is_first_graph: Whether this is the first graph in the sequence
is_last_graph: Whether this is the last graph in the sequence
Returns:
The wrapped backend if CUDA graphs are enabled, otherwise the original backend
"""
if (
not compilation_config.cudagraph_mode.has_piecewise_cudagraphs()
or compilation_config.use_inductor_graph_partition
):
return piecewise_backend
# We're using Dynamo-based piecewise splitting, so we wrap
# the whole subgraph with a static graph wrapper.
from .cuda_graph import CUDAGraphOptions
# resolve the static graph wrapper class (e.g. CUDAGraphWrapper
# class) as platform dependent.
static_graph_wrapper_class = resolve_obj_by_qualname(
current_platform.get_static_graph_wrapper_cls()
)
# Always assign PIECEWISE runtime mode to the
# CUDAGraphWrapper for piecewise_backend, to distinguish
# it from the FULL cudagraph runtime mode, no matter it
# is wrapped on a full or piecewise fx graph.
return static_graph_wrapper_class(
runnable=piecewise_backend,
vllm_config=vllm_config,
runtime_mode=CUDAGraphMode.PIECEWISE,
cudagraph_options=CUDAGraphOptions(
debug_log_enable=is_first_graph,
gc_disable=not is_first_graph,
weak_ref_output=is_last_graph,
),
)As listed below the modules that are subject to graph capture are replaced or wrapped (using FX graph transformation) as illustrated in the figure shown earlier.
class PiecewiseCompileInterpreter(torch.fx.Interpreter):
...
@instrument(span_name="Inductor compilation")
def run(self, *args: Any) -> Any:
return super().run(*args)
def call_module(
self,
target: torch.fx.node.Target,
args: tuple[torch.fx.node.Argument, ...],
kwargs: dict[str, Any],
) -> Any:
assert isinstance(target, str)
gm = getattr(self.module, target)
outputs = gm.graph.output_node().args[0]
output = fx.map_arg(outputs, lambda node: node.meta["example_value"])
if target in self.compile_submod_names:
index = self.compile_submod_names.index(target)
submod = self.fetch_attr(target)
sym_shape_indices = [
i for i, x in enumerate(args) if isinstance(x, torch.SymInt)
]
# Lazy import here to avoid circular import
from torch._inductor.compile_fx import graph_returns_tuple
from .piecewise_backend import PiecewiseBackend
piecewise_backend = PiecewiseBackend(
submod,
self.vllm_config,
index,
len(self.compile_submod_names),
sym_shape_indices,
self.vllm_backend,
graph_returns_tuple(submod),
submod_name=target,
)
self.module.__dict__[target] = wrap_with_cudagraph_if_needed(
piecewise_backend,
self.vllm_config,
self.compilation_config,
piecewise_backend.is_first_graph,
piecewise_backend.is_last_graph,
)
compilation_counter.num_piecewise_capturable_graphs_seen += 1
return output
What happens, basically, is that during worker initialization, CUDA Graph capture is initiated using dummy inputs (model_runner._dummy_run())
with (
self.maybe_randomize_inputs(
input_ids, inputs_embeds, randomize_inputs=randomize_inputs
),
set_forward_context(
attn_metadata,
self.vllm_config,
num_tokens=num_tokens_padded,
num_tokens_across_dp=num_tokens_across_dp,
cudagraph_runtime_mode=cudagraph_runtime_mode,
batch_descriptor=batch_desc,
ubatch_slices=ubatch_slices_padded,
slot_mapping=slot_mappings,
is_padding=is_padding,
),
):
outputs = self.model(
input_ids=input_ids,
positions=positions,
intermediate_tensors=intermediate_tensors,
inputs_embeds=inputs_embeds,
**model_kwargs,
)The model is then called, and the optimized forward function invokes each partition (or region) of the model. For example, partitions 0, 2, 4, 6, etc., are captured as CUDA Graphs. Once capture is complete, replay quicks in. Meanwhile, partitions 1, 3, 5, etc., correspond to attention operations and use eager execution, i.e., no CUDA Graph is involved.
Finally, once the warmup and capture phases are complete, token generation can start. In this case, entry.cudagraph.replay() is invoked instead of performing capture for each submodule represented by a CUDA Graph.
For example, for Qwen3-0.6B, there are 57 submodules (indexed from 0 to 56), with every second submodule using CUDA Graphs, resulting in 29 capturable partitions and 28 attention partitions. One can think of this as the operations of the decoder layers being flattened into a computation graph and subsequently split into partitions.
For example, submod_41 only invokes attention and KV cache update operations:
class submod_41(torch.nn.Module):
def forward(self, key_62: "bf16[s72, 8, 128]", s72: "Sym(s72)", value_20: "bf16[s72, 8, 128]", synthetic_local_tmp_40_ : vllm_utils_torch_utils_LayerName, query_62: "bf16[s72, 16, 128]", output_83: "bf16[s72, 16, 128]"):
# File: /usr/local/lib/python3.12/dist-packages/vllm/model_executor/layers/attention/attention.py:599 in forward, code: kv_cache_dummy_dep = torch.ops.vllm.unified_kv_cache_update(
unified_kv_cache_update: "bf16[0]" = torch.ops.vllm.unified_kv_cache_update(key_62, value_20, synthetic_local_tmp_40_)
# File: /usr/local/lib/python3.12/dist-packages/vllm/model_executor/layers/attention/attention.py:602 in forward, code: torch.ops.vllm.unified_attention_with_output(
unified_attention_with_output = torch.ops.vllm.unified_attention_with_output(query_62, key_62, value_20, output_83, synthetic_local_tmp_40_, kv_cache_dummy_dep = unified_kv_cache_update); query_62 = key_62 = value_20 = output_83 = synthetic_local_tmp_40_ = unified_kv_cache_update = unified_attention_with_output = None
return ()Meanwhile, submod_42 performs operations such as linear projections, RMS normalization, and SwiGLU activation (i.e., \(\texttt{F.silu(x[..., :d]) * x[..., d:]})\), all captured within a single CUDA Graph for a given batch descriptor.
That is all. In the next post, we will cover NCCL, GPU-to-GPU communication, hardware topology, and security vulnerabilities at the inference engine level.