Skip to content

Free make_graphed_callables' CUDA graphs by refcount, not by the cyclic GC - #195397

Closed
ngimel wants to merge 5 commits into
gh/ngimel/15/basefrom
gh/ngimel/15/head
Closed

ngimel wants to merge 5 commits into
gh/ngimel/15/basefrom
gh/ngimel/15/head

Conversation

@ngimel

@ngimel ngimel commented Aug 31, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

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.

[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/195397

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

✅ No Failures

As of commit af61414 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 ngimel added the topic: not user facing topic category label Aug 31, 2026
[ghstack-poisoned]
@ngimel

ngimel commented Sep 1, 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 1, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 5, 8, linux.rocm.gpu.gfx950.1)

Details for Dev Infra team Raised by workflow job

[ghstack-poisoned]
[ghstack-poisoned]
@eqy
eqy requested review from eee4017 and galv September 2, 2026 00:04
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #195398

pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
…_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
…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
@github-actions
github-actions Bot deleted the gh/ngimel/15/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.

4 participants