Repository navigation
Conversation
[ghstack-poisoned]
ngimel
requested review from
Aidyn-A,
eqy,
ryanzhang22,
scotts and
syed-ahmed
as code owners
August 26, 2026 05:14
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194852
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 254e523 with merge base 460948b ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Aug 26, 2026
drisspg
approved these changes
Aug 26, 2026
[ghstack-poisoned]
Collaborator
|
Starting merge as part of PR stack under #194853 |
pytorchmergebot
pushed a commit
that referenced
this pull request
Aug 30, 2026
Human note:
backward annotation projection and cupti backend for getting annotations were merged approximately simultaneously,
and cupti backend didn't correctly handle backward annotations - all the backward node stayed empty with cupti backend.
mark_kernels' CUPTI path returned as soon as it had pushed its annotation onto
the ambient scope stack, before the code that enters the annotation region and
installs the autograd node-creation hook. So with annotation_config={"backend":
"cupti"} the documented backward=True behaviour silently did nothing: no autograd
node created in a scope was ever bracketed, and backward kernels were attributed
only to whatever scope happened to be lexically open around the backward() call,
or to nothing at all.
The region and creation hook are backend-independent, so they move into a shared
_annotation_region context manager that both paths enter. The bracket the hook
installs then splits on the backend the same way mark_kernels does: under the
edge walk it snapshots the capture frontier and collects new nodes on the way
out, under CUPTI it publishes its (already merged) region on _active_scopes so
the nodes created while it runs are attributed as CUPTI reports them. Publishing
is also what gets the precedence right -- the forward region has to outrank the
scope lexically open around the backward call, which is what CUPTI would
otherwise record for those nodes.
Test Plan:
```
LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py
```
115 tests pass. test_parity_with_edge_walk grows a backward pass -- run inside a
second scope, so it also pins the precedence -- and compares the full per-node
annotation maps of the two backends rather than just their node ids. On the
parent commit the CUPTI run records no autograd_phase entries at all, so the
comparison fails.
Authored with assistance from Claude Code.
Pull Request resolved: #194853
Approved by: https://github.com/drisspg
ghstack dependencies: #194852
orrangetabby17
pushed a commit
to orrangetabby17/pytorch
that referenced
this pull request
Sep 2, 2026
Human note:
_kernel_annotations type is now map(int, list(Any)), this masks that the list at most contains a single dict.
Make the type correct - for each node there's a single dict of annotations.
The kernel annotation registry mapped a node's toolsId to a list of annotations,
but nothing ever put a second entry in that list on a reachable path. Both
writers already merge before they write: the CUPTI backend merges nested scopes
at scope entry and records one dict per node, and the edge-walk backend merges a
resolve batch's overlapping scopes and appends the single result. The remaining
paths that could append twice cannot happen -- the rekey collision branch needed
a graph and an exec id to be equal, and the driver mints both from one counter it
does not reuse (measured: graph/exec ids 1,2 / 4,5 / 7,8 ... across create and
destroy). So consumers carried list-merging code for a case the producer never
produced, and disagreed on precedence while doing it: the resolver merged
first-wins, the offline trace annotator later-wins.
Make the store dict[toolsId, annotation] with a single merge helper both writers
share (first write wins per key, which is the existing inner-scope-wins rule --
scopes are recorded innermost first). resolve_pending_annotations collapses to a
loop over pending scopes, and the rekey no longer needs its collision branch.
get_kernel_annotations() keeps its list-valued shape via a read-only Mapping view
that wraps each entry on read, since pickles of it are consumed by
_annotate_cuda_graph_trace and it is documented as a live view. Wrapping at the
boundary rather than storing lists is what makes "at most one annotation per
node" explicit. In-process consumers read the dict directly through the new
annotation_for(), so the profiler exporters spread its fields instead of
re-serializing a list into an opaque "annotation" string; the node timer's bucket
keys go from "[{'name': 'x'}]" to "{'name': 'x'}" for the same reason.
Review the store and merge helper first, then the resolve/rekey simplifications
that follow from it, then the view and the two consumers.
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_cupti_monitor.py
```
test_cuda_graph_utils passes (115 tests), including the new TestAnnotationStore
covering the merge rule and the view's liveness/read-only-ness. test_cupti_monitor
has one pre-existing failure (CUPTI_ERROR_MULTIPLE_SUBSCRIBERS_NOT_SUPPORTED in
full-suite runs); it fails identically on the parent commit and passes when run
alone.
Authored with assistance from Claude Code.
Pull Request resolved: pytorch#194852
Approved by: https://github.com/drisspg
orrangetabby17
pushed a commit
to orrangetabby17/pytorch
that referenced
this pull request
Sep 2, 2026
…#194853) Human note: backward annotation projection and cupti backend for getting annotations were merged approximately simultaneously, and cupti backend didn't correctly handle backward annotations - all the backward node stayed empty with cupti backend. mark_kernels' CUPTI path returned as soon as it had pushed its annotation onto the ambient scope stack, before the code that enters the annotation region and installs the autograd node-creation hook. So with annotation_config={"backend": "cupti"} the documented backward=True behaviour silently did nothing: no autograd node created in a scope was ever bracketed, and backward kernels were attributed only to whatever scope happened to be lexically open around the backward() call, or to nothing at all. The region and creation hook are backend-independent, so they move into a shared _annotation_region context manager that both paths enter. The bracket the hook installs then splits on the backend the same way mark_kernels does: under the edge walk it snapshots the capture frontier and collects new nodes on the way out, under CUPTI it publishes its (already merged) region on _active_scopes so the nodes created while it runs are attributed as CUPTI reports them. Publishing is also what gets the precedence right -- the forward region has to outrank the scope lexically open around the backward call, which is what CUPTI would otherwise record for those nodes. Test Plan: ``` LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py ``` 115 tests pass. test_parity_with_edge_walk grows a backward pass -- run inside a second scope, so it also pins the precedence -- and compares the full per-node annotation maps of the two backends rather than just their node ids. On the parent commit the CUPTI run records no autograd_phase entries at all, so the comparison fails. Authored with assistance from Claude Code. Pull Request resolved: pytorch#194853 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#194852
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 2, 2026
…ne joiner (#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: #194854 Approved by: https://github.com/drisspg ghstack dependencies: #194852, #194853
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
Sanskaaar1
pushed a commit
to Sanskaaar1/pytorch
that referenced
this pull request
Sep 8, 2026
Human note:
_kernel_annotations type is now map(int, list(Any)), this masks that the list at most contains a single dict.
Make the type correct - for each node there's a single dict of annotations.
The kernel annotation registry mapped a node's toolsId to a list of annotations,
but nothing ever put a second entry in that list on a reachable path. Both
writers already merge before they write: the CUPTI backend merges nested scopes
at scope entry and records one dict per node, and the edge-walk backend merges a
resolve batch's overlapping scopes and appends the single result. The remaining
paths that could append twice cannot happen -- the rekey collision branch needed
a graph and an exec id to be equal, and the driver mints both from one counter it
does not reuse (measured: graph/exec ids 1,2 / 4,5 / 7,8 ... across create and
destroy). So consumers carried list-merging code for a case the producer never
produced, and disagreed on precedence while doing it: the resolver merged
first-wins, the offline trace annotator later-wins.
Make the store dict[toolsId, annotation] with a single merge helper both writers
share (first write wins per key, which is the existing inner-scope-wins rule --
scopes are recorded innermost first). resolve_pending_annotations collapses to a
loop over pending scopes, and the rekey no longer needs its collision branch.
get_kernel_annotations() keeps its list-valued shape via a read-only Mapping view
that wraps each entry on read, since pickles of it are consumed by
_annotate_cuda_graph_trace and it is documented as a live view. Wrapping at the
boundary rather than storing lists is what makes "at most one annotation per
node" explicit. In-process consumers read the dict directly through the new
annotation_for(), so the profiler exporters spread its fields instead of
re-serializing a list into an opaque "annotation" string; the node timer's bucket
keys go from "[{'name': 'x'}]" to "{'name': 'x'}" for the same reason.
Review the store and merge helper first, then the resolve/rekey simplifications
that follow from it, then the view and the two consumers.
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_cupti_monitor.py
```
test_cuda_graph_utils passes (115 tests), including the new TestAnnotationStore
covering the merge rule and the view's liveness/read-only-ness. test_cupti_monitor
has one pre-existing failure (CUPTI_ERROR_MULTIPLE_SUBSCRIBERS_NOT_SUPPORTED in
full-suite runs); it fails identically on the parent commit and passes when run
alone.
Authored with assistance from Claude Code.
Pull Request resolved: pytorch#194852
Approved by: https://github.com/drisspg
Sanskaaar1
pushed a commit
to Sanskaaar1/pytorch
that referenced
this pull request
Sep 8, 2026
…#194853) Human note: backward annotation projection and cupti backend for getting annotations were merged approximately simultaneously, and cupti backend didn't correctly handle backward annotations - all the backward node stayed empty with cupti backend. mark_kernels' CUPTI path returned as soon as it had pushed its annotation onto the ambient scope stack, before the code that enters the annotation region and installs the autograd node-creation hook. So with annotation_config={"backend": "cupti"} the documented backward=True behaviour silently did nothing: no autograd node created in a scope was ever bracketed, and backward kernels were attributed only to whatever scope happened to be lexically open around the backward() call, or to nothing at all. The region and creation hook are backend-independent, so they move into a shared _annotation_region context manager that both paths enter. The bracket the hook installs then splits on the backend the same way mark_kernels does: under the edge walk it snapshots the capture frontier and collects new nodes on the way out, under CUPTI it publishes its (already merged) region on _active_scopes so the nodes created while it runs are attributed as CUPTI reports them. Publishing is also what gets the precedence right -- the forward region has to outrank the scope lexically open around the backward call, which is what CUPTI would otherwise record for those nodes. Test Plan: ``` LD_LIBRARY_PATH=/usr/local/cuda-13.2/compat python test/test_cuda_graph_utils.py ``` 115 tests pass. test_parity_with_edge_walk grows a backward pass -- run inside a second scope, so it also pins the precedence -- and compares the full per-node annotation maps of the two backends rather than just their node ids. On the parent commit the CUPTI run records no autograd_phase entries at all, so the comparison fails. Authored with assistance from Claude Code. Pull Request resolved: pytorch#194853 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#194852
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Human note:
_kernel_annotations type is now map(int, list(Any)), this masks that the list at most contains a single dict.
Make the type correct - for each node there's a single dict of annotations.
The kernel annotation registry mapped a node's toolsId to a list of annotations,
but nothing ever put a second entry in that list on a reachable path. Both
writers already merge before they write: the CUPTI backend merges nested scopes
at scope entry and records one dict per node, and the edge-walk backend merges a
resolve batch's overlapping scopes and appends the single result. The remaining
paths that could append twice cannot happen -- the rekey collision branch needed
a graph and an exec id to be equal, and the driver mints both from one counter it
does not reuse (measured: graph/exec ids 1,2 / 4,5 / 7,8 ... across create and
destroy). So consumers carried list-merging code for a case the producer never
produced, and disagreed on precedence while doing it: the resolver merged
first-wins, the offline trace annotator later-wins.
Make the store dict[toolsId, annotation] with a single merge helper both writers
share (first write wins per key, which is the existing inner-scope-wins rule --
scopes are recorded innermost first). resolve_pending_annotations collapses to a
loop over pending scopes, and the rekey no longer needs its collision branch.
get_kernel_annotations() keeps its list-valued shape via a read-only Mapping view
that wraps each entry on read, since pickles of it are consumed by
_annotate_cuda_graph_trace and it is documented as a live view. Wrapping at the
boundary rather than storing lists is what makes "at most one annotation per
node" explicit. In-process consumers read the dict directly through the new
annotation_for(), so the profiler exporters spread its fields instead of
re-serializing a list into an opaque "annotation" string; the node timer's bucket
keys go from "[{'name': 'x'}]" to "{'name': 'x'}" for the same reason.
Review the store and merge helper first, then the resolve/rekey simplifications
that follow from it, then the view and the two consumers.
Test Plan:
test_cuda_graph_utils passes (115 tests), including the new TestAnnotationStore
covering the merge rule and the view's liveness/read-only-ness. test_cupti_monitor
has one pre-existing failure (CUPTI_ERROR_MULTIPLE_SUBSCRIBERS_NOT_SUPPORTED in
full-suite runs); it fails identically on the parent commit and passes when run
alone.
Authored with assistance from Claude Code.