Repository navigation
Conversation
Add infrastructure to annotate individual kernels within CUDA graph captures so their metadata appears in perfetto/chrome profiler traces. Port of D95237028 and D96410655 to OSS PyTorch. - torch/cuda/_graph_annotations.py: Core module with mark_kernels() context manager, resolve_pending_annotations(), remap_to_exec_graph(), mark_stream(), and stream ID registry. Uses cuda.bindings.runtime for cudaGraphGetNodes/cudaGraphNodeGetToolsId. Gracefully no-ops when cuda.bindings is unavailable. - torch/cuda/_annotate_cuda_graph_trace.py: Post-processing script that merges annotations into profiler trace JSON. Handles stream reassignment, overlapping timestamp fixes, ac2g flow event tracking, and noise event removal. - test/test_cuda_graph_annotations.py: 23 tests covering annotation capture, nested/same-range scope merging, remap, and trace post-processing. Authored with Claude. [ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/179768
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ✅ No FailuresAs of commit f93472d with merge base a4a69be ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
| return False | ||
|
|
||
|
|
||
| def _check_cuda(result: Any) -> Any: |
There was a problem hiding this comment.
can you move it somewhere to torch/cuda/utils because it can be reused for a lot of cuda-python calls, not just for annotations
| with mark_kernels(annotation): | ||
| yield | ||
| else: | ||
| if isinstance(annotation, dict): |
There was a problem hiding this comment.
I think you should also handle str annotation here by turning it into dict with annotation["str"] = annotation
| graph = torch.cuda.CUDAGraph() | ||
| x = torch.randn(8, device="cuda") | ||
|
|
||
| with torch.cuda.graph(graph): |
There was a problem hiding this comment.
maybe not for this PR, but it would be better to extend torch.cuda.graph context manager with enable_annotations kword that would also automatically call resolve_pending_annotations() before exiting. Alternatively, maybe we should allow pre- and post- callbacks for torch.cuda.graph context manager to allow people more customization. In this case it might still make sense to have explicit enable_annotations arg that would be a shortcut to registering corresponding callbacks.
Note, the context manager should not unconditionally clear kernel annotations, because you should be able to annotate several graphs in the same workload
There was a problem hiding this comment.
good point. Sure, I can do it as a follow up PR.
There was a problem hiding this comment.
…traces"
**This works in eager code only for now, because dynamo doesn't preserve the `mark_kernels()` context manager **
### Summary
Adds infrastructure to annotate individual kernels within CUDA graph captures so their metadata (e.g., collective op name, process group, message sizes) appears in perfetto/chrome profiler traces.
This is a port of the internal implementation (D95237028, D96410655) to OSS PyTorch.
**Three components:**
- **`torch/cuda/_graph_annotations.py`** — Core annotation module. Provides `mark_kernels()` context manager that tracks which graph nodes are added during capture using `cudaGraphGetNodes` and `cudaGraphNodeGetToolsId`. Includes `mark_stream()` for stream-aware annotations, nested scope merging (inner wins common keys), and `remap_to_exec_graph()` to fix up graph IDs post-instantiation. Gracefully no-ops when `cuda.bindings` is unavailable.
- **`torch/_inductor/cudagraph_trees.py`** — Integration into `CUDAGraphNode._record()`. Gated behind `config.triton.cudagraph_kernel_annotations` (default `False`). Calls `clear_kernel_annotations()` before capture, `resolve_pending_annotations()` inside the capture context, and `remap_to_exec_graph()` after capture ends.
- **`torch/cuda/_annotate_cuda_graph_trace.py`** — Post-processing script. Reads a profiler trace JSON and an annotations pickle, matches kernel events by `graph node id`, merges annotation fields, reassigns streams, fixes overlapping timestamps from CUPTI, and cleans up noise events. Runnable as `python -m torch.cuda._annotate_cuda_graph_trace`.
### Requirements
- `cuda-python` package (`pip install cuda-python`) for `cuda.bindings.runtime`
- `cuda-compat >= 13.1` on `LD_LIBRARY_PATH` (or driver >= 13.1) for `cudaGraphNodeGetToolsId`
### Example usage
#### 1. Annotating kernels during CUDA graph capture
```python
import torch
from torch.cuda._graph_annotations import (
enable_annotations,
mark_kernels,
resolve_pending_annotations,
remap_to_exec_graph,
clear_kernel_annotations,
get_kernel_annotations,
)
enable_annotations()
clear_kernel_annotations()
x = torch.randn(1024, device="cuda")
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
# Annotate a region with a string
with mark_kernels("forward_pass"):
y = x + 1
z = y * 2
# Annotate with a dict for richer metadata
with mark_kernels({"name": "all_gather", "Group size": 8, "dtype": "bfloat16"}):
w = z - 1
resolve_pending_annotations()
remap_to_exec_graph(graph)
# Save annotations for later trace post-processing
import pickle
with open("kernel_annotations.pkl", "wb") as f:
pickle.dump(dict(get_kernel_annotations()), f)
# Replay the graph
graph.replay()
```
#### 2. Annotating with stream awareness (for collectives)
```python
from torch.cuda._graph_annotations import mark_stream, get_stream_for_pg
# Get a unique stream ID for a process group
stream_id = get_stream_for_pg("default_pg")
# mark_stream switches to the stream, injects stream ID, and wraps mark_kernels
ag_stream = torch.cuda.Stream()
with mark_stream(ag_stream, {"name": "all_gather", "stream": stream_id}):
# collective ops here
pass
```
#### 3. Nested scopes (inner wins for common keys)
```python
with torch.cuda.graph(graph):
with mark_kernels({"name": "fsdp_ag", "stream": 71}):
# outer scope
with mark_kernels({"name": "all_gather", "stream": 62, "dtype": "bf16"}):
# inner scope — kernels here get name="all_gather", stream=62, dtype="bf16"
y = x + 1
# back to outer — kernels here get name="fsdp_ag", stream=71
z = y * 2
resolve_pending_annotations()
```
#### 4. Post-processing a profiler trace
```bash
# After collecting a profiler trace, merge annotations into it:
python -m torch.cuda._annotate_cuda_graph_trace \
traces/step_14/000000.pt.trace.json.gz \
-a kernel_annotations.pkl \
-o annotated_trace.json.gz
# Or auto-discover the annotations pickle from the trace directory:
python -m torch.cuda._annotate_cuda_graph_trace \
traces/step_14/000000.pt.trace.json.gz
```
#### 5. Enabling via inductor config (for torch.compile + cudagraph trees)
```python
import torch._inductor.config as config
config.triton.cudagraph_kernel_annotations = True
# Now any CUDA graph captured by the inductor will automatically
# call clear/resolve/remap around the capture. Users still need
# mark_kernels() in their model code to annotate specific regions.
```
#### 6. E2E Example adding annotation to perfetto trace:
```python
"""End-to-end example: capture a CUDA graph with annotations, profile it,
and post-process the trace so kernel events carry the annotation metadata.
Run with:
LD_LIBRARY_PATH=/home/shangdiy/.conda/envs/pytorch-3.12/cuda-compat:$LD_LIBRARY_PATH \
python agent_space/e2e_annotated_trace.py
"""
import json
import pickle
import tempfile
from pathlib import Path
import torch
from torch.cuda._graph_annotations import (
clear_kernel_annotations,
enable_annotations,
get_kernel_annotations,
mark_kernels,
remap_to_exec_graph,
resolve_pending_annotations,
)
from torch.cuda._annotate_cuda_graph_trace import annotate_trace
def main() -> None:
enable_annotations()
clear_kernel_annotations()
# --- 1. Capture a CUDA graph with annotated regions ---
x = torch.randn(256, device="cuda")
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
with mark_kernels({"name": "linear_fwd", "layer": "0"}):
y = x * 2 + 1
with mark_kernels({"name": "all_gather", "dtype": "float32", "Group size": 4}):
z = y + x
with mark_kernels("residual_add"):
out = z + y
resolve_pending_annotations()
remap_to_exec_graph(graph)
annotations = dict(get_kernel_annotations())
print(f"Captured {len(annotations)} annotated kernel(s)")
for tid, anns in annotations.items():
print(f" toolsId=0x{tid:016x}: {anns}")
# --- 2. Profile a graph replay ---
if True:
tmpdir = "agent_space"
trace_path = Path(tmpdir) / "trace.json"
ann_path = Path(tmpdir) / "annotations.pkl"
out_path = Path(tmpdir) / "trace.annotated.json"
# Save annotations pickle
with open(ann_path, "wb") as f:
pickle.dump(annotations, f)
# Profile the graph replay
with torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.CUDA,
],
) as prof:
for _ in range(3):
graph.replay()
torch.cuda.synchronize()
prof.export_chrome_trace(str(trace_path))
print(f"\nExported raw trace to {trace_path}")
# --- 3. Load trace and annotate ---
with open(trace_path) as f:
trace = json.load(f)
count = annotate_trace(trace, annotations)
print(f"Annotated {count} kernel event(s)")
# Save annotated trace
with open(out_path, "w") as f:
json.dump(trace, f)
print(f"\nSaved annotated trace to {out_path}")
if __name__ == "__main__":
main()
```
Result:
<img width="926" height="412" alt="Screenshot 2026-04-08 at 4 06 44 PM" src="https://github.com/user-attachments/assets/96f7799f-ea13-4487-8ed9-11ac24bfcdc3" />
### Files changed
| File | Change |
|------|--------|
| `torch/cuda/_graph_annotations.py` | New — core annotation module |
| `torch/cuda/_annotate_cuda_graph_trace.py` | New — trace post-processing script |
| `test/test_cuda_graph_annotations.py` | New — 13 tests |
### Test plan
```bash
# Install prerequisites
pip install cuda-python
conda install -c nvidia/label/cuda-13.1.0 cuda-compat
# Run tests
LD_LIBRARY_PATH=$CONDA_PREFIX/cuda-compat:$LD_LIBRARY_PATH \
python test/test_cuda_graph_annotations.py -v
```
Authored with Claude.
based on D95237028 , D96410655
[ghstack-poisoned]
…traces"
**This works in eager code only for now, because dynamo doesn't preserve the `mark_kernels()` context manager **
### Summary
Adds infrastructure to annotate individual kernels within CUDA graph captures so their metadata (e.g., collective op name, process group, message sizes) appears in perfetto/chrome profiler traces.
This is a port of the internal implementation (D95237028, D96410655) to OSS PyTorch.
**Three components:**
- **`torch/cuda/_graph_annotations.py`** — Core annotation module. Provides `mark_kernels()` context manager that tracks which graph nodes are added during capture using `cudaGraphGetNodes` and `cudaGraphNodeGetToolsId`. Includes `mark_stream()` for stream-aware annotations, nested scope merging (inner wins common keys), and `remap_to_exec_graph()` to fix up graph IDs post-instantiation. Gracefully no-ops when `cuda.bindings` is unavailable.
- **`torch/_inductor/cudagraph_trees.py`** — Integration into `CUDAGraphNode._record()`. Gated behind `config.triton.cudagraph_kernel_annotations` (default `False`). Calls `clear_kernel_annotations()` before capture, `resolve_pending_annotations()` inside the capture context, and `remap_to_exec_graph()` after capture ends.
- **`torch/cuda/_annotate_cuda_graph_trace.py`** — Post-processing script. Reads a profiler trace JSON and an annotations pickle, matches kernel events by `graph node id`, merges annotation fields, reassigns streams, fixes overlapping timestamps from CUPTI, and cleans up noise events. Runnable as `python -m torch.cuda._annotate_cuda_graph_trace`.
### Requirements
- `cuda-python` package (`pip install cuda-python`) for `cuda.bindings.runtime`
- `cuda-compat >= 13.1` on `LD_LIBRARY_PATH` (or driver >= 13.1) for `cudaGraphNodeGetToolsId`
### Example usage
#### 1. Annotating kernels during CUDA graph capture
```python
import torch
from torch.cuda._graph_annotations import (
enable_annotations,
mark_kernels,
resolve_pending_annotations,
remap_to_exec_graph,
clear_kernel_annotations,
get_kernel_annotations,
)
enable_annotations()
clear_kernel_annotations()
x = torch.randn(1024, device="cuda")
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
# Annotate a region with a string
with mark_kernels("forward_pass"):
y = x + 1
z = y * 2
# Annotate with a dict for richer metadata
with mark_kernels({"name": "all_gather", "Group size": 8, "dtype": "bfloat16"}):
w = z - 1
resolve_pending_annotations()
remap_to_exec_graph(graph)
# Save annotations for later trace post-processing
import pickle
with open("kernel_annotations.pkl", "wb") as f:
pickle.dump(dict(get_kernel_annotations()), f)
# Replay the graph
graph.replay()
```
#### 2. Annotating with stream awareness (for collectives)
```python
from torch.cuda._graph_annotations import mark_stream, get_stream_for_pg
# Get a unique stream ID for a process group
stream_id = get_stream_for_pg("default_pg")
# mark_stream switches to the stream, injects stream ID, and wraps mark_kernels
ag_stream = torch.cuda.Stream()
with mark_stream(ag_stream, {"name": "all_gather", "stream": stream_id}):
# collective ops here
pass
```
#### 3. Nested scopes (inner wins for common keys)
```python
with torch.cuda.graph(graph):
with mark_kernels({"name": "fsdp_ag", "stream": 71}):
# outer scope
with mark_kernels({"name": "all_gather", "stream": 62, "dtype": "bf16"}):
# inner scope — kernels here get name="all_gather", stream=62, dtype="bf16"
y = x + 1
# back to outer — kernels here get name="fsdp_ag", stream=71
z = y * 2
resolve_pending_annotations()
```
#### 4. Post-processing a profiler trace
```bash
# After collecting a profiler trace, merge annotations into it:
python -m torch.cuda._annotate_cuda_graph_trace \
traces/step_14/000000.pt.trace.json.gz \
-a kernel_annotations.pkl \
-o annotated_trace.json.gz
# Or auto-discover the annotations pickle from the trace directory:
python -m torch.cuda._annotate_cuda_graph_trace \
traces/step_14/000000.pt.trace.json.gz
```
#### 5. Enabling via inductor config (for torch.compile + cudagraph trees)
```python
import torch._inductor.config as config
config.triton.cudagraph_kernel_annotations = True
# Now any CUDA graph captured by the inductor will automatically
# call clear/resolve/remap around the capture. Users still need
# mark_kernels() in their model code to annotate specific regions.
```
#### 6. E2E Example adding annotation to perfetto trace:
```python
"""End-to-end example: capture a CUDA graph with annotations, profile it,
and post-process the trace so kernel events carry the annotation metadata.
Run with:
LD_LIBRARY_PATH=/home/shangdiy/.conda/envs/pytorch-3.12/cuda-compat:$LD_LIBRARY_PATH \
python agent_space/e2e_annotated_trace.py
"""
import json
import pickle
import tempfile
from pathlib import Path
import torch
from torch.cuda._graph_annotations import (
clear_kernel_annotations,
enable_annotations,
get_kernel_annotations,
mark_kernels,
remap_to_exec_graph,
resolve_pending_annotations,
)
from torch.cuda._annotate_cuda_graph_trace import annotate_trace
def main() -> None:
enable_annotations()
clear_kernel_annotations()
# --- 1. Capture a CUDA graph with annotated regions ---
x = torch.randn(256, device="cuda")
graph = torch.cuda.CUDAGraph()
with torch.cuda.graph(graph):
with mark_kernels({"name": "linear_fwd", "layer": "0"}):
y = x * 2 + 1
with mark_kernels({"name": "all_gather", "dtype": "float32", "Group size": 4}):
z = y + x
with mark_kernels("residual_add"):
out = z + y
resolve_pending_annotations()
remap_to_exec_graph(graph)
annotations = dict(get_kernel_annotations())
print(f"Captured {len(annotations)} annotated kernel(s)")
for tid, anns in annotations.items():
print(f" toolsId=0x{tid:016x}: {anns}")
# --- 2. Profile a graph replay ---
if True:
tmpdir = "agent_space"
trace_path = Path(tmpdir) / "trace.json"
ann_path = Path(tmpdir) / "annotations.pkl"
out_path = Path(tmpdir) / "trace.annotated.json"
# Save annotations pickle
with open(ann_path, "wb") as f:
pickle.dump(annotations, f)
# Profile the graph replay
with torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.CUDA,
],
) as prof:
for _ in range(3):
graph.replay()
torch.cuda.synchronize()
prof.export_chrome_trace(str(trace_path))
print(f"\nExported raw trace to {trace_path}")
# --- 3. Load trace and annotate ---
with open(trace_path) as f:
trace = json.load(f)
count = annotate_trace(trace, annotations)
print(f"Annotated {count} kernel event(s)")
# Save annotated trace
with open(out_path, "w") as f:
json.dump(trace, f)
print(f"\nSaved annotated trace to {out_path}")
if __name__ == "__main__":
main()
```
Result:
<img width="926" height="412" alt="Screenshot 2026-04-08 at 4 06 44 PM" src="https://github.com/user-attachments/assets/96f7799f-ea13-4487-8ed9-11ac24bfcdc3" />
### Files changed
| File | Change |
|------|--------|
| `torch/cuda/_graph_annotations.py` | New — core annotation module |
| `torch/cuda/_annotate_cuda_graph_trace.py` | New — trace post-processing script |
| `test/test_cuda_graph_annotations.py` | New — 13 tests |
### Test plan
```bash
# Install prerequisites
pip install cuda-python
conda install -c nvidia/label/cuda-13.1.0 cuda-compat
# Run tests
LD_LIBRARY_PATH=$CONDA_PREFIX/cuda-compat:$LD_LIBRARY_PATH \
python test/test_cuda_graph_annotations.py -v
```
Authored with Claude.
based on D95237028 , D96410655
[ghstack-poisoned]
|
@pytorchbot merge |
Merge startedYour 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 |
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: #179867 Approved by: https://github.com/ngimel ghstack dependencies: #179768
…orch#179768) **This works in eager code only for now, because dynamo doesn't preserve the `mark_kernels()` context manager ** ### Summary Adds infrastructure to annotate individual kernels within CUDA graph captures so their metadata (e.g., collective op name, process group, message sizes) appears in perfetto/chrome profiler traces. This is a port of the internal implementation (D95237028, D96410655) to OSS PyTorch. **Three components:** - **`torch/cuda/_graph_annotations.py`** — Core annotation module. Provides `mark_kernels()` context manager that tracks which graph nodes are added during capture using `cudaGraphGetNodes` and `cudaGraphNodeGetToolsId`. Includes `mark_stream()` for stream-aware annotations, nested scope merging (inner wins common keys), and `remap_to_exec_graph()` to fix up graph IDs post-instantiation. Gracefully no-ops when `cuda.bindings` is unavailable. - **`torch/_inductor/cudagraph_trees.py`** — Integration into `CUDAGraphNode._record()`. Gated behind `config.triton.cudagraph_kernel_annotations` (default `False`). Calls `clear_kernel_annotations()` before capture, `resolve_pending_annotations()` inside the capture context, and `remap_to_exec_graph()` after capture ends. - **`torch/cuda/_annotate_cuda_graph_trace.py`** — Post-processing script. Reads a profiler trace JSON and an annotations pickle, matches kernel events by `graph node id`, merges annotation fields, reassigns streams, fixes overlapping timestamps from CUPTI, and cleans up noise events. Runnable as `python -m torch.cuda._annotate_cuda_graph_trace`. ### Requirements - `cuda-python` package (`pip install cuda-python`) for `cuda.bindings.runtime` - `cuda-compat >= 13.1` on `LD_LIBRARY_PATH` (or driver >= 13.1) for `cudaGraphNodeGetToolsId` ### Example usage #### 1. Annotating kernels during CUDA graph capture ```python import torch from torch.cuda._graph_annotations import ( enable_annotations, mark_kernels, resolve_pending_annotations, remap_to_exec_graph, clear_kernel_annotations, get_kernel_annotations, ) enable_annotations() clear_kernel_annotations() x = torch.randn(1024, device="cuda") graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): # Annotate a region with a string with mark_kernels("forward_pass"): y = x + 1 z = y * 2 # Annotate with a dict for richer metadata with mark_kernels({"name": "all_gather", "Group size": 8, "dtype": "bfloat16"}): w = z - 1 resolve_pending_annotations() remap_to_exec_graph(graph) # Save annotations for later trace post-processing import pickle with open("kernel_annotations.pkl", "wb") as f: pickle.dump(dict(get_kernel_annotations()), f) # Replay the graph graph.replay() ``` #### 2. Annotating with stream awareness (for collectives) ```python from torch.cuda._graph_annotations import mark_stream, get_stream_for_pg # Get a unique stream ID for a process group stream_id = get_stream_for_pg("default_pg") # mark_stream switches to the stream, injects stream ID, and wraps mark_kernels ag_stream = torch.cuda.Stream() with mark_stream(ag_stream, {"name": "all_gather", "stream": stream_id}): # collective ops here pass ``` #### 3. Nested scopes (inner wins for common keys) ```python with torch.cuda.graph(graph): with mark_kernels({"name": "fsdp_ag", "stream": 71}): # outer scope with mark_kernels({"name": "all_gather", "stream": 62, "dtype": "bf16"}): # inner scope — kernels here get name="all_gather", stream=62, dtype="bf16" y = x + 1 # back to outer — kernels here get name="fsdp_ag", stream=71 z = y * 2 resolve_pending_annotations() ``` #### 4. Post-processing a profiler trace ```bash # After collecting a profiler trace, merge annotations into it: python -m torch.cuda._annotate_cuda_graph_trace \ traces/step_14/000000.pt.trace.json.gz \ -a kernel_annotations.pkl \ -o annotated_trace.json.gz # Or auto-discover the annotations pickle from the trace directory: python -m torch.cuda._annotate_cuda_graph_trace \ traces/step_14/000000.pt.trace.json.gz ``` #### 5. Enabling via inductor config (for torch.compile + cudagraph trees) ```python import torch._inductor.config as config config.triton.cudagraph_kernel_annotations = True # Now any CUDA graph captured by the inductor will automatically # call clear/resolve/remap around the capture. Users still need # mark_kernels() in their model code to annotate specific regions. ``` #### 6. E2E Example adding annotation to perfetto trace: ```python """End-to-end example: capture a CUDA graph with annotations, profile it, and post-process the trace so kernel events carry the annotation metadata. Run with: LD_LIBRARY_PATH=/home/shangdiy/.conda/envs/pytorch-3.12/cuda-compat:$LD_LIBRARY_PATH \ python agent_space/e2e_annotated_trace.py """ import json import pickle import tempfile from pathlib import Path import torch from torch.cuda._graph_annotations import ( clear_kernel_annotations, enable_annotations, get_kernel_annotations, mark_kernels, remap_to_exec_graph, resolve_pending_annotations, ) from torch.cuda._annotate_cuda_graph_trace import annotate_trace def main() -> None: enable_annotations() clear_kernel_annotations() # --- 1. Capture a CUDA graph with annotated regions --- x = torch.randn(256, device="cuda") graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): with mark_kernels({"name": "linear_fwd", "layer": "0"}): y = x * 2 + 1 with mark_kernels({"name": "all_gather", "dtype": "float32", "Group size": 4}): z = y + x with mark_kernels("residual_add"): out = z + y resolve_pending_annotations() remap_to_exec_graph(graph) annotations = dict(get_kernel_annotations()) print(f"Captured {len(annotations)} annotated kernel(s)") for tid, anns in annotations.items(): print(f" toolsId=0x{tid:016x}: {anns}") # --- 2. Profile a graph replay --- if True: tmpdir = "agent_space" trace_path = Path(tmpdir) / "trace.json" ann_path = Path(tmpdir) / "annotations.pkl" out_path = Path(tmpdir) / "trace.annotated.json" # Save annotations pickle with open(ann_path, "wb") as f: pickle.dump(annotations, f) # Profile the graph replay with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ], ) as prof: for _ in range(3): graph.replay() torch.cuda.synchronize() prof.export_chrome_trace(str(trace_path)) print(f"\nExported raw trace to {trace_path}") # --- 3. Load trace and annotate --- with open(trace_path) as f: trace = json.load(f) count = annotate_trace(trace, annotations) print(f"Annotated {count} kernel event(s)") # Save annotated trace with open(out_path, "w") as f: json.dump(trace, f) print(f"\nSaved annotated trace to {out_path}") if __name__ == "__main__": main() ``` Result: <img width="926" height="412" alt="Screenshot 2026-04-08 at 4 06 44 PM" src="https://github.com/user-attachments/assets/96f7799f-ea13-4487-8ed9-11ac24bfcdc3" /> ### Files changed | File | Change | |------|--------| | `torch/cuda/_graph_annotations.py` | New — core annotation module | | `torch/cuda/_annotate_cuda_graph_trace.py` | New — trace post-processing script | | `test/test_cuda_graph_annotations.py` | New — 13 tests | ### Test plan ```bash # Install prerequisites pip install cuda-python conda install -c nvidia/label/cuda-13.1.0 cuda-compat # Run tests LD_LIBRARY_PATH=$CONDA_PREFIX/cuda-compat:$LD_LIBRARY_PATH \ python test/test_cuda_graph_annotations.py -v ``` Authored with Claude. based on D95237028 , D96410655 Pull Request resolved: pytorch#179768 Approved by: https://github.com/ngimel
…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
…orch#179768) **This works in eager code only for now, because dynamo doesn't preserve the `mark_kernels()` context manager ** ### Summary Adds infrastructure to annotate individual kernels within CUDA graph captures so their metadata (e.g., collective op name, process group, message sizes) appears in perfetto/chrome profiler traces. This is a port of the internal implementation (D95237028, D96410655) to OSS PyTorch. **Three components:** - **`torch/cuda/_graph_annotations.py`** — Core annotation module. Provides `mark_kernels()` context manager that tracks which graph nodes are added during capture using `cudaGraphGetNodes` and `cudaGraphNodeGetToolsId`. Includes `mark_stream()` for stream-aware annotations, nested scope merging (inner wins common keys), and `remap_to_exec_graph()` to fix up graph IDs post-instantiation. Gracefully no-ops when `cuda.bindings` is unavailable. - **`torch/_inductor/cudagraph_trees.py`** — Integration into `CUDAGraphNode._record()`. Gated behind `config.triton.cudagraph_kernel_annotations` (default `False`). Calls `clear_kernel_annotations()` before capture, `resolve_pending_annotations()` inside the capture context, and `remap_to_exec_graph()` after capture ends. - **`torch/cuda/_annotate_cuda_graph_trace.py`** — Post-processing script. Reads a profiler trace JSON and an annotations pickle, matches kernel events by `graph node id`, merges annotation fields, reassigns streams, fixes overlapping timestamps from CUPTI, and cleans up noise events. Runnable as `python -m torch.cuda._annotate_cuda_graph_trace`. ### Requirements - `cuda-python` package (`pip install cuda-python`) for `cuda.bindings.runtime` - `cuda-compat >= 13.1` on `LD_LIBRARY_PATH` (or driver >= 13.1) for `cudaGraphNodeGetToolsId` ### Example usage #### 1. Annotating kernels during CUDA graph capture ```python import torch from torch.cuda._graph_annotations import ( enable_annotations, mark_kernels, resolve_pending_annotations, remap_to_exec_graph, clear_kernel_annotations, get_kernel_annotations, ) enable_annotations() clear_kernel_annotations() x = torch.randn(1024, device="cuda") graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): # Annotate a region with a string with mark_kernels("forward_pass"): y = x + 1 z = y * 2 # Annotate with a dict for richer metadata with mark_kernels({"name": "all_gather", "Group size": 8, "dtype": "bfloat16"}): w = z - 1 resolve_pending_annotations() remap_to_exec_graph(graph) # Save annotations for later trace post-processing import pickle with open("kernel_annotations.pkl", "wb") as f: pickle.dump(dict(get_kernel_annotations()), f) # Replay the graph graph.replay() ``` #### 2. Annotating with stream awareness (for collectives) ```python from torch.cuda._graph_annotations import mark_stream, get_stream_for_pg # Get a unique stream ID for a process group stream_id = get_stream_for_pg("default_pg") # mark_stream switches to the stream, injects stream ID, and wraps mark_kernels ag_stream = torch.cuda.Stream() with mark_stream(ag_stream, {"name": "all_gather", "stream": stream_id}): # collective ops here pass ``` #### 3. Nested scopes (inner wins for common keys) ```python with torch.cuda.graph(graph): with mark_kernels({"name": "fsdp_ag", "stream": 71}): # outer scope with mark_kernels({"name": "all_gather", "stream": 62, "dtype": "bf16"}): # inner scope — kernels here get name="all_gather", stream=62, dtype="bf16" y = x + 1 # back to outer — kernels here get name="fsdp_ag", stream=71 z = y * 2 resolve_pending_annotations() ``` #### 4. Post-processing a profiler trace ```bash # After collecting a profiler trace, merge annotations into it: python -m torch.cuda._annotate_cuda_graph_trace \ traces/step_14/000000.pt.trace.json.gz \ -a kernel_annotations.pkl \ -o annotated_trace.json.gz # Or auto-discover the annotations pickle from the trace directory: python -m torch.cuda._annotate_cuda_graph_trace \ traces/step_14/000000.pt.trace.json.gz ``` #### 5. Enabling via inductor config (for torch.compile + cudagraph trees) ```python import torch._inductor.config as config config.triton.cudagraph_kernel_annotations = True # Now any CUDA graph captured by the inductor will automatically # call clear/resolve/remap around the capture. Users still need # mark_kernels() in their model code to annotate specific regions. ``` #### 6. E2E Example adding annotation to perfetto trace: ```python """End-to-end example: capture a CUDA graph with annotations, profile it, and post-process the trace so kernel events carry the annotation metadata. Run with: LD_LIBRARY_PATH=/home/shangdiy/.conda/envs/pytorch-3.12/cuda-compat:$LD_LIBRARY_PATH \ python agent_space/e2e_annotated_trace.py """ import json import pickle import tempfile from pathlib import Path import torch from torch.cuda._graph_annotations import ( clear_kernel_annotations, enable_annotations, get_kernel_annotations, mark_kernels, remap_to_exec_graph, resolve_pending_annotations, ) from torch.cuda._annotate_cuda_graph_trace import annotate_trace def main() -> None: enable_annotations() clear_kernel_annotations() # --- 1. Capture a CUDA graph with annotated regions --- x = torch.randn(256, device="cuda") graph = torch.cuda.CUDAGraph() with torch.cuda.graph(graph): with mark_kernels({"name": "linear_fwd", "layer": "0"}): y = x * 2 + 1 with mark_kernels({"name": "all_gather", "dtype": "float32", "Group size": 4}): z = y + x with mark_kernels("residual_add"): out = z + y resolve_pending_annotations() remap_to_exec_graph(graph) annotations = dict(get_kernel_annotations()) print(f"Captured {len(annotations)} annotated kernel(s)") for tid, anns in annotations.items(): print(f" toolsId=0x{tid:016x}: {anns}") # --- 2. Profile a graph replay --- if True: tmpdir = "agent_space" trace_path = Path(tmpdir) / "trace.json" ann_path = Path(tmpdir) / "annotations.pkl" out_path = Path(tmpdir) / "trace.annotated.json" # Save annotations pickle with open(ann_path, "wb") as f: pickle.dump(annotations, f) # Profile the graph replay with torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ], ) as prof: for _ in range(3): graph.replay() torch.cuda.synchronize() prof.export_chrome_trace(str(trace_path)) print(f"\nExported raw trace to {trace_path}") # --- 3. Load trace and annotate --- with open(trace_path) as f: trace = json.load(f) count = annotate_trace(trace, annotations) print(f"Annotated {count} kernel event(s)") # Save annotated trace with open(out_path, "w") as f: json.dump(trace, f) print(f"\nSaved annotated trace to {out_path}") if __name__ == "__main__": main() ``` Result: <img width="926" height="412" alt="Screenshot 2026-04-08 at 4 06 44 PM" src="https://github.com/user-attachments/assets/96f7799f-ea13-4487-8ed9-11ac24bfcdc3" /> ### Files changed | File | Change | |------|--------| | `torch/cuda/_graph_annotations.py` | New — core annotation module | | `torch/cuda/_annotate_cuda_graph_trace.py` | New — trace post-processing script | | `test/test_cuda_graph_annotations.py` | New — 13 tests | ### Test plan ```bash # Install prerequisites pip install cuda-python conda install -c nvidia/label/cuda-13.1.0 cuda-compat # Run tests LD_LIBRARY_PATH=$CONDA_PREFIX/cuda-compat:$LD_LIBRARY_PATH \ python test/test_cuda_graph_annotations.py -v ``` Authored with Claude. based on D95237028 , D96410655 Pull Request resolved: pytorch#179768 Approved by: https://github.com/ngimel
…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
Stack from ghstack (oldest at bottom):
**This works in eager code only for now, because dynamo doesn't preserve the
mark_kernels()context manager **Summary
Adds infrastructure to annotate individual kernels within CUDA graph captures so their metadata (e.g., collective op name, process group, message sizes) appears in perfetto/chrome profiler traces.
This is a port of the internal implementation (D95237028, D96410655) to OSS PyTorch.
Three components:
torch/cuda/_graph_annotations.py— Core annotation module. Providesmark_kernels()context manager that tracks which graph nodes are added during capture usingcudaGraphGetNodesandcudaGraphNodeGetToolsId. Includesmark_stream()for stream-aware annotations, nested scope merging (inner wins common keys), andremap_to_exec_graph()to fix up graph IDs post-instantiation. Gracefully no-ops whencuda.bindingsis unavailable.torch/_inductor/cudagraph_trees.py— Integration intoCUDAGraphNode._record(). Gated behindconfig.triton.cudagraph_kernel_annotations(defaultFalse). Callsclear_kernel_annotations()before capture,resolve_pending_annotations()inside the capture context, andremap_to_exec_graph()after capture ends.torch/cuda/_annotate_cuda_graph_trace.py— Post-processing script. Reads a profiler trace JSON and an annotations pickle, matches kernel events bygraph node id, merges annotation fields, reassigns streams, fixes overlapping timestamps from CUPTI, and cleans up noise events. Runnable aspython -m torch.cuda._annotate_cuda_graph_trace.Requirements
cuda-pythonpackage (pip install cuda-python) forcuda.bindings.runtimecuda-compat >= 13.1onLD_LIBRARY_PATH(or driver >= 13.1) forcudaGraphNodeGetToolsIdExample usage
1. Annotating kernels during CUDA graph capture
2. Annotating with stream awareness (for collectives)
3. Nested scopes (inner wins for common keys)
4. Post-processing a profiler trace
5. Enabling via inductor config (for torch.compile + cudagraph trees)
6. E2E Example adding annotation to perfetto trace:
Result:
Files changed
torch/cuda/_graph_annotations.pytorch/cuda/_annotate_cuda_graph_trace.pytest/test_cuda_graph_annotations.pyTest plan
Authored with Claude.
based on D95237028 , D96410655