From 0eb9c38ba05932a6db5bafb6fbc4fa50661fee8e Mon Sep 17 00:00:00 2001 From: Pinoeer-kingxi <13022943007@163.com> Date: Thu, 12 Nov 2026 21:11:00 -0800 Subject: [PATCH 1/9] Clean up CUDA graph state after warmup failures Signed-off-by: Pinoeer-kingxi <13022943007@163.com> --- tests/pytorch/test_cuda_graphs.py | 55 ++++++++++++++++++++++ transformer_engine/pytorch/graph.py | 73 +++++++++++++++-------------- 2 files changed, 93 insertions(+), 35 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index 46aab13075c..5d51b936bbe 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -141,6 +141,61 @@ def reset_global_fp8_state(): FP8GlobalStateManager.reset() +def test_warmup_forward_failure_cleanup_and_retry(): + """A failed warmup must leave the module reusable for capture and training.""" + from transformer_engine.pytorch import graph as te_graph + + class FailDuringWarmup(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(32, 32, dtype=torch.bfloat16, device="cuda") + self.dropout = torch.nn.Dropout(0.1) + self.fail = True + + def forward(self, inp): + output = self.dropout(self.linear(inp)) + if self.fail: + raise RuntimeError("controlled warmup forward failure") + return output + + model = FailDuringWarmup() + inp = torch.randn(4, 32, device="cuda", dtype=torch.bfloat16) + original_call = type(model).__call__ + hooks = [(module, dict(module._forward_hooks)) for module in model.modules()] + cpu_rng = torch.get_rng_state() + cuda_rng = torch.cuda.get_rng_state() + graphed = None + try: + with pytest.raises(RuntimeError, match="controlled warmup forward failure"): + make_graphed_callables(model, (inp,), num_warmup_iters=1) + for module, original_hooks in hooks: + assert module._forward_hooks == original_hooks + assert type(model).__call__ is original_call + assert not te_graph.is_graph_capturing() + torch.testing.assert_close(torch.get_rng_state(), cpu_rng, rtol=0, atol=0) + torch.testing.assert_close(torch.cuda.get_rng_state(), cuda_rng, rtol=0, atol=0) + + model.fail = False + reference = copy.deepcopy(model) + reference_input = inp.clone() + rng = torch.cuda.get_rng_state() + expected = reference(reference_input) + expected.sum().backward() + expected_parameter_grads = [p.grad.clone() for p in reference.parameters()] + torch.cuda.set_rng_state(rng) + graphed = make_graphed_callables(model, (inp,), num_warmup_iters=1) + actual = graphed(inp) + actual.sum().backward() + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + for parameter, expected_grad in zip(model.parameters(), expected_parameter_grads): + torch.testing.assert_close(parameter.grad, expected_grad, rtol=0, atol=0) + finally: + if graphed is not None: + graphed.reset() + type(model).__call__ = original_call + te_graph.set_capture_end() + + def assert_all_equal(l1: List[torch.Tensor], l2: List[torch.Tensor], names=None) -> bool: """Check that two lists of tensors match exactly.""" assert len(l1) == len(l2), "Unequal number of outputs." diff --git a/transformer_engine/pytorch/graph.py b/transformer_engine/pytorch/graph.py index 5362c7cc278..8a7ff292e54 100644 --- a/transformer_engine/pytorch/graph.py +++ b/transformer_engine/pytorch/graph.py @@ -3,6 +3,7 @@ # See LICENSE for license information. """Functions for CUDA Graphs support in FP8""" + from collections.abc import Iterable import contextlib import gc @@ -576,11 +577,13 @@ def hook_fn(module, inputs, outputs, func_idx=func_idx): # pylint: disable=unus _run_capture_time_hooks(capture_time_hooks, callable_idx, "forward_pre_hooks", func) hooks = [] - for module in func.modules(): - hooks.append(module.register_forward_hook(hook_fn)) - outputs = func(*args, **kwargs) - for hook in hooks: - hook.remove() + try: + for module in func.modules(): + hooks.append(module.register_forward_hook(hook_fn)) + outputs = func(*args, **kwargs) + finally: + for hook in hooks: + hook.remove() _run_capture_time_hooks(capture_time_hooks, callable_idx, "forward_hooks", func) @@ -1479,6 +1482,10 @@ def make_graphed_callables( `original PyTorch implementation `_ for more documentation. + If a callable raises during warmup, temporary discovery hooks, saved RNG state, + module call wrappers, and the capture flag are restored before the exception is + re-raised. This cleanup does not make fatal CUDA errors recoverable. + .. warning:: Arguments 'fp8_enabled', 'fp8_calibrating', 'fp8_recipe', 'fp8_group', and 'fp8_weight_caching' are deprecated. @@ -1717,34 +1724,30 @@ def call_func(self, *args, **kwargs): ] original_rng_states = [state.get_state() for state in generators] - graphed_callables = _make_graphed_callables( - forward_funcs, - sample_args, - num_warmup_iters=num_warmup_iters, - allow_unused_input=allow_unused_input, - cache_quantized_params=cache_quantized_params, - sample_kwargs=sample_kwargs, - _order=_order, - _num_layers_per_chunk=_num_layers_per_chunk, - pool=pool, - retain_graph_in_backward=retain_graph_in_backward, - _reuse_graph_input_output_buffers=_reuse_graph_input_output_buffers, - clone_param_grads_on_return=clone_param_grads_on_return, - pre_warmup_hook=pre_warmup_hook, - post_warmup_hook=post_warmup_hook, - capture_time_hooks=capture_time_hooks, - ) - - # Ensures warmup does not affect numerics for ops such as dropout. - for gen, state in zip(generators, original_rng_states): - gen.set_state(state) - - # Remove FP8 wrapper. - for module_cls, old_call in old_call_funcs.items(): - module_cls.__call__ = old_call - - # Restore FP8 state. - restore_fp8_tensors(modules, saved_fp8_tensors) - - set_capture_end() + try: + graphed_callables = _make_graphed_callables( + forward_funcs, + sample_args, + num_warmup_iters=num_warmup_iters, + allow_unused_input=allow_unused_input, + cache_quantized_params=cache_quantized_params, + sample_kwargs=sample_kwargs, + _order=_order, + _num_layers_per_chunk=_num_layers_per_chunk, + pool=pool, + retain_graph_in_backward=retain_graph_in_backward, + _reuse_graph_input_output_buffers=_reuse_graph_input_output_buffers, + clone_param_grads_on_return=clone_param_grads_on_return, + pre_warmup_hook=pre_warmup_hook, + post_warmup_hook=post_warmup_hook, + capture_time_hooks=capture_time_hooks, + ) + finally: + # Restore capture-owned state even if warmup raises. + for gen, state in zip(generators, original_rng_states): + gen.set_state(state) + for module_cls, old_call in old_call_funcs.items(): + module_cls.__call__ = old_call + restore_fp8_tensors(modules, saved_fp8_tensors) + set_capture_end() return graphed_callables From 22d47275127b64cf9236e708039a7517cfc83e0a Mon Sep 17 00:00:00 2001 From: Pinoeer-kingxi Date: Tue, 24 Nov 2026 03:43:53 -0800 Subject: [PATCH 2/9] Restore CUDA graph setup state and preserve capture errors 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 --- tests/pytorch/test_cuda_graphs.py | 49 ++++++++++++++-- transformer_engine/pytorch/graph.py | 89 ++++++++++++++--------------- 2 files changed, 86 insertions(+), 52 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index 5d51b936bbe..9b03de49012 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -141,7 +141,24 @@ def reset_global_fp8_state(): FP8GlobalStateManager.reset() -def test_warmup_forward_failure_cleanup_and_retry(): +def test_invalid_module_does_not_leave_capture_state(): + from transformer_engine.pytorch import graph as te_graph + + class LocalLinear(torch.nn.Linear): + pass + + module = LocalLinear(8, 8) + original_call = LocalLinear.__call__ + try: + with pytest.raises(TypeError, match="Graphing for"): + make_graphed_callables((module, "not a module"), ((torch.zeros(1, 8),), ())) + assert not te_graph.is_graph_capturing() + assert LocalLinear.__call__ is original_call + finally: + te_graph.set_capture_end() + + +def test_warmup_forward_failure_cleanup_and_retry(monkeypatch): """A failed warmup must leave the module reusable for capture and training.""" from transformer_engine.pytorch import graph as te_graph @@ -158,23 +175,44 @@ def forward(self, inp): raise RuntimeError("controlled warmup forward failure") return output + class InheritedCall(FailDuringWarmup): + pass + model = FailDuringWarmup() + derived = InheritedCall() inp = torch.randn(4, 32, device="cuda", dtype=torch.bfloat16) + modules, sample_args = (model, derived), ((inp,), (inp,)) original_call = type(model).__call__ hooks = [(module, dict(module._forward_hooks)) for module in model.modules()] cpu_rng = torch.get_rng_state() cuda_rng = torch.cuda.get_rng_state() - graphed = None - try: - with pytest.raises(RuntimeError, match="controlled warmup forward failure"): - make_graphed_callables(model, (inp,), num_warmup_iters=1) + + def assert_restored(): for module, original_hooks in hooks: assert module._forward_hooks == original_hooks assert type(model).__call__ is original_call + assert InheritedCall.__call__ is original_call + assert "__call__" not in InheritedCall.__dict__ assert not te_graph.is_graph_capturing() torch.testing.assert_close(torch.get_rng_state(), cpu_rng, rtol=0, atol=0) torch.testing.assert_close(torch.cuda.get_rng_state(), cuda_rng, rtol=0, atol=0) + def fail_fp8_restore(*args): + raise RuntimeError("controlled FP8 restore failure") + + graphed = None + try: + with pytest.raises(RuntimeError, match="controlled warmup forward failure"): + make_graphed_callables(modules, sample_args, num_warmup_iters=1) + assert_restored() + + with monkeypatch.context() as patch: + patch.setattr(te_graph, "restore_fp8_tensors", fail_fp8_restore) + with pytest.raises(RuntimeError, match="controlled warmup forward failure") as error: + make_graphed_callables(modules, sample_args, num_warmup_iters=1) + assert str(error.value.__cause__) == "controlled FP8 restore failure" + assert_restored() + model.fail = False reference = copy.deepcopy(model) reference_input = inp.clone() @@ -192,7 +230,6 @@ def forward(self, inp): finally: if graphed is not None: graphed.reset() - type(model).__call__ = original_call te_graph.set_capture_end() diff --git a/transformer_engine/pytorch/graph.py b/transformer_engine/pytorch/graph.py index 8a7ff292e54..386333bd865 100644 --- a/transformer_engine/pytorch/graph.py +++ b/transformer_engine/pytorch/graph.py @@ -1482,9 +1482,11 @@ def make_graphed_callables( `original PyTorch implementation `_ for more documentation. - If a callable raises during warmup, temporary discovery hooks, saved RNG state, - module call wrappers, and the capture flag are restored before the exception is - re-raised. This cleanup does not make fatal CUDA errors recoverable. + Capture setup and warmup clean up temporary hooks, module call wrappers, + saved RNG and FP8 state, and the capture flag on failure. If cleanup also + raises, the capture exception remains primary and the cleanup error is chained + to it. Capture temporarily changes class dispatch and must be serialized. + Fatal CUDA errors still require restarting the process. .. warning:: @@ -1647,8 +1649,6 @@ def make_graphed_callables( if cache_quantized_params is None: cache_quantized_params = False - set_capture_start() - # Handle single module. just_one_callable = False if not isinstance(modules, tuple): @@ -1678,19 +1678,17 @@ def make_graphed_callables( capture_time_hooks, ) - # Store FP8 tensors to reset later. - saved_fp8_tensors = save_fp8_tensors(modules, recipe=recipe) - - # FP8 wrapper. - old_call_funcs = {} - - def wrap_autocast(block): - block_cls = type(block) - if block_cls in old_call_funcs: - return + # Validate every module before installing any class-wide wrappers. + for module in modules: + if not isinstance(module, torch.nn.Module): + raise TypeError(f"Graphing for {type(module)} is not supported.") - old_call_funcs[block_cls] = block_cls.__call__ + # Resolve inherited calls before any class is patched. + classes = dict.fromkeys(type(module) for module in modules) + original_calls = {cls: cls.__call__ for cls in classes} + cleanup = contextlib.ExitStack() + def wrap_autocast(block_cls, original_call): # Wrap the original call function of the module class. def call_func(self, *args, **kwargs): with autocast( @@ -1700,33 +1698,33 @@ def call_func(self, *args, **kwargs): amax_reduction_group=amax_reduction_group, _graph=True, ): - outputs = old_call_funcs[block_cls](self, *args, **kwargs) - return outputs + return original_call(self, *args, **kwargs) + if "__call__" in block_cls.__dict__: + restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) + else: + restore_call = (delattr, block_cls, "__call__") block_cls.__call__ = call_func + cleanup.callback(*restore_call) - forward_funcs = [] - for module in modules: - if not isinstance(module, torch.nn.Module): - raise TypeError(f"Graphing for {type(module)} is not supported.") - wrap_autocast(module) - forward_funcs.append(module) - - if just_one_callable: - forward_funcs = forward_funcs[0] - else: - forward_funcs = tuple(forward_funcs) - - # Save RNG state. - generators = [ - torch.cuda.default_generators[torch.cuda.current_device()], - *get_all_rng_states().values(), - ] - original_rng_states = [state.get_state() for state in generators] - + set_capture_start() + cleanup.callback(set_capture_end) try: + saved_fp8_tensors = save_fp8_tensors(modules, recipe=recipe) + cleanup.callback(restore_fp8_tensors, modules, saved_fp8_tensors) + for block_cls, original_call in original_calls.items(): + wrap_autocast(block_cls, original_call) + + # Ensures warmup does not affect numerics for ops such as dropout. + generators = [ + torch.cuda.default_generators[torch.cuda.current_device()], + *get_all_rng_states().values(), + ] + for gen in reversed(generators): + cleanup.callback(gen.set_state, gen.get_state()) + graphed_callables = _make_graphed_callables( - forward_funcs, + modules[0] if just_one_callable else modules, sample_args, num_warmup_iters=num_warmup_iters, allow_unused_input=allow_unused_input, @@ -1742,12 +1740,11 @@ def call_func(self, *args, **kwargs): post_warmup_hook=post_warmup_hook, capture_time_hooks=capture_time_hooks, ) - finally: - # Restore capture-owned state even if warmup raises. - for gen, state in zip(generators, original_rng_states): - gen.set_state(state) - for module_cls, old_call in old_call_funcs.items(): - module_cls.__call__ = old_call - restore_fp8_tensors(modules, saved_fp8_tensors) - set_capture_end() + except BaseException as error: + try: + cleanup.close() + except BaseException as cleanup_error: + raise error from cleanup_error + raise + cleanup.close() return graphed_callables From 181dbd517414f83de77c28d88404b134e335cea9 Mon Sep 17 00:00:00 2001 From: Pinoeer-kingxi Date: Tue, 24 Nov 2026 04:08:32 -0800 Subject: [PATCH 3/9] Test eager calibration after successful class-mixed graph capture 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 --- tests/pytorch/test_cuda_graphs.py | 34 +++++++++++++++++++++++-------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index 9b03de49012..44188e4b49f 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -158,6 +158,29 @@ class LocalLinear(torch.nn.Linear): te_graph.set_capture_end() +def test_capture_preserves_eager_calibration_for_subclass(): + """Capturing a base and derived layer must preserve later eager calibration.""" + + class DerivedLinear(Linear): + pass + + kwargs = dict(params_dtype=torch.bfloat16, device="cuda") + modules = (Linear(32, 32, **kwargs), DerivedLinear(32, 32, **kwargs)) + inp = torch.randn(8, 32, device="cuda", dtype=torch.bfloat16) + graphs = make_graphed_callables(modules, ((inp,), (inp,)), num_warmup_iters=1) + try: + for graph in graphs: + graph(inp).sum().backward() + finally: + for graph in graphs: + graph.reset() + + eager = DerivedLinear(32, 32, **kwargs) + with autocast(enabled=False, calibrating=True, recipe=recipe.DelayedScaling()): + eager(inp) + assert eager.fp8_calibration + + def test_warmup_forward_failure_cleanup_and_retry(monkeypatch): """A failed warmup must leave the module reusable for capture and training.""" from transformer_engine.pytorch import graph as te_graph @@ -175,13 +198,8 @@ def forward(self, inp): raise RuntimeError("controlled warmup forward failure") return output - class InheritedCall(FailDuringWarmup): - pass - model = FailDuringWarmup() - derived = InheritedCall() inp = torch.randn(4, 32, device="cuda", dtype=torch.bfloat16) - modules, sample_args = (model, derived), ((inp,), (inp,)) original_call = type(model).__call__ hooks = [(module, dict(module._forward_hooks)) for module in model.modules()] cpu_rng = torch.get_rng_state() @@ -191,8 +209,6 @@ def assert_restored(): for module, original_hooks in hooks: assert module._forward_hooks == original_hooks assert type(model).__call__ is original_call - assert InheritedCall.__call__ is original_call - assert "__call__" not in InheritedCall.__dict__ assert not te_graph.is_graph_capturing() torch.testing.assert_close(torch.get_rng_state(), cpu_rng, rtol=0, atol=0) torch.testing.assert_close(torch.cuda.get_rng_state(), cuda_rng, rtol=0, atol=0) @@ -203,13 +219,13 @@ def fail_fp8_restore(*args): graphed = None try: with pytest.raises(RuntimeError, match="controlled warmup forward failure"): - make_graphed_callables(modules, sample_args, num_warmup_iters=1) + make_graphed_callables(model, (inp,), num_warmup_iters=1) assert_restored() with monkeypatch.context() as patch: patch.setattr(te_graph, "restore_fp8_tensors", fail_fp8_restore) with pytest.raises(RuntimeError, match="controlled warmup forward failure") as error: - make_graphed_callables(modules, sample_args, num_warmup_iters=1) + make_graphed_callables(model, (inp,), num_warmup_iters=1) assert str(error.value.__cause__) == "controlled FP8 restore failure" assert_restored() From a642d9c490b8c6f99603eb2703cfd06a01d7d96d Mon Sep 17 00:00:00 2001 From: Pawel Gadzinski Date: Wed, 25 Nov 2026 18:11:46 +0100 Subject: [PATCH 4/9] Remove verbose cleanup note from make_graphed_callables docstring Signed-off-by: Pawel Gadzinski --- transformer_engine/pytorch/graph.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/transformer_engine/pytorch/graph.py b/transformer_engine/pytorch/graph.py index 386333bd865..34f4f4e21bf 100644 --- a/transformer_engine/pytorch/graph.py +++ b/transformer_engine/pytorch/graph.py @@ -1482,12 +1482,6 @@ def make_graphed_callables( `original PyTorch implementation `_ for more documentation. - Capture setup and warmup clean up temporary hooks, module call wrappers, - saved RNG and FP8 state, and the capture flag on failure. If cleanup also - raises, the capture exception remains primary and the cleanup error is chained - to it. Capture temporarily changes class dispatch and must be serialized. - Fatal CUDA errors still require restarting the process. - .. warning:: Arguments 'fp8_enabled', 'fp8_calibrating', 'fp8_recipe', 'fp8_group', and 'fp8_weight_caching' are deprecated. From b2328fd986172cb932234d669c9f6a24ba1e5f8c Mon Sep 17 00:00:00 2001 From: Pawel Gadzinski Date: Fri, 27 Nov 2026 11:54:20 +0100 Subject: [PATCH 5/9] Remove verbose warmup failure retry test Signed-off-by: Pawel Gadzinski --- tests/pytorch/test_cuda_graphs.py | 68 ------------------------------- 1 file changed, 68 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index 44188e4b49f..7ae8fa6dd51 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -181,74 +181,6 @@ class DerivedLinear(Linear): assert eager.fp8_calibration -def test_warmup_forward_failure_cleanup_and_retry(monkeypatch): - """A failed warmup must leave the module reusable for capture and training.""" - from transformer_engine.pytorch import graph as te_graph - - class FailDuringWarmup(torch.nn.Module): - def __init__(self): - super().__init__() - self.linear = torch.nn.Linear(32, 32, dtype=torch.bfloat16, device="cuda") - self.dropout = torch.nn.Dropout(0.1) - self.fail = True - - def forward(self, inp): - output = self.dropout(self.linear(inp)) - if self.fail: - raise RuntimeError("controlled warmup forward failure") - return output - - model = FailDuringWarmup() - inp = torch.randn(4, 32, device="cuda", dtype=torch.bfloat16) - original_call = type(model).__call__ - hooks = [(module, dict(module._forward_hooks)) for module in model.modules()] - cpu_rng = torch.get_rng_state() - cuda_rng = torch.cuda.get_rng_state() - - def assert_restored(): - for module, original_hooks in hooks: - assert module._forward_hooks == original_hooks - assert type(model).__call__ is original_call - assert not te_graph.is_graph_capturing() - torch.testing.assert_close(torch.get_rng_state(), cpu_rng, rtol=0, atol=0) - torch.testing.assert_close(torch.cuda.get_rng_state(), cuda_rng, rtol=0, atol=0) - - def fail_fp8_restore(*args): - raise RuntimeError("controlled FP8 restore failure") - - graphed = None - try: - with pytest.raises(RuntimeError, match="controlled warmup forward failure"): - make_graphed_callables(model, (inp,), num_warmup_iters=1) - assert_restored() - - with monkeypatch.context() as patch: - patch.setattr(te_graph, "restore_fp8_tensors", fail_fp8_restore) - with pytest.raises(RuntimeError, match="controlled warmup forward failure") as error: - make_graphed_callables(model, (inp,), num_warmup_iters=1) - assert str(error.value.__cause__) == "controlled FP8 restore failure" - assert_restored() - - model.fail = False - reference = copy.deepcopy(model) - reference_input = inp.clone() - rng = torch.cuda.get_rng_state() - expected = reference(reference_input) - expected.sum().backward() - expected_parameter_grads = [p.grad.clone() for p in reference.parameters()] - torch.cuda.set_rng_state(rng) - graphed = make_graphed_callables(model, (inp,), num_warmup_iters=1) - actual = graphed(inp) - actual.sum().backward() - torch.testing.assert_close(actual, expected, rtol=0, atol=0) - for parameter, expected_grad in zip(model.parameters(), expected_parameter_grads): - torch.testing.assert_close(parameter.grad, expected_grad, rtol=0, atol=0) - finally: - if graphed is not None: - graphed.reset() - te_graph.set_capture_end() - - def assert_all_equal(l1: List[torch.Tensor], l2: List[torch.Tensor], names=None) -> bool: """Check that two lists of tensors match exactly.""" assert len(l1) == len(l2), "Unequal number of outputs." From 141cb316344f8adf5e0db12101ea7889b54142e8 Mon Sep 17 00:00:00 2001 From: Pawel Gadzinski Date: Fri, 27 Nov 2026 11:54:54 +0100 Subject: [PATCH 6/9] Remove invalid module capture state test Signed-off-by: Pawel Gadzinski --- tests/pytorch/test_cuda_graphs.py | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index 7ae8fa6dd51..ec490f882a2 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -141,23 +141,6 @@ def reset_global_fp8_state(): FP8GlobalStateManager.reset() -def test_invalid_module_does_not_leave_capture_state(): - from transformer_engine.pytorch import graph as te_graph - - class LocalLinear(torch.nn.Linear): - pass - - module = LocalLinear(8, 8) - original_call = LocalLinear.__call__ - try: - with pytest.raises(TypeError, match="Graphing for"): - make_graphed_callables((module, "not a module"), ((torch.zeros(1, 8),), ())) - assert not te_graph.is_graph_capturing() - assert LocalLinear.__call__ is original_call - finally: - te_graph.set_capture_end() - - def test_capture_preserves_eager_calibration_for_subclass(): """Capturing a base and derived layer must preserve later eager calibration.""" From 7a895dcdedc5165f095fc776db7a6b5fff1fe197 Mon Sep 17 00:00:00 2001 From: Pawel Gadzinski Date: Fri, 27 Nov 2026 12:16:31 +0100 Subject: [PATCH 7/9] Simplify ExitStack cleanup and fix remaining failure-path leaks Signed-off-by: Pawel Gadzinski --- transformer_engine/pytorch/graph.py | 78 ++++++++++++++--------------- 1 file changed, 39 insertions(+), 39 deletions(-) diff --git a/transformer_engine/pytorch/graph.py b/transformer_engine/pytorch/graph.py index 34f4f4e21bf..86280ec2cfa 100644 --- a/transformer_engine/pytorch/graph.py +++ b/transformer_engine/pytorch/graph.py @@ -86,9 +86,11 @@ def _none_grad_context_wrapper(inputs): for input_tensor in inputs: original_input_grads.append(input_tensor.grad) input_tensor.grad = None - yield - for input_tensor, original_grad in zip(inputs, original_input_grads): - input_tensor.grad = original_grad + try: + yield + finally: + for input_tensor, original_grad in zip(inputs, original_input_grads): + input_tensor.grad = original_grad @contextlib.contextmanager @@ -104,10 +106,12 @@ def _graph_context_wrapper(*args, **kwargs): gc_is_enabled = gc.isenabled() if gc_is_enabled: gc.disable() - with torch.cuda.graph(*args, **kwargs): - yield - if gc_is_enabled: - gc.enable() + try: + with torch.cuda.graph(*args, **kwargs): + yield + finally: + if gc_is_enabled: + gc.enable() def _canonicalize_capture_time_hooks( @@ -651,7 +655,11 @@ def _run_warmup_backward(func_idx, func, outputs, warmup_iter, callable_idx): need_bwd_dw_graph[func_idx] = need_backward_dw # Run warmup and do the above filtering. - with torch.cuda.stream(torch.cuda.Stream()): + warmup_stream = torch.cuda.Stream() + caller_stream = torch.cuda.current_stream() + with contextlib.ExitStack() as warmup_cleanup: + warmup_cleanup.callback(caller_stream.wait_stream, warmup_stream) + warmup_cleanup.enter_context(torch.cuda.stream(warmup_stream)) if pre_warmup_hook is not None: pre_warmup_hook() @@ -1680,30 +1688,30 @@ def make_graphed_callables( # Resolve inherited calls before any class is patched. classes = dict.fromkeys(type(module) for module in modules) original_calls = {cls: cls.__call__ for cls in classes} - cleanup = contextlib.ExitStack() - - def wrap_autocast(block_cls, original_call): - # Wrap the original call function of the module class. - def call_func(self, *args, **kwargs): - with autocast( - enabled=module_uses_fp8.get(id(self), False), - calibrating=calibrating, - recipe=recipe, - amax_reduction_group=amax_reduction_group, - _graph=True, - ): - return original_call(self, *args, **kwargs) - if "__call__" in block_cls.__dict__: - restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) - else: - restore_call = (delattr, block_cls, "__call__") - block_cls.__call__ = call_func - cleanup.callback(*restore_call) + with contextlib.ExitStack() as cleanup: + + def wrap_autocast(block_cls, original_call): + # Wrap the original call function of the module class. + def call_func(self, *args, **kwargs): + with autocast( + enabled=module_uses_fp8.get(id(self), False), + calibrating=calibrating, + recipe=recipe, + amax_reduction_group=amax_reduction_group, + _graph=True, + ): + return original_call(self, *args, **kwargs) - set_capture_start() - cleanup.callback(set_capture_end) - try: + if "__call__" in block_cls.__dict__: + restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) + else: + restore_call = (delattr, block_cls, "__call__") + block_cls.__call__ = call_func + cleanup.callback(*restore_call) + + set_capture_start() + cleanup.callback(set_capture_end) saved_fp8_tensors = save_fp8_tensors(modules, recipe=recipe) cleanup.callback(restore_fp8_tensors, modules, saved_fp8_tensors) for block_cls, original_call in original_calls.items(): @@ -1717,7 +1725,7 @@ def call_func(self, *args, **kwargs): for gen in reversed(generators): cleanup.callback(gen.set_state, gen.get_state()) - graphed_callables = _make_graphed_callables( + return _make_graphed_callables( modules[0] if just_one_callable else modules, sample_args, num_warmup_iters=num_warmup_iters, @@ -1734,11 +1742,3 @@ def call_func(self, *args, **kwargs): post_warmup_hook=post_warmup_hook, capture_time_hooks=capture_time_hooks, ) - except BaseException as error: - try: - cleanup.close() - except BaseException as cleanup_error: - raise error from cleanup_error - raise - cleanup.close() - return graphed_callables From 9c1e9c0a323a7930f451d943c238f022738ec985 Mon Sep 17 00:00:00 2001 From: Pinoeer-kingxi Date: Fri, 27 Nov 2026 03:47:59 -0800 Subject: [PATCH 8/9] Preserve CUDA graph capture errors during cleanup 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 --- tests/pytorch/test_cuda_graphs.py | 67 +++++++++++++++++++++++++++++ transformer_engine/pytorch/graph.py | 51 +++++++++++++--------- 2 files changed, 97 insertions(+), 21 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index ec490f882a2..9c197daef34 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -164,6 +164,73 @@ class DerivedLinear(Linear): assert eager.fp8_calibration +def test_invalid_module_does_not_leave_capture_state(): + from transformer_engine.pytorch import graph as te_graph + + class LocalLinear(torch.nn.Linear): + pass + + model = LocalLinear(8, 8) + original_call = LocalLinear.__call__ + with pytest.raises(TypeError, match="Graphing for"): + make_graphed_callables((model, None), ((torch.zeros(1, 8),), ())) + assert LocalLinear.__call__ is original_call + assert not te_graph.is_graph_capturing() + + +@pytest.mark.parametrize("cleanup_fails", (False, True), ids=("retry", "cleanup-error")) +def test_warmup_failure_restores_capture_state(monkeypatch, cleanup_fails): + from transformer_engine.pytorch import graph as te_graph + + class WarmupLinear(torch.nn.Linear): + fail_warmup = True + + def forward(self, inp): + output = super().forward(inp) + if self.fail_warmup: + torch.rand(1, device=inp.device) + raise RuntimeError("warmup forward failed") + return output + + def fail_restore(*_): + raise ValueError("FP8 restore failed") + + model = WarmupLinear(32, 32, dtype=torch.bfloat16, device="cuda") + inp = torch.randn(4, 32, dtype=torch.bfloat16, device="cuda") + rng = torch.cuda.get_rng_state() + original_call = WarmupLinear.__call__ + + with monkeypatch.context() as patch: + if cleanup_fails: + patch.setattr(te_graph, "restore_fp8_tensors", fail_restore) + with pytest.raises(RuntimeError, match="warmup forward failed") as error: + make_graphed_callables(model, (inp,), num_warmup_iters=1) + assert not model._forward_hooks + assert WarmupLinear.__call__ is original_call + assert not te_graph.is_graph_capturing() + assert torch.equal(torch.cuda.get_rng_state(), rng) + if cleanup_fails: + assert isinstance(error.value.__cause__, ValueError) + assert str(error.value.__cause__) == "FP8 restore failed" + return + + model.fail_warmup = False + expected = model(inp) + expected.sum().backward() + expected_grads = [param.grad for param in model.parameters()] + model.zero_grad(set_to_none=True) + graphed = make_graphed_callables(model, (inp,), num_warmup_iters=1) + try: + actual = graphed(inp) + actual.sum().backward() + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + torch.testing.assert_close( + [param.grad for param in model.parameters()], expected_grads, rtol=0, atol=0 + ) + finally: + graphed.reset() + + def assert_all_equal(l1: List[torch.Tensor], l2: List[torch.Tensor], names=None) -> bool: """Check that two lists of tensors match exactly.""" assert len(l1) == len(l2), "Unequal number of outputs." diff --git a/transformer_engine/pytorch/graph.py b/transformer_engine/pytorch/graph.py index 86280ec2cfa..0e4338d15b2 100644 --- a/transformer_engine/pytorch/graph.py +++ b/transformer_engine/pytorch/graph.py @@ -1688,28 +1688,29 @@ def make_graphed_callables( # Resolve inherited calls before any class is patched. classes = dict.fromkeys(type(module) for module in modules) original_calls = {cls: cls.__call__ for cls in classes} + # Close explicitly so a cleanup failure cannot replace the capture error. + cleanup = contextlib.ExitStack() + + def wrap_autocast(block_cls, original_call): + # Wrap the original call function of the module class. + def call_func(self, *args, **kwargs): + with autocast( + enabled=module_uses_fp8.get(id(self), False), + calibrating=calibrating, + recipe=recipe, + amax_reduction_group=amax_reduction_group, + _graph=True, + ): + return original_call(self, *args, **kwargs) - with contextlib.ExitStack() as cleanup: - - def wrap_autocast(block_cls, original_call): - # Wrap the original call function of the module class. - def call_func(self, *args, **kwargs): - with autocast( - enabled=module_uses_fp8.get(id(self), False), - calibrating=calibrating, - recipe=recipe, - amax_reduction_group=amax_reduction_group, - _graph=True, - ): - return original_call(self, *args, **kwargs) - - if "__call__" in block_cls.__dict__: - restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) - else: - restore_call = (delattr, block_cls, "__call__") - block_cls.__call__ = call_func - cleanup.callback(*restore_call) + if "__call__" in block_cls.__dict__: + restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) + else: + restore_call = (delattr, block_cls, "__call__") + block_cls.__call__ = call_func + cleanup.callback(*restore_call) + try: set_capture_start() cleanup.callback(set_capture_end) saved_fp8_tensors = save_fp8_tensors(modules, recipe=recipe) @@ -1725,7 +1726,7 @@ def call_func(self, *args, **kwargs): for gen in reversed(generators): cleanup.callback(gen.set_state, gen.get_state()) - return _make_graphed_callables( + graphed_callables = _make_graphed_callables( modules[0] if just_one_callable else modules, sample_args, num_warmup_iters=num_warmup_iters, @@ -1742,3 +1743,11 @@ def call_func(self, *args, **kwargs): post_warmup_hook=post_warmup_hook, capture_time_hooks=capture_time_hooks, ) + except BaseException as error: + try: + cleanup.close() + except BaseException as cleanup_error: + raise error from cleanup_error + raise + cleanup.close() + return graphed_callables From a1ccd337d186ef0f8df8dc7bd1a2b0206de97abc Mon Sep 17 00:00:00 2001 From: Pawel Gadzinski Date: Fri, 27 Nov 2026 14:51:16 +0100 Subject: [PATCH 9/9] Revert "Preserve CUDA graph capture errors during cleanup" This reverts commit 9c1e9c0a323a7930f451d943c238f022738ec985. Signed-off-by: Pawel Gadzinski --- tests/pytorch/test_cuda_graphs.py | 67 ----------------------------- transformer_engine/pytorch/graph.py | 51 +++++++++------------- 2 files changed, 21 insertions(+), 97 deletions(-) diff --git a/tests/pytorch/test_cuda_graphs.py b/tests/pytorch/test_cuda_graphs.py index 9c197daef34..ec490f882a2 100644 --- a/tests/pytorch/test_cuda_graphs.py +++ b/tests/pytorch/test_cuda_graphs.py @@ -164,73 +164,6 @@ class DerivedLinear(Linear): assert eager.fp8_calibration -def test_invalid_module_does_not_leave_capture_state(): - from transformer_engine.pytorch import graph as te_graph - - class LocalLinear(torch.nn.Linear): - pass - - model = LocalLinear(8, 8) - original_call = LocalLinear.__call__ - with pytest.raises(TypeError, match="Graphing for"): - make_graphed_callables((model, None), ((torch.zeros(1, 8),), ())) - assert LocalLinear.__call__ is original_call - assert not te_graph.is_graph_capturing() - - -@pytest.mark.parametrize("cleanup_fails", (False, True), ids=("retry", "cleanup-error")) -def test_warmup_failure_restores_capture_state(monkeypatch, cleanup_fails): - from transformer_engine.pytorch import graph as te_graph - - class WarmupLinear(torch.nn.Linear): - fail_warmup = True - - def forward(self, inp): - output = super().forward(inp) - if self.fail_warmup: - torch.rand(1, device=inp.device) - raise RuntimeError("warmup forward failed") - return output - - def fail_restore(*_): - raise ValueError("FP8 restore failed") - - model = WarmupLinear(32, 32, dtype=torch.bfloat16, device="cuda") - inp = torch.randn(4, 32, dtype=torch.bfloat16, device="cuda") - rng = torch.cuda.get_rng_state() - original_call = WarmupLinear.__call__ - - with monkeypatch.context() as patch: - if cleanup_fails: - patch.setattr(te_graph, "restore_fp8_tensors", fail_restore) - with pytest.raises(RuntimeError, match="warmup forward failed") as error: - make_graphed_callables(model, (inp,), num_warmup_iters=1) - assert not model._forward_hooks - assert WarmupLinear.__call__ is original_call - assert not te_graph.is_graph_capturing() - assert torch.equal(torch.cuda.get_rng_state(), rng) - if cleanup_fails: - assert isinstance(error.value.__cause__, ValueError) - assert str(error.value.__cause__) == "FP8 restore failed" - return - - model.fail_warmup = False - expected = model(inp) - expected.sum().backward() - expected_grads = [param.grad for param in model.parameters()] - model.zero_grad(set_to_none=True) - graphed = make_graphed_callables(model, (inp,), num_warmup_iters=1) - try: - actual = graphed(inp) - actual.sum().backward() - torch.testing.assert_close(actual, expected, rtol=0, atol=0) - torch.testing.assert_close( - [param.grad for param in model.parameters()], expected_grads, rtol=0, atol=0 - ) - finally: - graphed.reset() - - def assert_all_equal(l1: List[torch.Tensor], l2: List[torch.Tensor], names=None) -> bool: """Check that two lists of tensors match exactly.""" assert len(l1) == len(l2), "Unequal number of outputs." diff --git a/transformer_engine/pytorch/graph.py b/transformer_engine/pytorch/graph.py index 0e4338d15b2..86280ec2cfa 100644 --- a/transformer_engine/pytorch/graph.py +++ b/transformer_engine/pytorch/graph.py @@ -1688,29 +1688,28 @@ def make_graphed_callables( # Resolve inherited calls before any class is patched. classes = dict.fromkeys(type(module) for module in modules) original_calls = {cls: cls.__call__ for cls in classes} - # Close explicitly so a cleanup failure cannot replace the capture error. - cleanup = contextlib.ExitStack() - - def wrap_autocast(block_cls, original_call): - # Wrap the original call function of the module class. - def call_func(self, *args, **kwargs): - with autocast( - enabled=module_uses_fp8.get(id(self), False), - calibrating=calibrating, - recipe=recipe, - amax_reduction_group=amax_reduction_group, - _graph=True, - ): - return original_call(self, *args, **kwargs) - if "__call__" in block_cls.__dict__: - restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) - else: - restore_call = (delattr, block_cls, "__call__") - block_cls.__call__ = call_func - cleanup.callback(*restore_call) + with contextlib.ExitStack() as cleanup: + + def wrap_autocast(block_cls, original_call): + # Wrap the original call function of the module class. + def call_func(self, *args, **kwargs): + with autocast( + enabled=module_uses_fp8.get(id(self), False), + calibrating=calibrating, + recipe=recipe, + amax_reduction_group=amax_reduction_group, + _graph=True, + ): + return original_call(self, *args, **kwargs) + + if "__call__" in block_cls.__dict__: + restore_call = (setattr, block_cls, "__call__", block_cls.__dict__["__call__"]) + else: + restore_call = (delattr, block_cls, "__call__") + block_cls.__call__ = call_func + cleanup.callback(*restore_call) - try: set_capture_start() cleanup.callback(set_capture_end) saved_fp8_tensors = save_fp8_tensors(modules, recipe=recipe) @@ -1726,7 +1725,7 @@ def call_func(self, *args, **kwargs): for gen in reversed(generators): cleanup.callback(gen.set_state, gen.get_state()) - graphed_callables = _make_graphed_callables( + return _make_graphed_callables( modules[0] if just_one_callable else modules, sample_args, num_warmup_iters=num_warmup_iters, @@ -1743,11 +1742,3 @@ def call_func(self, *args, **kwargs): post_warmup_hook=post_warmup_hook, capture_time_hooks=capture_time_hooks, ) - except BaseException as error: - try: - cleanup.close() - except BaseException as cleanup_error: - raise error from cleanup_error - raise - cleanup.close() - return graphed_callables