CUDA Graphs: When to Capture and Replay Repeated GPU Work
A CUDA Graph represents GPU work, such as kernel launches and memory copies, together with the dependencies between those operations. You define and prepare the workflow once, then submit an executable graph for repeated runs. This can help when a stable workflow contains short operations and the host spends noticeable time submitting each one; it does not make the GPU computation itself automatically faster.
CUDA Graphs: When to Capture and Replay Repeated GPU Work
A CUDA Graph represents GPU work, such as kernel launches and memory copies, together with the dependencies between those operations. You define and prepare the workflow once, then submit an executable graph for repeated runs. This can help when a stable workflow contains short operations and the host spends noticeable time submitting each one; it does not make the GPU computation itself automatically faster.
This article explains how CUDA C++ developers can decide whether to capture a workflow, replay it safely, and measure whether it helps. It is based on NVIDIA’s CUDA Programming Guide and Runtime API documentation reviewed on 2026-11-22.
What does a CUDA Graph represent, and how does it run?
A graph node is an operation such as a kernel or memory copy. A directed edge states that one operation must finish before another can proceed. The graph is therefore not simply a list: independent nodes may be eligible to overlap, while CUDA and the GPU scheduler decide actual execution and resource use. A missing dependency can expose an unfinished result; an unnecessary one can block useful overlap.
With ordinary stream code, the host submits each kernel or copy call in turn. A graph separates workflow definition and validation from execution. After creating an executable instance, the application can replay the same workflow with one graph-launch call instead of submitting every operation separately on every iteration.
The diagram shows one definition reused for several batches. “Preprocess → infer → postprocess” is an illustrative workflow, not a claim about a particular library.
Host: [define workflow] → [validate and instantiate] → [launch graph] ─┬→ batch 1
├→ batch 2
└→ batch 3
Graph: [preprocess] → [inference] → [postprocess]When is a benefit plausible?
The trade-off depends on how much repeated host submission work the graph removes and how many replays amortize the workflow-definition and instantiation costs. These expressions are a conceptual comparison, not a performance model that predicts a particular machine. Operation count, synchronization, data movement, and runtime behavior affect actual time.
Repeated stream cost ≈ repetitions × (sum of per-operation host submission costs + GPU work)
Graph cost ≈ definition and instantiation cost + repetitions × (graph submission cost + the same GPU work)
For example, assume an application runs several small preprocessing kernels on the same buffers in the same order for each frame. If GPU computation is brief but the host submits many calls per frame, graph capture is worth measuring. If one long matrix operation dominates total time, grouping submissions leaves that computation intact, so the possible gain is limited.
| Workflow characteristic | Decision | Why |
|---|---|---|
| Short kernels or copies repeat in a stable order | Consider capture and compare measurements | A graph launch may replace many host submissions |
| GPU computation dominates and there are few calls | Optimize the stream workflow first | Lower submission cost leaves the main device bottleneck |
| Operation count, dependencies, or addresses vary substantially | Check graph suitability and update rules first | Captured structure and executable parameters have constraints |
| The workflow runs once or too few times to recover setup cost | Defer adoption or measure the trade-off | Definition and instantiation can exceed any savings |
How do you capture and replay existing stream code?
A practical starting point is to bracket existing stream work with capture calls. While capture is active, operations submitted to the stream are recorded as graph nodes instead of being executed immediately by the GPU. Ending capture returns a graph object; instantiation validates it and creates an executable object that can be launched repeatedly.
Definition Preparation Repeated execution
stream calls → graph nodes → validate and instantiate → launch graph → GPU work
once reuse executableThe C++ below is an illustrative outline with a fixed stream, buffers, and kernel parameters. The application must define stageA, stageB, and the launch configuration; error handling and application-specific setup are omitted. In production, check every CUDA return value, make inputs ready before launch, and wait for completion before the CPU reads output.
// Illustrative skeleton: stream, buffers, launch dimensions, and kernels are application-defined.
cudaGraph_t graph;
cudaGraphExec_t graphExec;
cudaStreamBeginCapture(stream, cudaStreamCaptureModeThreadLocal);
stageA<<<grid, block, 0, stream>>>(input, scratch);
stageB<<<grid, block, 0, stream>>>(scratch, output);
cudaStreamEndCapture(stream, &graph);
cudaGraphInstantiate(&graphExec, graph, 0);
for (int i = 0; i < iterations; ++i) {
cudaGraphLaunch(graphExec, stream);
}
cudaStreamSynchronize(stream); // Wait before the CPU consumes output.
cudaGraphExecDestroy(graphExec);
cudaGraphDestroy(graph);Capture records work; it does not wait for that work to finish. The stream synchronization in the example lets the CPU consume output after earlier graph work in that stream completes. Synchronization is a correctness boundary, not a step that must be inserted after every iteration for speed. In a real pipeline, use the narrowest event or stream dependency that protects buffer reuse.
What should you watch during capture, updates, and concurrent execution?
Capture is not a general-purpose recorder for every CUDA call. The legacy default stream (cudaStreamLegacy) cannot be captured. Host synchronization and some synchronous APIs during capture violate capture rules. An unsupported operation may invalidate capture, so cudaStreamEndCapture can return an error and no usable graph. Check CUDA errors, capture only supported work, or leave the unsupported portion on the ordinary stream path.
For multiple streams, event records and waits must express dependencies within the same capture graph. Any additional captured stream must rejoin the origin stream before capture ends there. An accidental query or synchronization during capture can break this flow.
| Change or execution situation | What to check | Safe decision |
|---|---|---|
| Only input contents are refreshed | Buffer addresses, lifetimes, and copy ordering | Do not free or overwrite graph-referenced memory before completion |
| Kernel parameters or node settings change | Whether the node type supports the relevant update API | Confirm the supported fields and conditions in the documentation |
| Node count, dependencies, or operation order change | Whether graph topology still matches | If structure changes, consider re-instantiation |
| Overlapping runs use the same executable object | Whether its prior run has completed | One cudaGraphExec_t cannot execute concurrently with itself; use separate executable instances if overlap is needed |
A whole-graph update requires a compatible topology and dependency order. APIs can update certain node parameters, but supported fields vary by node type; do not assume every value can change freely. Concurrent runs require multiple executable instances, and their buffers and dependencies must also be safe. Do not assume graph objects themselves are safe for concurrent access from multiple threads.
How do you verify the decision before and after adoption?
Use this sequence to check whether a graph reduces the actual bottleneck without changing results or making memory reuse unsafe.
Profile the existing stream path with representative inputs and real usage conditions; identify the repeated region and its kernel and copy calls.
Separate CPU submission time from device intervals measured with CUDA events or an equivalent GPU timing method. An asynchronous API return time is not GPU completion time.
Capture only a stable repeated region and instantiate it once. Check capture success, node order, and cross-stream dependencies, then compare outputs against the existing path for the same inputs.
Record setup cost separately from steady-state replay cost. Compare total application time with the same inputs and completion conditions; frequent added synchronization can change the original pipeline, so state the measurement boundary.
Decide whether the real replay count recovers setup cost. If the difference cannot be distinguished from measurement noise or operating-condition changes, or capture constraints add too much maintenance work, keep the stream implementation.
CUDA Graphs are an option for reducing repeated work submission. Adopt them when dependencies and memory lifetimes are clear and measurements under equivalent input and completion conditions show a benefit worth the setup and maintenance costs.
Sources
[NVIDIA CUDA Programming Guide — CUDA Graphs](https://docs.nvidia.com/cuda/cuda-programming-guide/04-special-topics/cuda-graphs.html)
[NVIDIA CUDA Runtime API 13.5 — Graph Management](https://docs.nvidia.com/cuda/cuda-runtime-api/cuda_runtime_api/group__CUDART__GRAPH.html)
[NVIDIA CUDA Runtime API 13.5 — Stream Management](https://docs.nvidia.com/cuda/cuda-runtime-api/cuda_runtime_api/group__CUDART__STREAM.html)
[NVIDIA CUDA Programming Guide — Asynchronous Execution](https://docs.nvidia.com/cuda/cuda-programming-guide/02-basics/asynchronous-execution.html)
[NVIDIA CUDA C++ Best Practices Guide — Timing](https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/)