Skip to content

Bake CUDA graph annotations into the chrome trace, retiring the offline joiner - #194854

Closed
ngimel wants to merge 7 commits into
gh/ngimel/14/basefrom
gh/ngimel/14/head
Closed

ngimel wants to merge 7 commits into
gh/ngimel/14/basefrom
gh/ngimel/14/head

Conversation

@ngimel

@ngimel ngimel commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Human note:
inline graph annotations in python trace exporter
Use it like prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())

Inline graph annotations in python trace exporter. Annotations
recorded by mark_kernels are injected during the single streaming write pass that
already happens, so exporting an annotated trace is one pass rather than write,
read back, splice, rewrite -- which would pay the dominant gzip cost twice. With
that in place torch.cuda._annotate_cuda_graph_trace, the offline script that did
the splice from a pickle side-file, is deleted along with its tests.

prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())

Passing annotation arg implies
use_python_export, since that is the export path able to inject; the C++ path is
untouched otherwise, and the cupti_monitor backend ignores them (it injects
through its own resolver).

A graphed work event whose graph node id has an annotation gets the annotation's
fields in its args and moves to the lane the annotation names; graphed work
without one moves to default_stream, since CUPTI reports a replay on whatever
hardware streams the graph executor picked -- often hundreds. The hardware stream
is kept as original_stream, and a top-level cudaGraphInlineAnnotated flag lets a
consumer tell an already annotated trace from one that still needs the join.

Also brings over three parity fixes: the deviceProperties,
the CUDA version keys from logGpuVersions (runtime version from torch), and
CPU instant events, which were being written as complete events and rendering as
bars.

Test Plan:

LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations TestMetadataJsonFormat
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py

15 and 112 tests pass. TestChromeTraceInlineAnnotations drives the new branches
through stub activities (annotated lane, default lane, non-graphed work left alone,
orphaned gpu_user_annotation slices dropped, no-annotations no-op); the parity test
compares the envelope against kineto's own save(); and an end-to-end test captures
an annotated graph, replays it under the profiler and checks the annotation reached
the kernel events. The end-to-end test lives in the profiler suite rather than
test_cuda_graph_utils because that module holds a CUPTI subscription from import
time, which starves kineto of GPU records.

Authored with assistance from Claude Code.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit e1df7cb with merge base 460948b (image):
💚 Looks good so far! There are no failures yet. 💚

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

[ghstack-poisoned]
ngimel added a commit that referenced this pull request Aug 26, 2026
…ne joiner

Ports farm's copy of the Python chrome-trace exporter back upstream. Annotations
recorded by mark_kernels are injected during the single streaming write pass that
already happens, so exporting an annotated trace is one pass rather than write,
read back, splice, rewrite -- which would pay the dominant gzip cost twice. With
that in place torch.cuda._annotate_cuda_graph_trace, the offline script that did
the splice from a pickle side-file, is deleted along with its tests.

    prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())

The annotations are passed in rather than picked up from the global registry
behind a boolean, so callers can filter or edit them first, or supply a set
unpickled from an earlier run -- get_kernel_annotations() hands out a read-only
view, so a boolean would have made those impossible. Passing them implies
use_python_export, since that is the export path able to inject; the C++ path is
untouched otherwise, and the cupti_monitor backend ignores them (it injects
through its own resolver).

A graphed work event whose graph node id has an annotation gets the annotation's
fields in its args and moves to the lane the annotation names; graphed work
without one moves to default_stream, since CUPTI reports a replay on whatever
hardware streams the graph executor picked -- often hundreds. The hardware stream
is kept as original_stream, and a top-level cudaGraphInlineAnnotated flag lets a
consumer tell an already annotated trace from one that still needs the join.

Also brings over three envelope-parity fixes the farm copy carries, all of which
matter more now that this exporter is the annotated path: the deviceProperties
kineto writes (all of them but regsPerBlock, which torch does not expose),
the CUDA version keys from logGpuVersions (runtime version from torch, whose CUDART
is the one kineto asks -- cuda.bindings would report its own, which differs), and
CPU instant events, which were being written as complete events and rendering as
bars.

Review the exporter first (parity fixes, then the annotation pass), then the
argument's two call sites, then the deletions.

Not ported from farm: its mfile/orjson dependencies, and its lane-label key
convention is kept as-is ("Process Group Description") so farm's recorded
annotations keep naming their lanes.

Test Plan:

```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations TestMetadataJsonFormat
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```

15 and 112 tests pass. TestChromeTraceInlineAnnotations drives the new branches
through stub activities (annotated lane, default lane, non-graphed work left alone,
orphaned gpu_user_annotation slices dropped, no-annotations no-op); the parity test
compares the envelope against kineto's own save(); and an end-to-end test captures
an annotated graph, replays it under the profiler and checks the annotation reached
the kernel events. The end-to-end test lives in the profiler suite rather than
test_cuda_graph_utils because that module holds a CUPTI subscription from import
time, which starves kineto of GPU records.

