Skip to content

[cuda graphs] Add kernel annotation module for CUDA graph traces - #179768

Closed
yushangdi wants to merge 3 commits into
gh/yushangdi/24/basefrom
gh/yushangdi/24/head
Closed

yushangdi wants to merge 3 commits into
gh/yushangdi/24/basefrom
gh/yushangdi/24/head

Conversation

@yushangdi

@yushangdi yushangdi commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

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. 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

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)

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)

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

# 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)

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:

"""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:

Screenshot 2026-04-08 at 4 06 44 PM

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

# 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

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]
@pytorch-bot

pytorch-bot Bot commented Apr 8, 2026 •

Copy link
Copy Markdown

🔗 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 SEVs

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

✅ No Failures

As of commit f93472d 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 8, 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.

Comment thread torch/cuda/_graph_annotations.py Outdated
return False


def _check_cuda(result: Any) -> Any:

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

sure, moved

with mark_kernels(annotation):
yield
else:
if isinstance(annotation, dict):

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.

I think you should also handle str annotation here by turning it into dict with annotation["str"] = annotation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

added now

graph = torch.cuda.CUDAGraph()
x = torch.randn(8, device="cuda")

with torch.cuda.graph(graph):

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

good point. Sure, I can do it as a follow up PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

…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]
@yushangdi

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 10, 2026
@yushangdi yushangdi added the topic: not user facing topic category label Apr 10, 2026
@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

pytorchmergebot pushed a commit that referenced this pull request Apr 13, 2026
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
@github-actions
github-actions Bot deleted the gh/yushangdi/24/head branch May 11, 2026 02:26
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…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
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
…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
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 topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants