Skip to content

Fix an annotation leak on failed capture, and retire the clear_kernel_annotations workflow - #195398

Closed
ngimel wants to merge 6 commits into
gh/ngimel/16/basefrom
gh/ngimel/16/head
Closed

ngimel wants to merge 6 commits into
gh/ngimel/16/basefrom
gh/ngimel/16/head

Conversation

@ngimel

@ngimel ngimel commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

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.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 58f32ba 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 31, 2026
…_annotations workflow

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.


ghstack-source-id: 4f3a16d
Pull-Request: #195398
[ghstack-poisoned]
ngimel added a commit that referenced this pull request Aug 31, 2026
…_annotations workflow

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

The _annotation_generation counter goes with that advice. It versioned the backward
brackets so a clear could revoke them: hooks mark_kernels attaches to live autograd nodes
cannot be detached, so a version check was the only way to stop them recording. Two
things make it not worth keeping. It never delivered what it claimed -- a forward scope
open across a clear registers on exit regardless, so "revokes recording from every scope
opened before the clear" was false as written. And what it does deliver, it delivers to
the wrong side: the clear has already emptied the registry for every live graph, so
suppressing a stale bracket write is guarding data integrity inside a data-destroying
call.

Its only effect on a working flow is to break one. Capturing a forward graph under a
mark_kernels scope and the backward in a second graph -- the make_graphed_callables
pattern -- projects the forward annotation onto the backward kernels today, because the
brackets outlive the first capture (test_backward_captured_in_separate_graph covers it).
A clear between the two captures kills that projection, and the counter is what makes the
kill thorough. So the three tests that pinned revocation semantics were asserting the
breakage as a feature; they are removed, and the deprecated docstring now says plainly
that nothing is revoked.

This is a silent behaviour change for anyone who called clear_kernel_annotations and
relied on revocation. No caller in torch or fbcode does -- the one live caller
(genai/msl/cudagraph_fx) clears for read scoping its per-key lookups do not need -- and
the contract was never fully honoured, but it changes results rather than erroring.

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.

ghstack-source-id: 2e52955
Pull-Request: #195398
Comment thread test/test_cuda_graph_utils.py Resolved
Comment thread test/test_cuda_graph_utils.py Resolved
Comment thread torch/cuda/graphs.py
# that nothing can reach later. Scoped to capture_end alone: once it
# returns the capture is usable and its annotations are worth keeping.
if self._enable_annotations:
discard_capture_annotations(self.cuda_graph)

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.

nit: if this fails, probably better to suppress it and continue to propagate the original exception

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.

It can't fail in any reasonable scenario, it's just deleting a dict

@ngimel ngimel added the topic: not user facing topic category label Aug 31, 2026
[ghstack-poisoned]
ngimel added a commit that referenced this pull request Sep 1, 2026
…_annotations workflow

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

The _annotation_generation counter goes with that advice. It versioned the backward
brackets so a clear could revoke them: hooks mark_kernels attaches to live autograd nodes
cannot be detached, so a version check was the only way to stop them recording. Two
things make it not worth keeping. It never delivered what it claimed -- a forward scope
open across a clear registers on exit regardless, so "revokes recording from every scope
opened before the clear" was false as written. And what it does deliver, it delivers to
the wrong side: the clear has already emptied the registry for every live graph, so
suppressing a stale bracket write is guarding data integrity inside a data-destroying
call.

Its only effect on a working flow is to break one. Capturing a forward graph under a
mark_kernels scope and the backward in a second graph -- the make_graphed_callables
pattern -- projects the forward annotation onto the backward kernels today, because the
brackets outlive the first capture (test_backward_captured_in_separate_graph covers it).
A clear between the two captures kills that projection, and the counter is what makes the
kill thorough. So the three tests that pinned revocation semantics were asserting the
breakage as a feature; they are removed, and the deprecated docstring now says plainly
that nothing is revoked.

This is a silent behaviour change for anyone who called clear_kernel_annotations and
relied on revocation. No caller in torch or fbcode does -- the one live caller
(genai/msl/cudagraph_fx) clears for read scoping its per-key lookups do not need -- and
the contract was never fully honoured, but it changes results rather than erroring.

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.