Authored with assistance from Claude Code.

ghstack-source-id: fbb7b34
Pull-Request: #194854
@ngimel ngimel added the release notes: cuda release notes category label Aug 26, 2026
metadata=None,
use_python_export=False,
cuda_graph_annotations=None,
default_stream=7,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

OOC where does 7 come from?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

No idea, but that's what default stream has been in the profiles forever

Comment thread torch/profiler/_chrome_trace_export.py Outdated
"sharedMemPerBlock": p.shared_memory_per_block, # pyrefly: ignore[missing-attribute]
"numSms": p.multi_processor_count,
"regsPerMultiprocessor": p.regs_per_multiprocessor, # pyrefly: ignore[missing-attribute]
"sharedMemPerBlockOptin": p.shared_memory_per_block_optin, # pyrefly: ignore[missing-attribute]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI-assisted review note:

shared_memory_per_block_optin is excluded from the device-properties binding under USE_ROCM, so use_python_export=True will raise AttributeError on ROCm here. Could we omit sharedMemPerBlockOptin when the property is unavailable (and add a ROCm-safe test)?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I suspect ROCm will error out much earlier - no annotations available on ROCm, cuda-bindings not available on ROCm

Comment thread torch/profiler/_chrome_trace_export.py Outdated
chunks: list[str] = []
for ann in annotation if isinstance(annotation, list) else [annotation]:
if not isinstance(ann, dict):
chunks.append(f'"annotation": {_json_escape(str(ann))}')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

not sure if we care about compat

AI-assisted review note:

The deleted annotator normalized legacy bare strings and {"str": "phase"} entries into the canonical name field. This path now emits annotation or str instead, and the old compatibility tests are removed. Could we preserve that normalization here and retain those regression cases?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

str annotation is now normalized into {"name":value}

