Skip to content

Clean up CUDA graph state after warmup failures - #3862

Merged
pggPL merged 9 commits into
NVIDIA:mainfrom
WEIXILIN0307:fix/cuda-graph-warmup-cleanup
Nov 27, 2026
Merged

pggPL merged 9 commits into
NVIDIA:mainfrom
WEIXILIN0307:fix/cuda-graph-warmup-cleanup

Conversation

@WEIXILIN0307

@WEIXILIN0307 WEIXILIN0307 commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Description

Capturing a TE Linear layer and its subclass together can leave the subclass with a temporary autocast wrapper after successful capture. A fresh eager instance then ignores its calibration context even after both graphs are reset. A warmup or capture exception can also leave temporary discovery hooks, GC disabled, cleared input gradients, or capture state behind.

Validate modules before changing capture state and register cleanup via contextlib.ExitStack as setup acquires it. Restore inherited class dispatch and saved capture state on exit, remove discovery hooks when warmup ends, wait on the warmup stream before returning to the caller stream, and guard _none_grad_context_wrapper and _graph_context_wrapper with try/finally. If capture and cleanup both raise, the capture error stays primary and the cleanup error is chained to it. Capture still needs serialized host access because it temporarily changes class dispatch. Fatal CUDA errors require a process restart.

Review guide

Start at make_graphed_callables(). Check that inherited calls are resolved before any class is patched and that cleanup removes temporary overrides. Then check warmup hook ownership and the normal capture and eager calibration regression.

Type of change

  • Bug fix

Validation

  • On 9c1e9c0, 13 focused CUDA Graph cases pass on one RTX A6000 with PyTorch 2.11.0+cu130 and the PR's Python graph module over TE 2.20.2 native binaries. Successful capture and rejected input regressions fail at base 464df75. On 7a895dc, the injected double failure exposes the FP8 restore error. This revision preserves the warmup error and its cause, restores capture state, and verifies a successful retry after a warmup failure.
  • Two downstream GPT and Hybrid MoE cases pass per rank on two A6000s with Megatron 4d48616, its eval/checkpoint prerequisites and the graph implementation at 22d4727. Downstream RFC · Earlier reproduction and logs
  • Full L0, a native rebuild and FP8 graph execution qualification remain pending.
python -m pytest -q tests/pytorch/test_cuda_graphs.py \
  -k 'capture_preserves_eager_calibration or invalid_module_does_not_leave_capture_state or warmup_failure_restores_capture_state'

Checklist

  • Read the contributing guidelines.
  • Add focused regression coverage.
  • Run the selected regression and downstream composition checks.
  • Run full upstream L0/CI.
  • Human author review before marking ready for maintainer review.

Signed-off-by: Pinoeer-kingxi <13022943007@163.com>
@lxcxjxhx

Copy link
Copy Markdown
Contributor

The finally covers the warmup itself, and I could not construct a path inside _make_graphed_callables that escapes it. There is one window before it that the same cleanup should probably cover — everything between set_capture_start() and the try.

In make_graphed_callables on main:

set_capture_start()                      # L1643 — flag is now True
...
saved_fp8_tensors = save_fp8_tensors(modules, recipe=recipe)   # L1675 — can raise
...
for module in modules:
    if not isinstance(module, torch.nn.Module):
        raise TypeError(f"Graphing for {type(module)} is not supported.")   # L1702
    wrap_autocast(module)                # L1705 — patches block_cls.__call__ class-wide
...
try:                                     # <- this PR's try starts here (~L1729)
    graphed_callables = _make_graphed_callables(...)
finally:
    ...restore...

wrap_autocast mutates type(block).__call__ for every module class it has seen, and the type check that raises TypeError runs inside the loop, after earlier modules have already been wrapped. So:

make_graphed_callables([torch.nn.Linear(8, 8), "not a module"], [(x,)], ...)
# raises TypeError as intended — but is_graph_capturing() is still True,
# and Linear.__call__ is still the autocast wrapper installed at L1705.

A second call after that is the exact situation the PR is about ("Retrying capture on the same module can then run with stale hooks or wrappers"), just reached through the argument-validation path instead of a failing forward. save_fp8_tensors raising at L1675 leaves the flag set as well.

Two ways to close it, both small:

  1. Move set_capture_start() inside the try (first statement), leaving the rest of the setup outside; the flag then has exactly one owner and one restore site. The RNG save at L1714 also belongs inside, since the finally restores it unconditionally.
  2. Or keep the current structure and wrap the whole body from L1643 in try/finally, which is the more literal reading of "restore capture-owned state".

Nothing here blocks the warmup-failure case the PR was written for; it is the neighbouring exit path that the same helper already knows how to handle.

Two smaller notes:

  • The finally body is unguarded: if restore_fp8_tensors(modules, saved_fp8_tensors) raises (e.g. a partially-captured module no longer matches the saved tensors), it replaces the warmup RuntimeError and the caller sees the cleanup error instead. Your test asserts match="controlled warmup forward failure", so it would notice this for the specific case it covers; wrapping each restore step (or collecting them in an ExitStack) keeps the original exception authoritative for all of them.
  • test_warmup_forward_failure_cleanup_and_retry's own finally calls te_graph.set_capture_end() and restores type(model).__call__, which is the same manual cleanup the PR is trying to make unnecessary inside the library — if the library behaviour regresses, the test's finally can mask it for the assertions that follow. Not a problem today (the assertions come before finally), only a note for whoever extends the test.

Validate modules before changing capture state, and register cleanup as RNG snapshots, FP8 state and class wrappers are acquired. Remove inherited class overrides on exit. Run the remaining cleanup after a restore error and keep the capture failure visible to callers.

Signed-off-by: Pinoeer-kingxi <weixilin307@gmail.com>
Graph a TE Linear and its subclass, replay and release both, then calibrate a fresh eager instance. The previously leaked class wrapper suppressed real calibration after successful capture. Move inheritance coverage out of the injected warmup failure test.

Signed-off-by: Pinoeer-kingxi <weixilin307@gmail.com>
@WEIXILIN0307
WEIXILIN0307 marked this pull request as ready for review November 25, 2026 01:50
@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · No new blocking issue was found beyond the supplied review threads.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] No new blocking issue was found beyond the supplied review threads.

Summary

The PR restores temporary CUDA graph state after capture and warmup finish.

  • Graph capture restores module calls and capture state when setup exits.
  • Warmup removes discovery hooks and waits on its CUDA stream before returning.
  • Graph contexts restore input gradients and garbage collection after exceptions.

Reviews (6) · Last reviewed commit: "Revert "Preserve CUDA graph capture erro..." · Reviewed by Greptile

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Comment thread tests/pytorch/test_cuda_graphs.py Resolved
Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>
Comment thread transformer_engine/pytorch/graph.py Resolved
@pggPL

pggPL commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

/te-ci pytorch L0

WEIXILIN0307 and others added 2 commits November 27, 2026 03:47
Close the cleanup stack explicitly on a capture failure so a secondary restore error is chained to the original failure. Restore focused tests for rejected inputs, warmup retry, and failure during cleanup.

Signed-off-by: Pinoeer-kingxi <weixilin307@gmail.com>
This reverts commit 9c1e9c0.

Signed-off-by: Pawel Gadzinski <pgadzinski@nvidia.com>

@pggPL pggPL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

hi, thanks for contributing. I prefer having less tests because we have limited budget for them, so I reverted your commit. Other things LGTM

@pggPL
pggPL merged commit 37be77c into NVIDIA:main Nov 27, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants