CUDA Graphs for PyTorch
CUDA Graphs capture a sequence of GPU operations once and replay them with
minimal CPU overhead. This skill guides applying CUDA Graphs to PyTorch
training and inference workloads using native PyTorch APIs, Transformer
Engine, and Megatron-LM.
When to Use
Reach for this skill when you encounter:
- Triggers: User wants to optimize with CUDA Graphs, reduce kernel launch
overhead, or speed up training/inference loops
- Symptoms: Low GPU utilization (<80%), many small kernel launches (<50 us
each), CPU-bound training, high kernel launch latency visible in Nsight
Systems profiles
- Keywords: "CUDA graph", "torch.cuda.graph", "make_graphed_callables",
"reduce-overhead", "graph capture", "graph replay", "kernel launch overhead",
"CudaGraphManager", "FullCudaGraphWrapper", "full-iteration graph", "stream
capture"
Do NOT use this skill for:
- General PyTorch performance tuning unrelated to kernel launch overhead
- CUDA kernel development or custom CUDA C++ code
- Host-device sync elimination only (use perf-torch-sync-free skill instead)
- Nsight Systems profiling (use perf-nsight-systems skill)
- TensorFlow/JAX graph compilation (different APIs entirely)
Requirements
| Dependency |
Version |
Notes |
| PyTorch |
>= 1.10 |
torch.cuda.graph() available |
| CUDA |
>= 11.0 |
Graph update APIs |
| GPU |
NVIDIA (any) |
Required for CUDA |
| Nsight Systems |
any |
Optional, for profiling |
| APEX |
any |
Optional, for capturable optimizers |
| Transformer Engine |
>= 2.2 |
Optional, for FP8-aware graphing |
| Megatron-LM |
core >= 0.14.0 |
Optional, for CudaGraphManager / FullCudaGraphWrapper |
API Selection Guide
Choose the API based on your framework and performance needs.
| Situation |
API |
Workflow |
| Quick experiment, unknown graph boundaries |
torch.compile(mode="reduce-overhead") |
Workflow 2 |
| Training, need autograd, no FP8/PP |
torch.cuda.make_graphed_callables() |
Workflow 3 |
| Any PyTorch model, FP8 or PP support |
TE make_graphed_callables |
Workflow 4 |
| Megatron-LM, per-layer, automatic |
MCore CudaGraphManager |
Workflow 5 |
| Maximum perf, full-iteration capture |
MCore FullCudaGraphWrapper |
Workflow 6 |
| Full manual control, custom pipelines |
torch.cuda.graph() |
Workflow 7 |
Decision flowchart:
- Using Megatron-LM with FP8/PP?
- Yes, want maximum perf with static workload --> Workflow 6 (FullCudaGraphWrapper)
- Yes, want per-layer automatic graphing --> Workflow 5 (CudaGraphManager)
- Yes, want manual control over what gets graphed --> Workflow 4 (TE make_graphed_callables)
- Using Transformer Engine without Megatron?
- Yes, need FP8 or PP --> Workflow 4 (TE make_graphed_callables)
- General PyTorch?
- Want zero effort, okay with fragmented graphs --> Workflow 2 (torch.compile)
- Want autograd support, training loop --> Workflow 3 (PyTorch make_graphed_callables)
- Want full manual control --> Workflow 7 (torch.cuda.graph)
Strategy: Start with the highest-level API available for your framework.
Move to lower-level APIs only if you need more control, hit limitations, or
do not achieve the expected performance improvement.
Workflows
Workflow 1: Profile and Decide Whether Graphs Help
Goal: Determine if CUDA Graphs will benefit your workload before investing
effort.
- Profile with Nsight Systems:
nsys profile --cuda-graph-trace=graph python train.py
- Check GPU utilization -- if already >95%, graphs won't help much.
- Look for gaps between kernel launches (CPU overhead) and many small kernels
(<50 us each). These are the targets for graphing.
- Annotate regions of interest to correlate idle GPU time with code:
with torch.cuda.nvtx.range("forward"):
output = model(input)
- Estimate benefit: count kernels per iteration. Workloads with hundreds of
small kernels and <80% GPU utilization are strong candidates.
Expected result: Identified bottleneck regions with low GPU occupancy between
kernels. Proceed to the appropriate workflow from the API Selection Guide.
Workflow 2: torch.compile(mode="reduce-overhead")
Goal: Automatic CUDA Graph capture with zero manual effort.
When to use: Quick experiment, unknown graph boundaries, already using
torch.compile.
Steps:
- Decorate the training step with
@torch.compile(mode="reduce-overhead"):@torch.compile(mode="reduce-overhead")
def train_step(model, x, target, criterion):
output = model(x)
loss = criterion(output, target)
loss.backward()
return loss
- Run the training loop normally -- graphs are captured automatically.
- Profile with Nsight Systems to see captured graphs:
nsys profile --cuda-graph-trace=graph python train.py
- If you see too many small graphs (graph fragmentation), check for graph
breaks:
.item(), print(), data-dependent control flow. Fix these or
escalate to Workflow 3+.
Trade-offs:
- Zero effort, but may create fragmented small graphs.
- Limited control over what gets graphed.
- Graph fragmentation limits performance gains compared to manual approaches.
Workflow 3: torch.cuda.make_graphed_callables()
Goal: Training with autograd support. Separate forward/backward graphs.
When to use: Training with custom loops, non-FP8, need autograd.
Steps:
- Prepare sample inputs matching training batch shape:
sample_input = torch.randn(batch_size, seq_len, hidden_size, device="cuda")
- Create the graphed model:
graphed_model = torch.cuda.make_graphed_callables(
model, (sample_input,), num_warmup_iters=3
)
- Use
graphed_model as a drop-in replacement in the training loop:for data, target in dataloader:
optimizer.zero_grad()
output = graphed_model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
- If using AMP, set
cache_enabled=False:for data, target in dataloader:
optimizer.zero_grad()
with torch.amp.autocast("cuda", cache_enabled=False):
output = graphed_model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
- If using DDP, construct DDP on a side stream and use 11 warmup iters:
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
s = torch.cuda.Stream()
with torch.cuda.stream(s):
model = DistributedDataParallel(model)
torch.cuda.current_stream().wait_stream(s)
graphed_model = torch.cuda.make_graphed_callables(
model, (sample_input,), num_warmup_iters=11
)
Limitations:
- No double backward (higher-order gradients).
- No module hooks during capture.
- Module structure is frozen after graphing (no add/remove parameters).
- Argument signature must match
sample_args exactly.
Workflow 4: TE make_graphed_callables
Goal: Per-callable graphing with FP8 support and pipeline parallelism.
When to use: FP8 training, PP with manual scheduling, non-Megatron models
needing FP8, or any PyTorch model that needs FP8-aware CUDA Graphs.
Steps:
- Import and configure:
from transformer_engine.pytorch.graph import make_graphed_callables
from transformer_engine.pytorch.fp8 import fp8_autocast
- Prepare sample inputs (one per callable per microbatch per chunk):
sample_args = tuple(
(torch.randn(batch_size, seq_len, hidden_size, device="cuda"),)
for _ in range(num_callables * num_microbatches)
)
- Define pipeline schedule if using PP (1-indexed chunk IDs, positive=fwd,
negative=bwd):
# Example: 2 chunks, 3 microbatches
layer_order = [1, 2, 1, 2, 1, 2, -2, -1, -2, -1, -2, -1]
- Wrap layers in CUDA Graphs:
graphed_layers = make_graphed_callables(
tuple(layers),
sample_args=sample_args,
fp8_enabled=True,
fp8_recipe=fp8_recipe,
fp8_weight_caching=True,
_order=layer_order, # None for no PP
)
- Training loop -- wrap with
fp8_autocast during replay:with fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):
for layer in graphed_layers[start:end]:
x = layer(x, is_first_microbatch=(mb_idx == 0))
# FP8 scaling auto-updated on fp8_autocast exit
optimizer.step()
Key points:
- AOT capture: Graphs captured before the training loop when you call
make_graphed_callables().
- Replay order must match
_order: The training loop must execute graphs
in the same interleaved order as specified during capture.
fp8_autocast required during replay: Without it, FP8 state is not
properly configured.
- Weight caching:
fp8_weight_caching=True caches FP8 weight
quantization across microbatches; pass is_first_microbatch kwarg to
control when weights are requantized.
For full API details, see references/api-te-megatron.md.
Workflow 5: MCore CudaGraphManager (Per-Layer)
Goal: Automatic per-layer graphing for Megatron-LM training.
When to use: Megatron-LM training, especially with PP > 1. Default choice
for Megatron users.
Steps:
- Enable via CLI flags (no code changes needed):
python pretrain_gpt.py \
--enable-cuda-graph \
--cuda-graph-num-warmup-steps 3
- Or enable via Python config:
config = TransformerConfig(
enable_cuda_graph=True,
cuda_graph_num_warmup_steps=3,
)
- Training loop is unchanged -- graphs are captured automatically after
warmup iterations.
Key points:
- Megatron layers only: Works with
TransformerLayer and MambaLayer.
- JIT capture: Records execution order during warmup, captures graphs
after warmup completes, then replays on subsequent iterations.
- Automatic FP8 handling: Uses
fp8_autocast(..., _graph=True) to skip
per-layer amax reduction; reduction happens once after all backward graphs.
- Automatic PP support: Handles microbatch interleaving automatically.
- Memory savings: Set
cuda_graph_share_io_buffers=True to share I/O
buffers between layers (requires no operations between layers).
- Memory pool strategy: Default uses separate pools per microbatch for
graph reuse. Set
cuda_graph_use_single_mempool=True for shared pool
(higher graph count but may reduce fragmentation).
Workflow 6: MCore FullCudaGraphWrapper (Full-Iteration)
Goal: Maximum performance. Captures forward+backward for all microbatches
as a single graph.
When to use: Maximum performance priority, static workloads, Megatron-LM
training.
Steps:
- Enable via CLI flags:
python pretrain_gpt.py \
--enable-cuda-graph \
--cuda-graph-scope full_iteration \
--cuda-graph-warmup-steps 1 \
--te-rng-tracker \
--no-check-for-nan-in-loss-and-grad
- Ensure all forward+backward code is capturable (no
.item(), no NaN
check, no dynamic control flow).
- Optimizer remains in eager mode by default (outside the graph). Can be
included inside the graph for maximum performance.
Key points:
- Only 2 graphs total: One for training, one for validation.
--te-rng-tracker required: Standard RNG uses CPU scalars that cannot
be captured; TE RNG uses device tensors compatible with graphs.
--no-check-for-nan-in-loss-and-grad mandatory: NaN checking uses
.item() which requires CPU-GPU sync, forbidden during capture.
- StaticBufferLoader: Pre-allocates input buffers for all microbatches
during warmup.
- Optimizer in/out of graph: Inside = maximum performance (all optimizer
kernels captured). Outside = more flexible (can change optimizer/LR without
recapture).
- JIT capture: Graph captured during training at iteration
warmup_steps + 1.
Workflow 7: torch.cuda.graph() (Manual)
Goal: Full control over capture and replay. Custom pipelines, full-iteration
capture without Megatron.
When to use: Need fine-grained control, non-Megatron full-iteration capture,
custom pipelines.
Inference pattern:
- Pre-allocate static input/output tensors:
static_input = torch.randn(batch_size, *shape, device="cuda")
- Warmup on a side stream (3 iterations, 11 for DDP):
s = torch.cuda.Stream()
with torch.cuda.stream(s):
for _ in range(3):
_ = model(static_input)
torch.cuda.current_stream().wait_stream(s)
- Capture the graph:
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g):
static_output = model(static_input)
- Replay loop -- update inputs via
.copy_(), clone outputs:for data in loader:
static_input.copy_(data)
g.replay()
result = static_output.clone()
Full training pattern (fwd+bwd+optimizer in one graph):
model = MyModel().cuda()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
criterion = torch.nn.CrossEntropyLoss()
static_input = torch.randn(batch_size, *shape, device="cuda")
static_target = torch.randint(0, num_classes, (batch_size,), device="cuda")
# Warmup
s = torch.cuda.Stream()
with torch.cuda.stream(s):
for _ in range(3):
optimizer.zero_grad()
with torch.amp.autocast("cuda", cache_enabled=False):
out = model(static_input)
loss = criterion(out, static_target)
loss.backward()
torch.cuda.current_stream().wait_stream(s)
# Capture
g = torch.cuda.CUDAGraph()
with torch.cuda.graph(g):
optimizer.zero_grad()
with torch.amp.autocast("cuda", cache_enabled=False):
static_output = model(static_input)
static_loss = criterion(static_output, static_target)
static_loss.backward()
# Replay loop
for data, target in loader:
static_input.copy_(data)
static_target.copy_(target)
g.replay()
optimizer.step()
DDP setup:
os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"
s = torch.cuda.Stream()
with torch.cuda.stream(s):
model = DistributedDataParallel(model)
# 11 warmup iterations for DDP
with torch.cuda.stream(s):
for _ in range(11):
out = model(static_input)
out.sum().backward()
torch.cuda.current_stream().wait_stream(s)
# Capture on the same side stream
with torch.cuda.graph(g):
static_output = model(static_input)
Memory pool sharing for multiple graphs:
g1 = torch.cuda.CUDAGraph()
with torch.cuda.graph(g1):
out1 = model_a(static_in_a)
# Second graph shares first graph's memory pool
g2 = torch.cuda.CUDAGraph()
with torch.cuda.graph(g2, pool=g1.pool()):
out2 = model_b(static_in_b)
Custom RNG registration:
gen = torch.cuda.default_generators[0]
g = torch.cuda.CUDAGraph()
g.register_generator_state(gen)
with torch.cuda.graph(g):
out = model(static_input) # RNG state properly captured
Navigating Between Workflows
- torch.compile gives insufficient speedup --> escalate to
make_graphed_callables (Workflow 3) for larger, fewer graphs.
- make_graphed_callables can't handle FP8/PP --> TE
make_graphed_callables (Workflow 4).
- Need Megatron per-layer automatic --> CudaGraphManager (Workflow 5).
- Want maximum perf --> FullCudaGraphWrapper (Workflow 6) or manual
full-iteration capture (Workflow 7).
- Something too hard to graph --> partial capture (graph what you can,
leave the rest in eager mode).
- User wants best absolute perf --> skip directly to Workflow 6
(Megatron) or Workflow 7 (manual).
- Start small, expand progressively: Begin with one module/layer. Verify
correctness. Then expand to more layers, full forward pass, add backward,
and eventually full iteration with optimizer.
Making Code Graph-Compatible
These principles apply to all workflows. Code inside the captured region must
satisfy three constraints.
Principle 1: GPU-Only
Only GPU operations are captured. CPU-side code (Python logic, I/O, logging)
executes during capture but is eliminated during replay.
Violations:
- File I/O:
data = torch.load("file.pt") won't reload on replay
- CPU preprocessing:
tokens = tokenizer.encode(text) won't re-tokenize
- Logging:
print(f"Step {i}") won't print during replay
- CPU RNG:
random.randint(0, 10) won't regenerate
- CPU bookkeeping:
buffer.append(tensor) won't populate during replay
Fix: Move all CPU-side operations outside the graphed region.
Principle 2: Sync-Free
No CPU-GPU synchronization inside the graph. The CPU queues work continuously
without waiting for GPU results.
Violations:
.item() to get scalar values
.cpu() to move tensors for inspection
torch.cuda.synchronize() or stream.synchronize()
print(tensor) (implicitly syncs)
Fix: Invoke the perf-torch-sync-free skill for systematic detection and
elimination of sync points. Use torch.cuda.set_sync_debug_mode("warn") to
find hidden syncs.
Principle 3: Static
All operations, control flow, memory addresses, and shapes must be fixed
across all replays.
Violations and fixes:
| Dynamic aspect |
Fix |
if loss > threshold: |
torch.where(condition, a, b) |
input = new_tensor (address changes) |
Pre-allocate + .copy_() |
| Python scalars (lr, temperature) |
GPU tensor + .fill_() |
| Variable batch size / sequence length |
Padding or bucketing |
| MoE / dynamic routing |
Partial graphing |
For detailed patterns, see references/patterns-dynamic.md.
Compatibility Checklist
Verify every item before attempting capture:
For the complete checklist with references, see references/patterns-compatibility.md.
Output Formats
Success indicators:
g.replay() completes without errors
- Outputs match eager mode within tolerance (
torch.allclose)
- Nsight Systems profile shows single graph launch replacing many kernels
- GPU utilization increases, training/inference latency decreases
Key metrics:
| Metric |
How to Check |
| Correctness |
torch.allclose(eager, graphed, rtol=1e-5) |
| Speedup |
Wall-clock time comparison |
| GPU utilization |
nvidia-smi or Nsight Systems timeline |
| Memory overhead |
torch.cuda.memory_summary() |
Error Handling
| Error |
Cause |
Fix |
StreamCaptureUnsupported (900) |
Sync op during capture (.item(), .cpu()) |
Move sync outside graph |
StreamCaptureInvalidated (901) |
Background thread (e.g., pin_memory) |
capture_error_mode="thread_local" |
StreamCaptureUnjoined (904) |
Side stream didn't rejoin capture stream |
capture_stream.wait_stream(side_stream) |
StreamCaptureImplicit (906) |
AccumulateGrad on default stream |
Warmup on side stream before capture |
| Illegal memory access |
Input tensor freed/reassigned |
Keep persistent ref, use .copy_() |
| Wrong numerical results |
Dynamic behavior frozen at capture |
See references/patterns-compatibility.md |
| OOM with multiple graphs |
Pools can't share memory |
pool=g1.pool() for sequential graphs |
| No speedup |
Already GPU-bound or wrong capture scope |
Profile with nsys first (Workflow 1) |
| FP8 scaling corruption |
TE without fp8_autocast during replay |
Wrap with fp8_autocast(enabled=True) |
| PP replay order mismatch |
Wrong execution order during replay |
Match _order / capture sequence exactly |
| FullCudaGraphWrapper capture fail |
NaN check or sync enabled |
--no-check-for-nan-in-loss-and-grad |
| RNG failure with FullCudaGraphWrapper |
Standard RNG not capturable |
--te-rng-tracker |
| DDP capture failure |
Async error handling watchdog |
TORCH_NCCL_ASYNC_ERROR_HANDLING=0 |
| DDP AccumulateGrad on default stream |
DDP constructed on default stream |
Construct DDP in side stream context |
| Autocast cache invalidation |
Cached cast tensors freed on exit |
cache_enabled=False |
For detailed troubleshooting, see references/troubleshooting.md.
Finding More Information
Use this 3-tier lookup hierarchy -- start at Tier 1 and escalate only when
needed.
Tier 1: This File (SKILL.md)
You are reading it now. The workflows, compatibility checklist, and error
table above cover the most common tasks. Search this file first before going
deeper.
Tier 2: references/ Directory
The references/ directory beside this file contains distilled reference
material -- API details, patterns, and troubleshooting pages.
How to search:
- Grep for your keyword across
references/ -- headers are designed to be
grep-friendly.
- Read only the file that grep points you to. Do not read every file.
Available references:
references/api-pytorch.md -- PyTorch CUDA Graph APIs (torch.cuda.graph,
make_graphed_callables, torch.compile reduce-overhead)
references/api-te-megatron.md -- TE make_graphed_callables,
CudaGraphManager, FullCudaGraphWrapper implementations
references/patterns-compatibility.md -- GPU-only, sync-free, and static
principles with full checklist
references/patterns-dynamic.md -- Dynamic control flow, tensors, scalars,
shapes: workarounds and patterns
references/troubleshooting.md -- Capture failures, numerical errors,
memory issues, performance issues
Tier 3: Original Documentation
If Tiers 1-2 do not answer the question, consult the original sources:
- NVIDIA guide:
https://docs.nvidia.com/dl-cuda-graph/latest/index.html
- PyTorch docs:
https://docs.pytorch.org/docs/stable/notes/cuda.html
(CUDA Graphs section)
- TE docs:
https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/index.html
- Megatron Core docs:
https://docs.nvidia.com/megatron-core/developer-guide/latest/index.html
Return to Tier 2 afterward and consider whether the answer should be distilled
into the references directory for next time.
1---2name: nvidia-tensorrt-llm-perf-torch-cuda-graphs3description: 'Apply CUDA Graphs to PyTorch workloads — API selection (torch.compile,4 PyTorch make_graphed_callables, TE make_graphed_callables, MCore CudaGraphManager,5 FullCudaGraphWrapper, manual torch.cuda.graph), code compatibility, capture workflows,6 dynamic pattern handling, and troubleshooting. Triggers: CUDA graph, torch.cuda.graph,7 make_graphed_callables, reduce-overhead, graph capture, graph replay, kernel launch8 overhead, CudaGraphManager, FullCudaGraphWrapper, full-iteration graph, stream capture.'9license: Apache-2.010metadata:11 author: NVIDIA Corporation12 tags:13 - cuda-graph14 - optimization15 - pytorch16---1718# CUDA Graphs for PyTorch1920CUDA Graphs capture a sequence of GPU operations once and replay them with21minimal CPU overhead. This skill guides applying CUDA Graphs to PyTorch22training and inference workloads using native PyTorch APIs, Transformer23Engine, and Megatron-LM.2425## When to Use2627Reach for this skill when you encounter:2829- **Triggers**: User wants to optimize with CUDA Graphs, reduce kernel launch30 overhead, or speed up training/inference loops31- **Symptoms**: Low GPU utilization (<80%), many small kernel launches (<50 us32 each), CPU-bound training, high kernel launch latency visible in Nsight33 Systems profiles34- **Keywords**: "CUDA graph", "torch.cuda.graph", "make_graphed_callables",35 "reduce-overhead", "graph capture", "graph replay", "kernel launch overhead",36 "CudaGraphManager", "FullCudaGraphWrapper", "full-iteration graph", "stream37 capture"3839Do NOT use this skill for:4041- General PyTorch performance tuning unrelated to kernel launch overhead42- CUDA kernel development or custom CUDA C++ code43- Host-device sync elimination only (use **perf-torch-sync-free** skill instead)44- Nsight Systems profiling (use **perf-nsight-systems** skill)45- TensorFlow/JAX graph compilation (different APIs entirely)4647## Requirements4849| Dependency | Version | Notes |50|------------|---------|-------|51| PyTorch | >= 1.10 | `torch.cuda.graph()` available |52| CUDA | >= 11.0 | Graph update APIs |53| GPU | NVIDIA (any) | Required for CUDA |54| Nsight Systems | any | Optional, for profiling |55| APEX | any | Optional, for capturable optimizers |56| Transformer Engine | >= 2.2 | Optional, for FP8-aware graphing |57| Megatron-LM | core >= 0.14.0 | Optional, for CudaGraphManager / FullCudaGraphWrapper |5859## API Selection Guide6061Choose the API based on your framework and performance needs.6263| Situation | API | Workflow |64|-----------|-----|---------|65| Quick experiment, unknown graph boundaries | `torch.compile(mode="reduce-overhead")` | Workflow 2 |66| Training, need autograd, no FP8/PP | `torch.cuda.make_graphed_callables()` | Workflow 3 |67| Any PyTorch model, FP8 or PP support | TE `make_graphed_callables` | Workflow 4 |68| Megatron-LM, per-layer, automatic | MCore `CudaGraphManager` | Workflow 5 |69| Maximum perf, full-iteration capture | MCore `FullCudaGraphWrapper` | Workflow 6 |70| Full manual control, custom pipelines | `torch.cuda.graph()` | Workflow 7 |7172**Decision flowchart:**73741. Using Megatron-LM with FP8/PP?75 - Yes, want maximum perf with static workload --> Workflow 6 (FullCudaGraphWrapper)76 - Yes, want per-layer automatic graphing --> Workflow 5 (CudaGraphManager)77 - Yes, want manual control over what gets graphed --> Workflow 4 (TE make_graphed_callables)782. Using Transformer Engine without Megatron?79 - Yes, need FP8 or PP --> Workflow 4 (TE make_graphed_callables)803. General PyTorch?81 - Want zero effort, okay with fragmented graphs --> Workflow 2 (torch.compile)82 - Want autograd support, training loop --> Workflow 3 (PyTorch make_graphed_callables)83 - Want full manual control --> Workflow 7 (torch.cuda.graph)8485**Strategy:** Start with the highest-level API available for your framework.86Move to lower-level APIs only if you need more control, hit limitations, or87do not achieve the expected performance improvement.8889## Workflows9091### Workflow 1: Profile and Decide Whether Graphs Help9293Goal: Determine if CUDA Graphs will benefit your workload before investing94effort.95961. Profile with Nsight Systems:97 ```bash98 nsys profile --cuda-graph-trace=graph python train.py99 ```1002. Check GPU utilization -- if already >95%, graphs won't help much.1013. Look for gaps between kernel launches (CPU overhead) and many small kernels102 (<50 us each). These are the targets for graphing.1034. Annotate regions of interest to correlate idle GPU time with code:104 ```python105 with torch.cuda.nvtx.range("forward"):106 output = model(input)107 ```1085. Estimate benefit: count kernels per iteration. Workloads with hundreds of109 small kernels and <80% GPU utilization are strong candidates.110111Expected result: Identified bottleneck regions with low GPU occupancy between112kernels. Proceed to the appropriate workflow from the API Selection Guide.113114### Workflow 2: torch.compile(mode="reduce-overhead")115116Goal: Automatic CUDA Graph capture with zero manual effort.117118When to use: Quick experiment, unknown graph boundaries, already using119`torch.compile`.120121Steps:1221231. Decorate the training step with `@torch.compile(mode="reduce-overhead")`:124 ```python125 @torch.compile(mode="reduce-overhead")126 def train_step(model, x, target, criterion):127 output = model(x)128 loss = criterion(output, target)129 loss.backward()130 return loss131 ```1322. Run the training loop normally -- graphs are captured automatically.1333. Profile with Nsight Systems to see captured graphs:134 ```bash135 nsys profile --cuda-graph-trace=graph python train.py136 ```1374. If you see too many small graphs (graph fragmentation), check for graph138 breaks: `.item()`, `print()`, data-dependent control flow. Fix these or139 escalate to Workflow 3+.140141Trade-offs:142- Zero effort, but may create fragmented small graphs.143- Limited control over what gets graphed.144- Graph fragmentation limits performance gains compared to manual approaches.145146### Workflow 3: torch.cuda.make_graphed_callables()147148Goal: Training with autograd support. Separate forward/backward graphs.149150When to use: Training with custom loops, non-FP8, need autograd.151152Steps:1531541. Prepare sample inputs matching training batch shape:155 ```python156 sample_input = torch.randn(batch_size, seq_len, hidden_size, device="cuda")157 ```1582. Create the graphed model:159 ```python160 graphed_model = torch.cuda.make_graphed_callables(161 model, (sample_input,), num_warmup_iters=3162 )163 ```1643. Use `graphed_model` as a drop-in replacement in the training loop:165 ```python166 for data, target in dataloader:167 optimizer.zero_grad()168 output = graphed_model(data)169 loss = criterion(output, target)170 loss.backward()171 optimizer.step()172 ```1734. If using AMP, set `cache_enabled=False`:174 ```python175 for data, target in dataloader:176 optimizer.zero_grad()177 with torch.amp.autocast("cuda", cache_enabled=False):178 output = graphed_model(data)179 loss = criterion(output, target)180 loss.backward()181 optimizer.step()182 ```1835. If using DDP, construct DDP on a side stream and use 11 warmup iters:184 ```python185 os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"186 s = torch.cuda.Stream()187 with torch.cuda.stream(s):188 model = DistributedDataParallel(model)189 torch.cuda.current_stream().wait_stream(s)190191 graphed_model = torch.cuda.make_graphed_callables(192 model, (sample_input,), num_warmup_iters=11193 )194 ```195196Limitations:197- No double backward (higher-order gradients).198- No module hooks during capture.199- Module structure is frozen after graphing (no add/remove parameters).200- Argument signature must match `sample_args` exactly.201202### Workflow 4: TE make_graphed_callables203204Goal: Per-callable graphing with FP8 support and pipeline parallelism.205206When to use: FP8 training, PP with manual scheduling, non-Megatron models207needing FP8, or any PyTorch model that needs FP8-aware CUDA Graphs.208209Steps:2102111. Import and configure:212 ```python213 from transformer_engine.pytorch.graph import make_graphed_callables214 from transformer_engine.pytorch.fp8 import fp8_autocast215 ```2162. Prepare sample inputs (one per callable per microbatch per chunk):217 ```python218 sample_args = tuple(219 (torch.randn(batch_size, seq_len, hidden_size, device="cuda"),)220 for _ in range(num_callables * num_microbatches)221 )222 ```2233. Define pipeline schedule if using PP (1-indexed chunk IDs, positive=fwd,224 negative=bwd):225 ```python226 # Example: 2 chunks, 3 microbatches227 layer_order = [1, 2, 1, 2, 1, 2, -2, -1, -2, -1, -2, -1]228 ```2294. Wrap layers in CUDA Graphs:230 ```python231 graphed_layers = make_graphed_callables(232 tuple(layers),233 sample_args=sample_args,234 fp8_enabled=True,235 fp8_recipe=fp8_recipe,236 fp8_weight_caching=True,237 _order=layer_order, # None for no PP238 )239 ```2405. Training loop -- wrap with `fp8_autocast` during replay:241 ```python242 with fp8_autocast(enabled=True, fp8_recipe=fp8_recipe):243 for layer in graphed_layers[start:end]:244 x = layer(x, is_first_microbatch=(mb_idx == 0))245 # FP8 scaling auto-updated on fp8_autocast exit246 optimizer.step()247 ```248249Key points:250- **AOT capture**: Graphs captured before the training loop when you call251 `make_graphed_callables()`.252- **Replay order must match `_order`**: The training loop must execute graphs253 in the same interleaved order as specified during capture.254- **`fp8_autocast` required during replay**: Without it, FP8 state is not255 properly configured.256- **Weight caching**: `fp8_weight_caching=True` caches FP8 weight257 quantization across microbatches; pass `is_first_microbatch` kwarg to258 control when weights are requantized.259260For full API details, see `references/api-te-megatron.md`.261262### Workflow 5: MCore CudaGraphManager (Per-Layer)263264Goal: Automatic per-layer graphing for Megatron-LM training.265266When to use: Megatron-LM training, especially with PP > 1. Default choice267for Megatron users.268269Steps:2702711. Enable via CLI flags (no code changes needed):272 ```bash273 python pretrain_gpt.py \274 --enable-cuda-graph \275 --cuda-graph-num-warmup-steps 3276 ```2772. Or enable via Python config:278 ```python279 config = TransformerConfig(280 enable_cuda_graph=True,281 cuda_graph_num_warmup_steps=3,282 )283 ```2843. Training loop is unchanged -- graphs are captured automatically after285 warmup iterations.286287Key points:288- **Megatron layers only**: Works with `TransformerLayer` and `MambaLayer`.289- **JIT capture**: Records execution order during warmup, captures graphs290 after warmup completes, then replays on subsequent iterations.291- **Automatic FP8 handling**: Uses `fp8_autocast(..., _graph=True)` to skip292 per-layer amax reduction; reduction happens once after all backward graphs.293- **Automatic PP support**: Handles microbatch interleaving automatically.294- **Memory savings**: Set `cuda_graph_share_io_buffers=True` to share I/O295 buffers between layers (requires no operations between layers).296- **Memory pool strategy**: Default uses separate pools per microbatch for297 graph reuse. Set `cuda_graph_use_single_mempool=True` for shared pool298 (higher graph count but may reduce fragmentation).299300### Workflow 6: MCore FullCudaGraphWrapper (Full-Iteration)301302Goal: Maximum performance. Captures forward+backward for all microbatches303as a single graph.304305When to use: Maximum performance priority, static workloads, Megatron-LM306training.307308Steps:3093101. Enable via CLI flags:311 ```bash312 python pretrain_gpt.py \313 --enable-cuda-graph \314 --cuda-graph-scope full_iteration \315 --cuda-graph-warmup-steps 1 \316 --te-rng-tracker \317 --no-check-for-nan-in-loss-and-grad318 ```3192. Ensure all forward+backward code is capturable (no `.item()`, no NaN320 check, no dynamic control flow).3213. Optimizer remains in eager mode by default (outside the graph). Can be322 included inside the graph for maximum performance.323324Key points:325- **Only 2 graphs total**: One for training, one for validation.326- **`--te-rng-tracker` required**: Standard RNG uses CPU scalars that cannot327 be captured; TE RNG uses device tensors compatible with graphs.328- **`--no-check-for-nan-in-loss-and-grad` mandatory**: NaN checking uses329 `.item()` which requires CPU-GPU sync, forbidden during capture.330- **StaticBufferLoader**: Pre-allocates input buffers for all microbatches331 during warmup.332- **Optimizer in/out of graph**: Inside = maximum performance (all optimizer333 kernels captured). Outside = more flexible (can change optimizer/LR without334 recapture).335- **JIT capture**: Graph captured during training at iteration336 `warmup_steps + 1`.337338### Workflow 7: torch.cuda.graph() (Manual)339340Goal: Full control over capture and replay. Custom pipelines, full-iteration341capture without Megatron.342343When to use: Need fine-grained control, non-Megatron full-iteration capture,344custom pipelines.345346**Inference pattern:**3473481. Pre-allocate static input/output tensors:349 ```python350 static_input = torch.randn(batch_size, *shape, device="cuda")351 ```3522. Warmup on a side stream (3 iterations, 11 for DDP):353 ```python354 s = torch.cuda.Stream()355 with torch.cuda.stream(s):356 for _ in range(3):357 _ = model(static_input)358 torch.cuda.current_stream().wait_stream(s)359 ```3603. Capture the graph:361 ```python362 g = torch.cuda.CUDAGraph()363 with torch.cuda.graph(g):364 static_output = model(static_input)365 ```3664. Replay loop -- update inputs via `.copy_()`, clone outputs:367 ```python368 for data in loader:369 static_input.copy_(data)370 g.replay()371 result = static_output.clone()372 ```373374**Full training pattern (fwd+bwd+optimizer in one graph):**375376```python377model = MyModel().cuda()378optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)379criterion = torch.nn.CrossEntropyLoss()380381static_input = torch.randn(batch_size, *shape, device="cuda")382static_target = torch.randint(0, num_classes, (batch_size,), device="cuda")383384# Warmup385s = torch.cuda.Stream()386with torch.cuda.stream(s):387 for _ in range(3):388 optimizer.zero_grad()389 with torch.amp.autocast("cuda", cache_enabled=False):390 out = model(static_input)391 loss = criterion(out, static_target)392 loss.backward()393torch.cuda.current_stream().wait_stream(s)394395# Capture396g = torch.cuda.CUDAGraph()397with torch.cuda.graph(g):398 optimizer.zero_grad()399 with torch.amp.autocast("cuda", cache_enabled=False):400 static_output = model(static_input)401 static_loss = criterion(static_output, static_target)402 static_loss.backward()403404# Replay loop405for data, target in loader:406 static_input.copy_(data)407 static_target.copy_(target)408 g.replay()409 optimizer.step()410```411412**DDP setup:**413414```python415os.environ["TORCH_NCCL_ASYNC_ERROR_HANDLING"] = "0"416417s = torch.cuda.Stream()418with torch.cuda.stream(s):419 model = DistributedDataParallel(model)420421# 11 warmup iterations for DDP422with torch.cuda.stream(s):423 for _ in range(11):424 out = model(static_input)425 out.sum().backward()426torch.cuda.current_stream().wait_stream(s)427428# Capture on the same side stream429with torch.cuda.graph(g):430 static_output = model(static_input)431```432433**Memory pool sharing for multiple graphs:**434435```python436g1 = torch.cuda.CUDAGraph()437with torch.cuda.graph(g1):438 out1 = model_a(static_in_a)439440# Second graph shares first graph's memory pool441g2 = torch.cuda.CUDAGraph()442with torch.cuda.graph(g2, pool=g1.pool()):443 out2 = model_b(static_in_b)444```445446**Custom RNG registration:**447448```python449gen = torch.cuda.default_generators[0]450g = torch.cuda.CUDAGraph()451g.register_generator_state(gen)452with torch.cuda.graph(g):453 out = model(static_input) # RNG state properly captured454```455456### Navigating Between Workflows457458- **torch.compile gives insufficient speedup** --> escalate to459 `make_graphed_callables` (Workflow 3) for larger, fewer graphs.460- **make_graphed_callables can't handle FP8/PP** --> TE461 `make_graphed_callables` (Workflow 4).462- **Need Megatron per-layer automatic** --> CudaGraphManager (Workflow 5).463- **Want maximum perf** --> FullCudaGraphWrapper (Workflow 6) or manual464 full-iteration capture (Workflow 7).465- **Something too hard to graph** --> partial capture (graph what you can,466 leave the rest in eager mode).467- **User wants best absolute perf** --> skip directly to Workflow 6468 (Megatron) or Workflow 7 (manual).469- **Start small, expand progressively**: Begin with one module/layer. Verify470 correctness. Then expand to more layers, full forward pass, add backward,471 and eventually full iteration with optimizer.472473## Making Code Graph-Compatible474475These principles apply to all workflows. Code inside the captured region must476satisfy three constraints.477478### Principle 1: GPU-Only479480Only GPU operations are captured. CPU-side code (Python logic, I/O, logging)481executes during capture but is eliminated during replay.482483Violations:484- File I/O: `data = torch.load("file.pt")` won't reload on replay485- CPU preprocessing: `tokens = tokenizer.encode(text)` won't re-tokenize486- Logging: `print(f"Step {i}")` won't print during replay487- CPU RNG: `random.randint(0, 10)` won't regenerate488- CPU bookkeeping: `buffer.append(tensor)` won't populate during replay489490Fix: Move all CPU-side operations outside the graphed region.491492### Principle 2: Sync-Free493494No CPU-GPU synchronization inside the graph. The CPU queues work continuously495without waiting for GPU results.496497Violations:498- `.item()` to get scalar values499- `.cpu()` to move tensors for inspection500- `torch.cuda.synchronize()` or `stream.synchronize()`501- `print(tensor)` (implicitly syncs)502503Fix: **Invoke the perf-torch-sync-free skill** for systematic detection and504elimination of sync points. Use `torch.cuda.set_sync_debug_mode("warn")` to505find hidden syncs.506507### Principle 3: Static508509All operations, control flow, memory addresses, and shapes must be fixed510across all replays.511512Violations and fixes:513514| Dynamic aspect | Fix |515|---------------|-----|516| `if loss > threshold:` | `torch.where(condition, a, b)` |517| `input = new_tensor` (address changes) | Pre-allocate + `.copy_()` |518| Python scalars (lr, temperature) | GPU tensor + `.fill_()` |519| Variable batch size / sequence length | Padding or bucketing |520| MoE / dynamic routing | Partial graphing |521522For detailed patterns, see `references/patterns-dynamic.md`.523524### Compatibility Checklist525526Verify every item before attempting capture:527528- [ ] No `.item()`, `.cpu()`, `.numpy()`, `print(tensor)` inside graph529- [ ] No `torch.cuda.synchronize()` or `stream.synchronize()`530- [ ] No `if tensor_value:` -- use `torch.where()` instead531- [ ] All inputs pre-allocated, updated via `.copy_()`532- [ ] All shapes fixed (use padding or bucketing for variable sizes)533- [ ] Python scalars --> GPU tensors with `.fill_()`534- [ ] Output tensors `.clone()`d before next replay535- [ ] `cache_enabled=False` with `torch.amp.autocast`536- [ ] Custom RNG generators registered with `graph.register_generator_state()`537- [ ] Use `graphsafe_get_state()` / `graphsafe_set_state()` for RNG538- [ ] Warmup completed (3 standard, 11 for DDP)539- [ ] DDP: `TORCH_NCCL_ASYNC_ERROR_HANDLING=0`, construct on side stream540- [ ] DDP: NCCL >= 2.9.6 for full graph capture541- [ ] Libraries/extensions use `torch.cuda.current_stream()`, not default stream542- [ ] No pinned memory allocation during capture (triggers hidden event query)543- [ ] `activation_checkpointing`: `preserve_rng_state=False`544- [ ] Global tensors used in graph kept alive (not deleted/reassigned)545- [ ] No `torch.compile` functions inside manual capture without prior warmup546- [ ] Gradient clipping uses sync-free `clip_grad_norm_` (PyTorch >= 1.13)547548For the complete checklist with references, see `references/patterns-compatibility.md`.549550## Output Formats551552**Success indicators:**553- `g.replay()` completes without errors554- Outputs match eager mode within tolerance (`torch.allclose`)555- Nsight Systems profile shows single graph launch replacing many kernels556- GPU utilization increases, training/inference latency decreases557558**Key metrics:**559560| Metric | How to Check |561|--------|-------------|562| Correctness | `torch.allclose(eager, graphed, rtol=1e-5)` |563| Speedup | Wall-clock time comparison |564| GPU utilization | `nvidia-smi` or Nsight Systems timeline |565| Memory overhead | `torch.cuda.memory_summary()` |566567## Error Handling568569| Error | Cause | Fix |570|-------|-------|-----|571| `StreamCaptureUnsupported` (900) | Sync op during capture (`.item()`, `.cpu()`) | Move sync outside graph |572| `StreamCaptureInvalidated` (901) | Background thread (e.g., pin_memory) | `capture_error_mode="thread_local"` |573| `StreamCaptureUnjoined` (904) | Side stream didn't rejoin capture stream | `capture_stream.wait_stream(side_stream)` |574| `StreamCaptureImplicit` (906) | AccumulateGrad on default stream | Warmup on side stream before capture |575| Illegal memory access | Input tensor freed/reassigned | Keep persistent ref, use `.copy_()` |576| Wrong numerical results | Dynamic behavior frozen at capture | See `references/patterns-compatibility.md` |577| OOM with multiple graphs | Pools can't share memory | `pool=g1.pool()` for sequential graphs |578| No speedup | Already GPU-bound or wrong capture scope | Profile with nsys first (Workflow 1) |579| FP8 scaling corruption | TE without `fp8_autocast` during replay | Wrap with `fp8_autocast(enabled=True)` |580| PP replay order mismatch | Wrong execution order during replay | Match `_order` / capture sequence exactly |581| FullCudaGraphWrapper capture fail | NaN check or sync enabled | `--no-check-for-nan-in-loss-and-grad` |582| RNG failure with FullCudaGraphWrapper | Standard RNG not capturable | `--te-rng-tracker` |583| DDP capture failure | Async error handling watchdog | `TORCH_NCCL_ASYNC_ERROR_HANDLING=0` |584| DDP AccumulateGrad on default stream | DDP constructed on default stream | Construct DDP in side stream context |585| Autocast cache invalidation | Cached cast tensors freed on exit | `cache_enabled=False` |586587For detailed troubleshooting, see `references/troubleshooting.md`.588589## Finding More Information590591Use this 3-tier lookup hierarchy -- start at Tier 1 and escalate only when592needed.593594### Tier 1: This File (SKILL.md)595596You are reading it now. The workflows, compatibility checklist, and error597table above cover the most common tasks. Search this file first before going598deeper.599600### Tier 2: references/ Directory601602The `references/` directory beside this file contains distilled reference603material -- API details, patterns, and troubleshooting pages.604605**How to search:**6061. Grep for your keyword across `references/` -- headers are designed to be607 grep-friendly.6082. Read only the file that grep points you to. Do not read every file.609610Available references:611- `references/api-pytorch.md` -- PyTorch CUDA Graph APIs (`torch.cuda.graph`,612 `make_graphed_callables`, `torch.compile reduce-overhead`)613- `references/api-te-megatron.md` -- TE `make_graphed_callables`,614 CudaGraphManager, FullCudaGraphWrapper implementations615- `references/patterns-compatibility.md` -- GPU-only, sync-free, and static616 principles with full checklist617- `references/patterns-dynamic.md` -- Dynamic control flow, tensors, scalars,618 shapes: workarounds and patterns619- `references/troubleshooting.md` -- Capture failures, numerical errors,620 memory issues, performance issues621622### Tier 3: Original Documentation623624If Tiers 1-2 do not answer the question, consult the original sources:625- **NVIDIA guide**: `https://docs.nvidia.com/dl-cuda-graph/latest/index.html`626- **PyTorch docs**: `https://docs.pytorch.org/docs/stable/notes/cuda.html`627 (CUDA Graphs section)628- **TE docs**: `https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/index.html`629- **Megatron Core docs**: `https://docs.nvidia.com/megatron-core/developer-guide/latest/index.html`630631Return to Tier 2 afterward and consider whether the answer should be distilled632into the references directory for next time.