Skip to content

[cuda graphs] Add enable_annotations kwarg to torch.cuda.graph - #179867

Closed
yushangdi wants to merge 4 commits into
gh/yushangdi/26/basefrom
gh/yushangdi/26/head
Closed

yushangdi wants to merge 4 commits into
gh/yushangdi/26/basefrom
gh/yushangdi/26/head

Conversation

@yushangdi

@yushangdi yushangdi commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/179867

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ No Failures

As of commit 0ac0d6f with merge base a4a69be (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot

pytorch-bot Bot commented Apr 9, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

…raph"

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.

[ghstack-poisoned]
@yushangdi
yushangdi requested a review from ngimel April 9, 2026 22:48
@yushangdi yushangdi added the release notes: cuda release notes category label Apr 10, 2026
…raph"

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.

[ghstack-poisoned]
…raph"

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.

[ghstack-poisoned]
@yushangdi yushangdi added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 13, 2026
@yushangdi

Copy link
Copy Markdown
Contributor Author

note: similar to D99385663.

@ngimel ngimel left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, looks great!

@yushangdi

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

yushangdi added a commit to pytorch/torchtitan that referenced this pull request Apr 21, 2026
Need pytorch/pytorch#179867 and cuda 13.1
driver/compat

## [graph_trainer] Add CUDA graph kernel annotation pass

### Summary

Adds a compiler pass that automatically labels CUDA graph kernels with
their originating `nn.Module` path in profiler traces. When enabled,
Perfetto/chrome traces show which component each kernel belongs to
(e.g., `layers.0.attention.wq`, `layers.0.feed_forward.w1`, `norm`).
Both forward and backward kernels are annotated.

No model code changes required — module paths are derived from the
existing `nn.Module` hierarchy.

### How it works

1. **`annotate_module_fqns(model)`** walks the `nn.Module` tree and
wraps each submodule's `forward` with
`torch.fx.traceback.annotate_fn({"module_fqn": fqn})`. This sets
`node.meta["custom"]["module_fqn"]` on all FX nodes during tracing —
surviving dynamo, `make_fx`, and export tracers. Backward nodes receive
the metadata via `_copy_fwd_metadata_to_bw_nodes`.

2. **`insert_kernel_annotations_pass`** reads the `module_fqn` metadata
from FX nodes and inserts `mark_kernels()` enter/exit calls at module
boundaries in the graph. Bundled with `cudagraph_pass` — runs
automatically whenever cudagraph is used. No-op when `cuda-python` or
`cuda-compat >= 13.1` is unavailable.

3. **`CUDAGraphWrapper`** captures the annotations during CUDA graph
recording when the pass is active, and registers a trace post-processor
with the core profiler.

4. **Profiler integration** — `profiling.py` exposes
`register_trace_post_processor()` so experiment code can hook into trace
export without core importing from experiments. The annotation
post-processor merges kernel annotations into the trace automatically.

### Usage

The annotation pass runs automatically in `aot_fx_trace` mode when
cudagraph is compatible. Profiler traces come out pre-annotated:

```bash
NGPU=1 MODULE=graph_trainer.llama3 CONFIG=graph_trainer_llama3_debugmodel ./run_train.sh \
    --compile.mode aot_fx_trace \
    --profiling.enable_profiling \
    --profiling.profile_freq 4
```

Open the exported trace at `outputs/.../rank0_trace.json` in
https://ui.perfetto.dev to see module labels on each kernel.

### Example output (Llama3 debug model, 6 layers)

```
tok_embeddings                      → embedding gather
layers.0.attention_norm             → RMSNorm
layers.0.attention.wq/.wk/.wv      → Q/K/V projections
layers.0.attention                  → RoPE, reshapes
layers.0.attention.inner_attention  → flash_fwd_kernel
layers.0.attention.wo               → output projection
layers.0.ffn_norm                   → RMSNorm
layers.0.feed_forward.w1/.w3       → gate/up projections
layers.0.feed_forward               → silu + mul
layers.0.feed_forward.w2            → down projection
norm                                → final RMSNorm
output                              → output linear
```

### Requirements

Requires PyTorch with `torch.cuda._graph_annotations` module and
`enable_annotations` kwarg on `torch.cuda.graph()`. Falls back
gracefully when unavailable (pass is a no-op).

### Files changed

| File | Change |
|------|--------|
| `common_utils.py` | Add `annotate_module_fqns()` and `_MODULE_FQN`
constant |
| `passes.py` | Add `insert_kernel_annotations_pass` (bundled with
cudagraph pass), with alternative approaches documented |
| `cudagraph.py` | Add `enable_annotations` flag,
`enable_cudagraph_annotations()`, `get_cudagraph_annotations()`, trace
post-processor registration |
| `llama3/parallelize.py` | Call `annotate_module_fqns(model)` in
`annotate_llama()` |
| `deepseek_v3/parallelize.py` | Call `annotate_module_fqns(model)` in
`annotate_deepseekv3()` |
| `qwen3/parallelize.py` | Call `annotate_module_fqns(model)` in
`annotate_qwen3()` |
| `tools/profiling.py` | Add `register_trace_post_processor()` callback
API (no experiment imports) |
| `models/common/attention.py` | Remove unused `import os` +
`DISABLE_LLVM_OPT` |
| `tests/test_passes.py` | 5 unit tests: transformer-like model with
`trace_train_step`, pass insertion, no-op when unavailable, no-op
without metadata, xfail for same-class instances |
| `tests/profiler_tests.py` | E2E test: `trace_train_step` fwd+bwd →
pass → cudagraph → profile → verify `module_fqn` in trace for both fwd
and bwd kernels |
| `.github/workflows/integration_test_8gpu_graph_trainer.yaml` | Add
annotation tests to CI |

### Test plan

```bash
# Unit tests (single GPU):
python -m torchtitan.experiments.graph_trainer.tests.test_passes TestAnnotateModuleFqns -v

# E2E profiler test (single GPU, requires cuda-compat >= 13.1):
LD_LIBRARY_PATH=$CONDA_PREFIX/cuda-compat:$LD_LIBRARY_PATH \
    python -m torchtitan.experiments.graph_trainer.tests.profiler_tests -v

# Full training run (single GPU):
NGPU=1 LD_LIBRARY_PATH=$CONDA_PREFIX/cuda-compat:$LD_LIBRARY_PATH \
    torchrun --nproc_per_node=1 --rdzv_backend c10d --rdzv_endpoint="localhost:0" \
    -m torchtitan.train --module graph_trainer.llama3 --config graph_trainer_llama3_debugmodel \
    --compile.mode aot_fx_trace \
    --training.steps 4 --profiler.enable_profiling --profiler.profile_freq 4
```

Authored with Claude.


Example:

```
NGPU=4 LD_LIBRARY_PATH=/home/shangdiy/.conda/envs/pytorch-3.12/cuda-compat:$LD_LIBRARY_PATH \
  torchrun --nproc_per_node=1 --rdzv_backend c10d --rdzv_endpoint="localhost:0" \
      -m torchtitan.train \
      --module graph_trainer.llama3 \
      --config graph_trainer_llama3_debugmodel \
      --compile.mode aot_fx_trace \
      --training.steps 4 \
      --profiler.enable_profiling \
      --profiler.save_traces_folder agent_space/traces \
      --profiler.profile_freq 4 
```

Result: 


https://www.internalfb.com/intern/perfetto/open_trace/?manifold_path=perfetto_internal_traces%2Ftree%2Fshared_trace%2Fshangdiy_22d012fd-21e5-412f-aa06-d17a32426030_rank0_trace.json

<img width="1232" height="726" alt="Screenshot 2026-04-14 at 1 48 16 PM"
src="https://github.com/user-attachments/assets/fe8e62f4-97cd-4f8d-866e-ff648af0e065"
/>
@github-actions
github-actions Bot deleted the gh/yushangdi/26/head branch May 14, 2026 02:27
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ch#179867)

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.
Pull Request resolved: pytorch#179867
Approved by: https://github.com/ngimel
ghstack dependencies: pytorch#179768
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#179867)

Extend the torch.cuda.graph context manager with an enable_annotations
keyword that enables kernel annotation recording on entry and
automatically calls resolve_pending_annotations() before the capture
ends. Annotations are not cleared on exit so multiple graphs in the
same workload can accumulate annotations.

Authored with Claude.
Pull Request resolved: pytorch#179867
Approved by: https://github.com/ngimel
ghstack dependencies: pytorch#179768
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: cuda release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants