Repository navigation
Conversation
[ghstack-poisoned]
🔗 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 FailuresAs of commit e1df7cb with merge base 460948b ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
…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
| metadata=None, | ||
| use_python_export=False, | ||
| cuda_graph_annotations=None, | ||
| default_stream=7, |
There was a problem hiding this comment.
OOC where does 7 come from?
There was a problem hiding this comment.
No idea, but that's what default stream has been in the profiles forever
| "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] |
There was a problem hiding this comment.
AI-assisted review note:
shared_memory_per_block_optinis excluded from the device-properties binding underUSE_ROCM, souse_python_export=Truewill raiseAttributeErroron ROCm here. Could we omitsharedMemPerBlockOptinwhen the property is unavailable (and add a ROCm-safe test)?
There was a problem hiding this comment.
I suspect ROCm will error out much earlier - no annotations available on ROCm, cuda-bindings not available on ROCm
| 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))}') |
There was a problem hiding this comment.
not sure if we care about compat
AI-assisted review note:
The deleted annotator normalized legacy bare strings and
{"str": "phase"}entries into the canonicalnamefield. This path now emitsannotationorstrinstead, and the old compatibility tests are removed. Could we preserve that normalization here and retain those regression cases?
There was a problem hiding this comment.
str annotation is now normalized into {"name":value}
| """ | ||
| activities = kineto_results.trace_activities() | ||
| base_ns = _trimester_base_ns() | ||
| annotations = annotations or {} |
There was a problem hiding this comment.
subtle not sure if matters
AI-assisted review note:
annotations = annotations or {}plus the later truthiness checks meanscuda_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 todefault_stream; an empty mapping should therefore collapse all graphed work, whileNoneshould remain a no-op. Could we keep anannotations is not Nonemode flag?
There was a problem hiding this comment.
Resolved to have {} and None behave in the same way
| 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 |
There was a problem hiding this comment.
not sure if this is like the inner wins thign
AI-assisted review note:
metadata_json()already contains the hardwarestream, and this appends anotherstreammember to the sameargsobject. 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 asoriginal_stream?
[ghstack-poisoned]
…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
…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
|
@claude check if review comments were addressed |
|
Claude finished @ngimel's task in 7m 35s —— View job Review-comment statusAll six of @drisspg's threads are either fixed in code (commits Thread-by-thread detail1. 2. ROCm 3. Legacy annotation normalization — 4. 5. Duplicate 6. Perfetto overlap / collision handling — ✅ answered + design change. Answered in thread (Perfetto no longer drops overlapping events). Additionally the Residual nits I noticed while checking, all minor:
I did not run tests or lint (no built PyTorch/CUDA in this checkout); the checks above are from reading the code and diffing |
[ghstack-poisoned]
|
Starting merge as part of PR stack under #195397 |
[ghstack-poisoned]
|
Starting merge as part of PR stack under #195398 |
…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
…_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
…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]>
…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
…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
…_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
…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]>
…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]>
…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]>
…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]>
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.
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:
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.