ghstack-source-id: 62f4ee7
Pull-Request: #195398
[ghstack-poisoned]
ngimel added a commit that referenced this pull request Sep 1, 2026
…_annotations workflow

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

The _annotation_generation counter goes with that advice. It versioned the backward
brackets so a clear could revoke them: hooks mark_kernels attaches to live autograd nodes
cannot be detached, so a version check was the only way to stop them recording. Two
things make it not worth keeping. It never delivered what it claimed -- a forward scope
open across a clear registers on exit regardless, so "revokes recording from every scope
opened before the clear" was false as written. And what it does deliver, it delivers to
the wrong side: the clear has already emptied the registry for every live graph, so
suppressing a stale bracket write is guarding data integrity inside a data-destroying
call.

Its only effect on a working flow is to break one. Capturing a forward graph under a
mark_kernels scope and the backward in a second graph -- the make_graphed_callables
pattern -- projects the forward annotation onto the backward kernels today, because the
brackets outlive the first capture (test_backward_captured_in_separate_graph covers it).
A clear between the two captures kills that projection, and the counter is what makes the
kill thorough. So the three tests that pinned revocation semantics were asserting the
breakage as a feature; they are removed, and the deprecated docstring now says plainly
that nothing is revoked.

This is a silent behaviour change for anyone who called clear_kernel_annotations and
relied on revocation. No caller in torch or fbcode does -- the one live caller
(genai/msl/cudagraph_fx) clears for read scoping its per-key lookups do not need -- and
the contract was never fully honoured, but it changes results rather than erroring.

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.

The same error path was also leaving the caller's stream behind. __exit__ unwound its
stream context only after capture_end returned, so a capture_end that raised propagated
without restoring it and left the graph's private stream current for everything that ran
next. The unwind moves into the finally; it still has to happen after capture_end, which
checks the current stream is the one capture began on, but nothing requires it to be
skipped when that check's call fails. test_failed_capture_end_discards_annotations covers
it -- it had been working around the leak by restoring the stream itself.

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.

ghstack-source-id: 048e456
Pull-Request: #195398
[ghstack-poisoned]
ngimel added a commit that referenced this pull request Sep 1, 2026
…_annotations workflow

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

The _annotation_generation counter goes with that advice. It versioned the backward
brackets so a clear could revoke them: hooks mark_kernels attaches to live autograd nodes
cannot be detached, so a version check was the only way to stop them recording. Two
things make it not worth keeping. It never delivered what it claimed -- a forward scope
open across a clear registers on exit regardless, so "revokes recording from every scope
opened before the clear" was false as written. And what it does deliver, it delivers to
the wrong side: the clear has already emptied the registry for every live graph, so
suppressing a stale bracket write is guarding data integrity inside a data-destroying
call.

Its only effect on a working flow is to break one. Capturing a forward graph under a
mark_kernels scope and the backward in a second graph -- the make_graphed_callables
pattern -- projects the forward annotation onto the backward kernels today, because the
brackets outlive the first capture (test_backward_captured_in_separate_graph covers it).
A clear between the two captures kills that projection, and the counter is what makes the
kill thorough. So the three tests that pinned revocation semantics were asserting the
breakage as a feature; they are removed, and the deprecated docstring now says plainly
that nothing is revoked.

This is a silent behaviour change for anyone who called clear_kernel_annotations and
relied on revocation. No caller in torch or fbcode does -- the one live caller
(genai/msl/cudagraph_fx) clears for read scoping its per-key lookups do not need -- and
the contract was never fully honoured, but it changes results rather than erroring.

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.

The same error path was also leaving the caller's stream behind. __exit__ unwound its
stream context only after capture_end returned, so a capture_end that raised propagated
without restoring it and left the graph's private stream current for everything that ran
next. The unwind moves into the finally; it still has to happen after capture_end, which
checks the current stream is the one capture began on, but nothing requires it to be
skipped when that check's call fails. test_failed_capture_end_discards_annotations covers
it -- it had been working around the leak by restoring the stream itself.

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.

ghstack-source-id: 7b9c2e1
Pull-Request: #195398
@ngimel

ngimel commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 2, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

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
@github-actions
github-actions Bot deleted the gh/ngimel/16/head branch November 13, 2026 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants