Skip to content

Clean up CUDA graph state after warmup failures - #3862

Open
WEIXILIN0307 wants to merge 4 commits into
NVIDIA:mainfrom
WEIXILIN0307:fix/cuda-graph-warmup-cleanup
Open

WEIXILIN0307 wants to merge 4 commits into
NVIDIA:mainfrom
WEIXILIN0307:fix/cuda-graph-warmup-cleanup

Conversation

@WEIXILIN0307

@WEIXILIN0307 WEIXILIN0307 commented Nov 13, 2026 •

Copy link
Copy Markdown

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 exception can also leave temporary discovery hooks installed, which affects the next capture attempt.

Validate modules before changing capture state and register cleanup as setup acquires it. Restore inherited class dispatch and saved capture state on exit, and remove the discovery hooks when warmup ends. If cleanup also fails, 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

  • The normal capture regression fails at 464df75 and passes at 181dbd5. Five focused tests pass on one RTX A6000 using the PR's Python graph module with PyTorch 2.11.0+cu130 and TE 2.20.2 native binaries.
  • The warmup tests inject a forward failure and a secondary cleanup failure to check error propagation. 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 warmup_forward_failure or invalid_module'

Checklist

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

@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 <[email protected]>
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 <[email protected]>
@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

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge based on this review.

Summary

The PR restores temporary class calls, saved RNG and FP8 state, and the capture flag after capture exits. It also removes discovery hooks when warmup fails.

  • Graph capture restores temporary module state when setup fails.

Reviews (2) · Last reviewed commit: "Remove verbose cleanup note from make_gr..." · Reviewed by Greptile

This branch has not been deployed

No deployments
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