"""
activities = kineto_results.trace_activities()
base_ns = _trimester_base_ns()
annotations = annotations or {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

subtle not sure if matters

AI-assisted review note:

annotations = annotations or {} plus the later truthiness checks means cuda_graph_annotations={} does not run the graph-lane pass at all. The API says that when annotations are supplied, graphed work without a match moves to default_stream; an empty mapping should therefore collapse all graphed work, while None should remain a no-op. Could we keep an annotations is not None mode flag?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Resolved to have {} and None behave in the same way

Comment thread torch/profiler/_chrome_trace_export.py Outdated
reassigned[(did, out_tid)] = (ts, lane_name)
# args.stream has to follow the lane. The annotation supplies it
# when it names one; otherwise override kineto's hardware stream
# (last key wins). Either way the hardware stream would be lost

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

not sure if this is like the inner wins thign

AI-assisted review note:

metadata_json() already contains the hardware stream, and this appends another stream member to the same args object. Although some parsers use the last value, duplicate-key behavior is not interoperable and another consumer may retain the original stream. Could we replace the existing field rather than emitting both, while still preserving it as original_stream?

Comment thread torch/profiler/_chrome_trace_export.py Resolved
[ghstack-poisoned]
ngimel added a commit that referenced this pull request Aug 28, 2026
…ne joiner

Ports farm's copy of the Python chrome-trace exporter back upstream. Annotations
recorded by mark_kernels are injected during the single streaming write pass that
already happens, so exporting an annotated trace is one pass rather than write,
read back, splice, rewrite -- which would pay the dominant gzip cost twice. With
that in place torch.cuda._annotate_cuda_graph_trace, the offline script that did
the splice from a pickle side-file, is deleted along with its tests.

    prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())

The annotations are passed in rather than picked up from the global registry
behind a boolean, so callers can filter or edit them first, or supply a set
unpickled from an earlier run -- get_kernel_annotations() hands out a read-only
view, so a boolean would have made those impossible. Passing them implies
use_python_export, since that is the export path able to inject; the C++ path is
untouched otherwise, and the cupti_monitor backend ignores them (it injects
through its own resolver).

A graphed work event whose graph node id has an annotation gets the annotation's
fields in its args. Whether it also moves onto a display lane is graph_lanes: "none"
by default, leaving the trace's stream layout alone, and "all" to move each graphed
event to the lane its annotation names (what mark_stream records) with the rest onto
default_stream. Collapsing that way is what a replay smeared over the hundreds of
hardware streams the graph executor picked needs, but it is the wrong thing to do to
someone who marked regions and not streams, whose profile would pile onto one lane --
so it is opt-in. A moved event keeps the stream it ran on as original_stream, and a
top-level cudaGraphInlineAnnotated flag lets a consumer tell an already annotated
trace from one that still needs the join.

Also brings over three envelope-parity fixes the farm copy carries, all of which
matter more now that this exporter is the annotated path: the deviceProperties
kineto writes (all of them but regsPerBlock, which torch does not expose),
the CUDA version keys from logGpuVersions (runtime version from torch, whose CUDART
is the one kineto asks -- cuda.bindings would report its own, which differs), and
CPU instant events, which were being written as complete events and rendering as
bars.

Review the exporter first (parity fixes, then the annotation pass), then the
argument's two call sites, then the deletions.

Not ported from farm: its mfile/orjson dependencies, and its lane-label key
convention is kept as-is ("Process Group Description") so farm's recorded
annotations keep naming their lanes.

Review feedback folded in: the lane rewrites the metadata fragment's own "stream"
rather than emitting a second one, bare-string annotations read back as "name" the way
the retired script normalized them, and sharedMemPerBlockOptin is skipped where torch
does not bind it (ROCm). An empty mapping reads the same as None -- nothing to inject,
so no lane pass and no reason to leave the C++ exporter.

Test Plan:

```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations TestMetadataJsonFormat
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```

20 and 113 tests pass. TestChromeTraceInlineAnnotations drives the new branches
through stub activities (both graph_lanes modes, non-graphed work left alone,
orphaned gpu_user_annotation slices dropped, no-annotations no-op); the parity test
compares the envelope against kineto's own save(); and an end-to-end test captures
an annotated graph, replays it under the profiler and checks the annotation reached
the kernel events. The end-to-end test lives in the profiler suite rather than
test_cuda_graph_utils because that module holds a CUPTI subscription from import
time, which starves kineto of GPU records.

Authored with assistance from Claude Code.

ghstack-source-id: 7514daf
Pull-Request: #194854
[ghstack-poisoned]
ngimel added a commit that referenced this pull request Aug 30, 2026
…ne joiner

Ports farm's copy of the Python chrome-trace exporter back upstream. Annotations
recorded by mark_kernels are injected during the single streaming write pass that
already happens, so exporting an annotated trace is one pass rather than write,
read back, splice, rewrite -- which would pay the dominant gzip cost twice. With
that in place torch.cuda._annotate_cuda_graph_trace, the offline script that did
the splice from a pickle side-file, is deleted along with its tests.

    prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())

The annotations are passed in rather than picked up from the global registry
behind a boolean, so callers can filter or edit them first, or supply a set
unpickled from an earlier run -- get_kernel_annotations() hands out a read-only
view, so a boolean would have made those impossible. Passing them implies
use_python_export, since that is the export path able to inject; the C++ path is
untouched otherwise, and the cupti_monitor backend ignores them (it injects
through its own resolver).

A graphed work event whose graph node id has an annotation gets the annotation's
fields in its args. Whether it also moves onto a display lane is graph_lanes: "none"
by default, leaving the trace's stream layout alone, and "all" to move each graphed
event to the lane its annotation names (what mark_stream records) with the rest onto
default_stream. Collapsing that way is what a replay smeared over the hundreds of
hardware streams the graph executor picked needs, but it is the wrong thing to do to
someone who marked regions and not streams, whose profile would pile onto one lane --
so it is opt-in. A moved event keeps the stream it ran on as original_stream, and a
top-level cudaGraphInlineAnnotated flag lets a consumer tell an already annotated
trace from one that still needs the join.

Also brings over three envelope-parity fixes the farm copy carries, all of which
matter more now that this exporter is the annotated path: the deviceProperties
kineto writes (all of them but regsPerBlock, which torch does not expose),
the CUDA version keys from logGpuVersions (runtime version from torch, whose CUDART
is the one kineto asks -- cuda.bindings would report its own, which differs), and
CPU instant events, which were being written as complete events and rendering as
bars.

Review the exporter first (parity fixes, then the annotation pass), then the
argument's two call sites, then the deletions.

Not ported from farm: its mfile/orjson dependencies, and its lane-label key
convention is kept as-is ("Process Group Description") so farm's recorded
annotations keep naming their lanes.

Review feedback folded in: the lane rewrites the metadata fragment's own "stream"
rather than emitting a second one, bare-string annotations read back as "name" the way
the retired script normalized them, and sharedMemPerBlockOptin is skipped where torch
does not bind it (ROCm). An empty mapping reads the same as None -- nothing to inject,
so no lane pass and no reason to leave the C++ exporter.

Test Plan:

```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations TestMetadataJsonFormat
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```

20 and 113 tests pass. TestChromeTraceInlineAnnotations drives the new branches
through stub activities (both graph_lanes modes, non-graphed work left alone,
orphaned gpu_user_annotation slices dropped, no-annotations no-op); the parity test
compares the envelope against kineto's own save(); and an end-to-end test captures
an annotated graph, replays it under the profiler and checks the annotation reached
the kernel events. The end-to-end test lives in the profiler suite rather than
test_cuda_graph_utils because that module holds a CUPTI subscription from import
time, which starves kineto of GPU records.

Authored with assistance from Claude Code.

ghstack-source-id: e21a875
Pull-Request: #194854
@ngimel

ngimel commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator Author

@claude check if review comments were addressed

@claude

claude Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Claude finished @ngimel's task in 7m 35s —— View job


Review-comment status

All six of @drisspg's threads are either fixed in code (commits 7b071357, 3ced0236) or answered in-thread; the one thing I could not find addressed is the legacy {"str": ...} → name normalization, plus the PR description is now stale about deviceProperties.

Thread-by-thread detail

1. torch/autograd/profiler.py:555 — "where does 7 come from?" — Answered in thread ("that's what default stream has been in the profiles forever"). No code change expected. Note that after graph_lanes was added, default_stream is only consulted when graph_lanes="all" (_chrome_trace_export.py:365-366), so the constant is now much less load-bearing.

2. ROCm sharedMemPerBlockOptin AttributeError — ✅ fixed. _chrome_trace_export.py:156-160 now guards with hasattr, and the docstring at 136-137 explains why. Verified the binding really is #ifndef USE_ROCM (torch/csrc/cuda/Module.cpp:1180-1185), so the guard is the right shape.
The requested ROCm-safe test was not added. TestPythonChromeTraceExport is gated only on kineto_available() + torch.cuda.is_available() (test_profiler.py:4457-4459), which is true on ROCm, so test_python_export_envelope_matches_kineto (4588) will run there and does an exact dict compare minus only regsPerBlock. If ROCm kineto's createDevicePropertiesJson emits a different field set, that assert goes red on ROCm rather than skipping. Worth either a ROCm skip or comparing only the intersection.

3. Legacy annotation normalization — ⚠️ half addressed. Bare strings now render as "name" (_chrome_trace_export.py:179), documented at 170-172, and covered by test_bare_string_annotation_reads_as_name (test_profiler.py:4885). But the old {"str": "phase"} → name mapping from the deleted annotator (args["name" if key == "str" else key]) has no equivalent here — such a pickle now emits args["str"], and the deleted test_legacy_str_key_maps_to_name was not re-homed. Given the docstring explicitly claims "annotations pickled by an older recorder still read as a name," that's an inconsistency, not just a dropped nicety. Fix this →

4. annotations={} vs None — ✅ resolved as answered. annotate_graphs = bool(annotations) with the rationale comment (_chrome_trace_export.py:233-236), documented in both docstrings, and pinned by test_empty_annotations_leave_events_alone (4857). The larger answer to this thread is the new graph_lanes knob: lane movement is now opt-in ("none" default), so the ambiguity about what "supplied annotations" implies is gone.

5. Duplicate stream key in args — ✅ fixed. _STREAM_RE.subn(..., count=1) rewrites kineto's own "stream" in the metadata fragment instead of appending a second, with an append-only fallback when the fragment has none (_chrome_trace_export.py:372-377), and original_stream is preserved. test_args_carry_one_stream_key (4826) parses with an object_pairs_hook that rejects duplicate keys, which is the right way to pin this.

6. Perfetto overlap / collision handling — ✅ answered + design change. Answered in thread (Perfetto no longer drops overlapping events). Additionally the graph_lanes="none" default means the collapse the objection was about no longer happens unless explicitly requested. Verified: with "none", out_tid stays rid, so no lane metadata and no original_stream are emitted (test_annotations_alone_move_nothing, 4868).

Residual nits I noticed while checking, all minor:

  • Stale PR description. It still says deviceProperties are "read through cuda.bindings, the only source exposing regsPerBlock" — 7b071357 dropped that path entirely in favor of torch.cuda.get_device_properties and now omits regsPerBlock. It also documents cuda_graph_annotations as moving work to lanes, which is now graph_lanes="all". Since this is a ghstack commit, the description needs a manual ghstack -u / edit.
  • graph_lanes="all" alone is a silent no-op. profiler.py:537 dispatches to the Python exporter only on use_python_export or cuda_graph_annotations, so export_chrome_trace(path, graph_lanes="all") goes down the C++ path and the argument (including its ValueError validation) is never seen. And even inside the exporter, graph_lanes="all" with annotations=None moves nothing, because node_id is only computed when annotate_graphs is true — reasonable, but the docstring's "graphed events are moved... and the rest onto default_stream" reads as if it works standalone.
  • A recorded stream is dropped in "none" mode. _annotation_args strips stream out of norm unconditionally (:185-186), so under the default the annotation's recorded stream appears nowhere in args. Documented ("a recorded stream is ignored"), just noting the information is discarded rather than kept under another key.

I did not run tests or lint (no built PyTorch/CUDA in this checkout); the checks above are from reading the code and diffing f52e8995/7b071357/3ced0236 against the base.

· branch [`gh/ngimel/14/head`](https://github.com/pytorch/pytorch/tree/gh/ngimel/14/head)

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #195397

[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #195398

pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
…ic GC (#195397)

Human note:

fix refcycles in make_graphed_callables so that gc doesn't unexpectedly kick in during graph capture

Destroying a CUDAGraph runs cudaGraphDestroy / cudaGraphExecDestroy / releasePool
(aten/src/ATen/cuda/CUDAGraph.cpp:399-408), none of which are permitted while a stream is
capturing. Doing it mid-capture warns "operation not permitted when stream is capturing
(function reset)" and invalidates that capture, after which the next allocation trips
TORCH_INTERNAL_ASSERT(info.status != cudaStreamCaptureStatusInvalidated) in
CUDACachingAllocator. So *when* a CUDAGraph is freed matters, and make_graphed_callables
was handing that decision to the cyclic collector, which picks an arbitrary allocation
point -- including one inside an unrelated capture.

Two reference cycles put the graphs in the collector's hands. The autograd Function
subclass closed over fwd_graph/bwd_graph, and a class plus its methods' closure cells is
a cycle, so anything those methods captured could only be reclaimed by the GC. On the
nn.Module path the closure installed as func.forward also closed over func -- and over
func.forward, a bound method holding it -- so the module, and through it the graphs, was
cyclic as well. Fixing only one of the two leaves the graphs stranded via the other.

The graphs are now passed to Graphed.apply per call and stashed on ctx, so the class
holds none of them while ctx keeps bwd_graph alive for exactly as long as a backward can
still run. new_fwd holds the module weakly and rebinds its original forward per call.
One case still retains: a module whose forward was already an instance attribute rather
than a bound method has nothing to unbind, so that path keeps holding the module; it is
commented where it happens.

Worth calling out as a behaviour change: calling a graphed module's forward after the
module itself has been freed now raises instead of working by accident. Holding
module.forward while the module is alive is unaffected.

This also removes a workaround. TestMarkKernels in test_cuda_graph_utils.py had a
tearDown that did not chain to super().tearDown(), and restoring the chain made a later
capture in that class fail with exactly the assert above -- the base tearDown shifted
allocation timing enough for a collection to land inside a capture. With the cycles gone
the fixture folds into the ordinary setUp + addCleanup.

Test Plan:

```
python test/test_cuda.py -k make_graphed
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```

8 and 115 tests pass (make_graphed has 3 pre-existing expected failures).
test_graph_make_graphed_callables_freed_by_refcount is the regression test: it drops a
graphed callable with the cyclic GC disabled and asserts no CUDAGraph survives, for both
the nn.Module and plain-callable paths, and fails on the parent commit. The original
end-to-end symptom reproduces via agent_space/repro_gc_capture_invalidate.py, which
stops reproducing with this change.

Authored with assistance from Claude Code.
Pull Request resolved: #195397
Approved by: https://github.com/ezyang, https://github.com/eqy
ghstack dependencies: #194852, #194853, #194854
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
…_annotations workflow (#195398)

Three findings from integrating the annotation store into a large trainer.

A capture that completes a mark_kernels scope and then fails in capture_end leaked its
annotations for the life of the process. resolve_pending_annotations has to run before
capture_end, because the rekey inside instantiate() is what consumes what it writes, so
its entries land keyed by the capture graph's id and only instantiate() rewrites them to
an exec id. When capture_end raises there is no exec graph and no rewrite, and
remove_kernel_annotations (the graph-destroy path) matches on exec ids, so nothing could
reach them again. __exit__ now purges that capture's entries when capture_end raises.
The purge is scoped to capture_end alone rather than the whole try block -- once it
returns the capture is usable and its annotations are worth keeping -- and is guarded on
the graph not having been remapped already, since keep_graph=False instantiates inside
capture_end.

An earlier writeup of this suggested moving the resolve into capture_end, after the
capture-id stamp. That no longer applies, and the reason is what makes the simpler fix
work: the stamp now happens at capture_begin, so graph._capture_graph_id is already set
when capture_end fails and we know exactly which entries are ours to drop.

clear_kernel_annotations is deprecated rather than deleted. It has no caller in torch
outside tests, and its docstring recommended clearing "once recorded annotations have
been consumed (e.g. after saving them alongside a profiler trace)" -- the
pickle-alongside-trace flow that inline trace export retires. For a long-running trainer
that advice is actively harmful: graphs are captured once and replayed for the whole run,
so a global wipe discards annotations for graphs that are still live and still being
joined against, and growth is already bounded by the remap on instantiate plus
remove_kernel_annotations on destroy. The docstring separately claimed clearing "revokes
recording from every scope opened before the clear", which is not true -- only backward
brackets are versioned by the generation counter, so a forward scope open across a clear
registers on exit as usual. Both claims are corrected, the second now has a test, and
tests call a new private _reset_kernel_annotations for isolation so the suite does not
trip the warning; the one test that is about the public entry point asserts it.

Cleaning up those call sites also removed the redundant ones: nine tests opened with a
reset that their class fixture already does, and two registry-only classes reset in
tearDown alone, which is why each of their tests began with one -- those now use setUp
plus addCleanup. The resets kept are the ones that do work: between iterations of a
loop, or mid-test where the reset is the thing under test.

Finally, register_capture_end_hook documents that capture-end hooks are best-effort:
skipped entirely when cudaStreamEndCapture raises, and truncated when an earlier hook
raises. A consumer using one for teardown needs its own fallback on the error path.

Test Plan:

```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_cupti_node_timer.py
```

115, 16 and 8 tests pass. test_failed_capture_end_discards_annotations is the regression
test for the leak: reverting just the __exit__ change makes it fail. test_public_bindings
has one failure in this environment that predates the change and is unrelated
(torch.distributed.debug._debug_handlers needs the `tabulate` package).

Authored with assistance from Claude Code.
Pull Request resolved: #195398
Approved by: https://github.com/ezyang
ghstack dependencies: #194852, #194853, #194854, #195397
alexmsettle added a commit to alexmsettle/pytorch that referenced this pull request Sep 6, 2026
…ement

Upstream PR pytorch#194854 retired the offline joiner (_annotate_cuda_graph_trace)
and bakes annotations directly into Chrome traces via
prof.export_chrome_trace(path, cuda_graph_annotations=...).

- Remove test_save_annotations_and_join_trace (used the deleted module);
  replace with test_save_annotations_and_chrome_trace which verifies
  save_kernel_annotations persists the registry to disk as pickle.
- Fix _all_fqn_strings to also check "name" key (upstream mark_kernels
  now stores {"name": fqn} not {"str": fqn}).
- Accept deletion of torch/cuda/_annotate_cuda_graph_trace.py during
  rebase onto upstream/main.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ne joiner (pytorch#194854)

Human note:
inline graph annotations in python trace exporter
Use it like `prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())`

Inline graph annotations in python trace exporter. Annotations
recorded by mark_kernels are injected during the single streaming write pass that
already happens, so exporting an annotated trace is one pass rather than write,
read back, splice, rewrite -- which would pay the dominant gzip cost twice. With
that in place torch.cuda._annotate_cuda_graph_trace, the offline script that did
the splice from a pickle side-file, is deleted along with its tests.

    prof.export_chrome_trace(path, cuda_graph_annotations=get_kernel_annotations())

Passing annotation arg implies
use_python_export, since that is the export path able to inject; the C++ path is
untouched otherwise, and the cupti_monitor backend ignores them (it injects
through its own resolver).

A graphed work event whose graph node id has an annotation gets the annotation's
fields in its args and moves to the lane the annotation names; graphed work
without one moves to default_stream, since CUPTI reports a replay on whatever
hardware streams the graph executor picked -- often hundreds. The hardware stream
is kept as original_stream, and a top-level cudaGraphInlineAnnotated flag lets a
consumer tell an already annotated trace from one that still needs the join.

Also brings over three parity fixes: the deviceProperties,
the CUDA version keys from logGpuVersions (runtime version from torch), and
CPU instant events, which were being written as complete events and rendering as
bars.

Test Plan:

```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations TestMetadataJsonFormat
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```

15 and 112 tests pass. TestChromeTraceInlineAnnotations drives the new branches
through stub activities (annotated lane, default lane, non-graphed work left alone,
orphaned gpu_user_annotation slices dropped, no-annotations no-op); the parity test
compares the envelope against kineto's own save(); and an end-to-end test captures
an annotated graph, replays it under the profiler and checks the annotation reached
the kernel events. The end-to-end test lives in the profiler suite rather than
test_cuda_graph_utils because that module holds a CUPTI subscription from import
time, which starves kineto of GPU records.

Authored with assistance from Claude Code.
Pull Request resolved: pytorch#194854
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194852, pytorch#194853
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ic GC (pytorch#195397)

Human note:

fix refcycles in make_graphed_callables so that gc doesn't unexpectedly kick in during graph capture

Destroying a CUDAGraph runs cudaGraphDestroy / cudaGraphExecDestroy / releasePool
(aten/src/ATen/cuda/CUDAGraph.cpp:399-408), none of which are permitted while a stream is
capturing. Doing it mid-capture warns "operation not permitted when stream is capturing
(function reset)" and invalidates that capture, after which the next allocation trips
TORCH_INTERNAL_ASSERT(info.status != cudaStreamCaptureStatusInvalidated) in
CUDACachingAllocator. So *when* a CUDAGraph is freed matters, and make_graphed_callables
was handing that decision to the cyclic collector, which picks an arbitrary allocation
point -- including one inside an unrelated capture.

Two reference cycles put the graphs in the collector's hands. The autograd Function
subclass closed over fwd_graph/bwd_graph, and a class plus its methods' closure cells is
a cycle, so anything those methods captured could only be reclaimed by the GC. On the
nn.Module path the closure installed as func.forward also closed over func -- and over
func.forward, a bound method holding it -- so the module, and through it the graphs, was
cyclic as well. Fixing only one of the two leaves the graphs stranded via the other.

The graphs are now passed to Graphed.apply per call and stashed on ctx, so the class
holds none of them while ctx keeps bwd_graph alive for exactly as long as a backward can
still run. new_fwd holds the module weakly and rebinds its original forward per call.
One case still retains: a module whose forward was already an instance attribute rather
than a bound method has nothing to unbind, so that path keeps holding the module; it is
commented where it happens.

Worth calling out as a behaviour change: calling a graphed module's forward after the
module itself has been freed now raises instead of working by accident. Holding
module.forward while the module is alive is unaffected.

This also removes a workaround. TestMarkKernels in test_cuda_graph_utils.py had a
tearDown that did not chain to super().tearDown(), and restoring the chain made a later
capture in that class fail with exactly the assert above -- the base tearDown shifted
allocation timing enough for a collection to land inside a capture. With the cycles gone
the fixture folds into the ordinary setUp + addCleanup.

Test Plan:

```
python test/test_cuda.py -k make_graphed
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```

8 and 115 tests pass (make_graphed has 3 pre-existing expected failures).
test_graph_make_graphed_callables_freed_by_refcount is the regression test: it drops a
graphed callable with the cyclic GC disabled and asserts no CUDAGraph survives, for both
the nn.Module and plain-callable paths, and fails on the parent commit. The original
end-to-end symptom reproduces via agent_space/repro_gc_capture_invalidate.py, which
stops reproducing with this change.

Authored with assistance from Claude Code.
Pull Request resolved: pytorch#195397
Approved by: https://github.com/ezyang, https://github.com/eqy
ghstack dependencies: pytorch#194852, pytorch#194853, pytorch#194854
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…_annotations workflow (pytorch#195398)

Three findings from integrating the annotation store into a large trainer.

A capture that completes a mark_kernels scope and then fails in capture_end leaked its
annotations for the life of the process. resolve_pending_annotations has to run before
capture_end, because the rekey inside instantiate() is what consumes what it writes, so
its entries land keyed by the capture graph's id and only instantiate() rewrites them to
an exec id. When capture_end raises there is no exec graph and no rewrite, and
remove_kernel_annotations (the graph-destroy path) matches on exec ids, so nothing could
reach them again. __exit__ now purges that capture's entries when capture_end raises.
The purge is scoped to capture_end alone rather than the whole try block -- once it
returns the capture is usable and its annotations are worth keeping -- and is guarded on
the graph not having been remapped already, since keep_graph=False instantiates inside
capture_end.

An earlier writeup of this suggested moving the resolve into capture_end, after the
capture-id stamp. That no longer applies, and the reason is what makes the simpler fix
work: the stamp now happens at capture_begin, so graph._capture_graph_id is already set
when capture_end fails and we know exactly which entries are ours to drop.

clear_kernel_annotations is deprecated rather than deleted. It has no caller in torch
outside tests, and its docstring recommended clearing "once recorded annotations have
been consumed (e.g. after saving them alongside a profiler trace)" -- the
pickle-alongside-trace flow that inline trace export retires. For a long-running trainer
that advice is actively harmful: graphs are captured once and replayed for the whole run,
so a global wipe discards annotations for graphs that are still live and still being
joined against, and growth is already bounded by the remap on instantiate plus
remove_kernel_annotations on destroy. The docstring separately claimed clearing "revokes
recording from every scope opened before the clear", which is not true -- only backward
brackets are versioned by the generation counter, so a forward scope open across a clear
registers on exit as usual. Both claims are corrected, the second now has a test, and
tests call a new private _reset_kernel_annotations for isolation so the suite does not
trip the warning; the one test that is about the public entry point asserts it.

Cleaning up those call sites also removed the redundant ones: nine tests opened with a
reset that their class fixture already does, and two registry-only classes reset in
tearDown alone, which is why each of their tests began with one -- those now use setUp
plus addCleanup. The resets kept are the ones that do work: between iterations of a
loop, or mid-test where the reset is the thing under test.

Finally, register_capture_end_hook documents that capture-end hooks are best-effort:
skipped entirely when cudaStreamEndCapture raises, and truncated when an earlier hook
raises. A consumer using one for teardown needs its own fallback on the error path.

Test Plan:

```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_profiler.py TestPythonChromeTraceExport TestChromeTraceInlineAnnotations
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/profiler/test_cupti_node_timer.py
```

115, 16 and 8 tests pass. test_failed_capture_end_discards_annotations is the regression
test for the leak: reverting just the __exit__ change makes it fail. test_public_bindings
has one failure in this environment that predates the change and is unrelated
(torch.distributed.debug._debug_handlers needs the `tabulate` package).

Authored with assistance from Claude Code.
Pull Request resolved: pytorch#195398
Approved by: https://github.com/ezyang
ghstack dependencies: pytorch#194852, pytorch#194853, pytorch#194854, pytorch#195397
pytorchmergebot pushed a commit that referenced this pull request Sep 16, 2026
…eck (#197136)

The class-level `skipIf(TEST_WITH_ROCM)` on `TestPythonChromeTraceExport` was added with the class in #194854 on the reasoning that the exporter's envelope is NVIDIA-shaped. Only one of the five tests checks the envelope. The other three compare the Python streaming exporter's event stream against kineto's C++ `save()` (plus the gzip and plain-JSON variants) and pass on ROCm: the exporter already degrades cleanly there (cuda-bindings is nulled on ROCm in `torch/cuda/_utils.py`, `sharedMemPerBlockOptin` is guarded). The fifth self-skips on ROCm because CUDA graph annotations are unavailable.

This moves the skip to `test_python_export_envelope_matches_kineto` and records the concrete disagreement: kineto's ROCm backend writes `hip_driver_version`/`hip_runtime_version` instead of the `cuda_*` keys, and its device-property set names two fields differently (`maxSharedMemoryPerMultiProcessor`, `regsPerBlock`) from the `cudaDeviceProp` shape the exporter reproduces. Defining ROCm equivalence for the envelope needs an exporter change and a kineto change and is out of scope here.

Test plan, on gfx950 (ROCm 10.0, HIP 7.15) with the class gate removed locally: 75/75 flake-finder passes and 25/25 per test in isolated processes for the three unskipped tests; full class 3 pass + 1 skip + the envelope test failing as expected without its skip; the rest of test_profiler.py unchanged.

    python -m pytest test/profiler/test_profiler.py -k "TestPythonChromeTraceExport and (gzip or plain_json or export_matches_kineto)" --flake-finder --flake-runs=25
    python test/profiler/test_profiler.py -k TestPythonChromeTraceExport
    python test/profiler/test_profiler.py

gfx942/gfx90a validation via the ciflow labels below; test_profiler is not in the navi31 include list, so gfx1100 gets no CI either way (the three tests exercise only the Python exporter against kineto's own output, no arch-specific path).

This PR was authored with the assistance of an AI agent (Claude). The analysis and test results were verified by hand.

Pull Request resolved: #197136
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
alexmsettle added a commit to alexmsettle/pytorch that referenced this pull request Sep 23, 2026
…ement

Upstream PR pytorch#194854 retired the offline joiner (_annotate_cuda_graph_trace)
and bakes annotations directly into Chrome traces via
prof.export_chrome_trace(path, cuda_graph_annotations=...).

- Remove test_save_annotations_and_join_trace (used the deleted module);
  replace with test_save_annotations_and_chrome_trace which verifies
  save_kernel_annotations persists the registry to disk as pickle.
- Fix _all_fqn_strings to also check "name" key (upstream mark_kernels
  now stores {"name": fqn} not {"str": fqn}).
- Accept deletion of torch/cuda/_annotate_cuda_graph_trace.py during
  rebase onto upstream/main.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
alexmsettle added a commit to alexmsettle/pytorch that referenced this pull request Sep 25, 2026
…ement

Upstream PR pytorch#194854 retired the offline joiner (_annotate_cuda_graph_trace)
and bakes annotations directly into Chrome traces via
prof.export_chrome_trace(path, cuda_graph_annotations=...).

- Remove test_save_annotations_and_join_trace (used the deleted module);
  replace with test_save_annotations_and_chrome_trace which verifies
  save_kernel_annotations persists the registry to disk as pickle.
- Fix _all_fqn_strings to also check "name" key (upstream mark_kernels
  now stores {"name": fqn} not {"str": fqn}).
- Accept deletion of torch/cuda/_annotate_cuda_graph_trace.py during
  rebase onto upstream/main.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
alexmsettle added a commit to alexmsettle/pytorch that referenced this pull request Sep 29, 2026
…ement

Upstream PR pytorch#194854 retired the offline joiner (_annotate_cuda_graph_trace)
and bakes annotations directly into Chrome traces via
prof.export_chrome_trace(path, cuda_graph_annotations=...).

- Remove test_save_annotations_and_join_trace (used the deleted module);
  replace with test_save_annotations_and_chrome_trace which verifies
  save_kernel_annotations persists the registry to disk as pickle.
- Fix _all_fqn_strings to also check "name" key (upstream mark_kernels
  now stores {"name": fqn} not {"str": fqn}).
- Accept deletion of torch/cuda/_annotate_cuda_graph_trace.py during
  rebase onto upstream/main.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <[email protected]>
@github-actions
github-actions Bot deleted the gh/ngimel/14/head branch November 12, 2026 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Merged release notes: cuda release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants