|
| 1 | +# Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. |
| 2 | + |
| 3 | +from unittest.mock import Mock, patch |
| 4 | + |
| 5 | +import pytest |
| 6 | +import torch |
| 7 | + |
| 8 | +from megatron.core.full_cuda_graph import FullCudaGraphWrapper |
| 9 | +from megatron.core.rerun_state_machine import ( |
| 10 | + EXIT_CODE_FAILED_ON_RESULT_VALIDATION, |
| 11 | + EXIT_CODE_RESUME_TO_DISAMBIGUATE, |
| 12 | + RerunMode, |
| 13 | + RerunState, |
| 14 | + RerunStateMachine, |
| 15 | +) |
| 16 | +from tests.unit_tests.test_utilities import Utils |
| 17 | + |
| 18 | + |
| 19 | +@pytest.mark.parametrize( |
| 20 | + "bad_value,rejection", [(float("nan"), torch.isnan), (float("inf"), torch.isinf)] |
| 21 | +) |
| 22 | +@pytest.mark.parametrize("mode", [RerunMode.DISABLED, RerunMode.VALIDATE_RESULTS]) |
| 23 | +@pytest.mark.parametrize("reproduced", [False, True]) |
| 24 | +def test_full_cuda_graph_validates_current_replay_before_optimizer( |
| 25 | + bad_value, rejection, mode, reproduced |
| 26 | +): |
| 27 | + """Replay failures reach rerun decisions without overwriting the retained failed result.""" |
| 28 | + Utils.initialize_model_parallel(tensor_model_parallel_size=1, pipeline_model_parallel_size=1) |
| 29 | + machine = RerunStateMachine(mode=mode) |
| 30 | + source = torch.ones((), device="cuda") |
| 31 | + |
| 32 | + def forward_backward_func(**_): |
| 33 | + intermediate = source.clone() |
| 34 | + machine.validate_result(intermediate, rejection, "captured local norm", fatal=True) |
| 35 | + # A reference without a capture-time snapshot would lose the invalid value. |
| 36 | + intermediate.zero_() |
| 37 | + return [{"loss": intermediate}] |
| 38 | + |
| 39 | + wrapper = FullCudaGraphWrapper(forward_backward_func, cuda_graph_warmup_steps=1) |
| 40 | + kwargs = dict( |
| 41 | + model=[torch.nn.Identity()], |
| 42 | + data_iterator=None, |
| 43 | + num_microbatches=1, |
| 44 | + seq_length=1, |
| 45 | + forward_only=False, |
| 46 | + ) |
| 47 | + with ( |
| 48 | + patch("megatron.core.full_cuda_graph.get_all_rng_states", return_value={}), |
| 49 | + patch("megatron.core.full_cuda_graph.get_rerun_state_machine", return_value=machine), |
| 50 | + ): |
| 51 | + wrapper.reset_cuda_graph() |
| 52 | + try: |
| 53 | + # Complete a healthy warmup step, then capture and replay another step. |
| 54 | + for _ in range(2): |
| 55 | + assert machine.should_run_forward_backward(None) |
| 56 | + wrapper(**kwargs) |
| 57 | + assert not machine.should_run_forward_backward(None) |
| 58 | + assert machine.should_checkpoint_and_exit() == (False, False, 0) |
| 59 | + |
| 60 | + source.fill_(bad_value) |
| 61 | + assert machine.should_run_forward_backward(None) |
| 62 | + if mode == RerunMode.DISABLED: |
| 63 | + with pytest.raises(RuntimeError, match="captured local norm"): |
| 64 | + wrapper(**kwargs) |
| 65 | + return |
| 66 | + |
| 67 | + wrapper(**kwargs) |
| 68 | + assert machine.rerun_requested |
| 69 | + assert rejection(machine.initial_result) |
| 70 | + assert machine.should_run_forward_backward(None) |
| 71 | + assert machine.state == RerunState.RERUNNING_IN_PLACE |
| 72 | + |
| 73 | + source.fill_(bad_value if reproduced else 2.0) |
| 74 | + wrapper(**kwargs) |
| 75 | + assert rejection(machine.initial_result), "Replay overwrote saved failed result" |
| 76 | + assert not machine.should_run_forward_backward(None) |
| 77 | + if reproduced: |
| 78 | + assert machine.state == RerunState.WILL_RERUN_FROM_CHECKPOINT |
| 79 | + assert machine.should_checkpoint_and_exit() == ( |
| 80 | + True, |
| 81 | + True, |
| 82 | + EXIT_CODE_RESUME_TO_DISAMBIGUATE, |
| 83 | + ) |
| 84 | + else: |
| 85 | + assert machine.state == RerunState.RERUNNING_IN_PLACE |
| 86 | + assert machine.should_checkpoint_and_exit() == ( |
| 87 | + False, |
| 88 | + True, |
| 89 | + EXIT_CODE_FAILED_ON_RESULT_VALIDATION, |
| 90 | + ) |
| 91 | + finally: |
| 92 | + wrapper.reset_cuda_graph() |
| 93 | + # Reset must remove callbacks as well as the CUDA graph itself. |
| 94 | + with patch.object(machine, "validate_result") as validate: |
| 95 | + machine.run_deferred_validations("training") |
| 96 | + validate.assert_not_called() |
| 97 | + Utils.destroy_model_parallel() |
| 98 | + |
| 99 | + |
| 100 | +def test_deferred_validations_are_replaced_and_cleared_per_graph(): |
| 101 | + """Recapture replaces one graph's checks, and reset preserves the other graph's checks.""" |
| 102 | + machine = RerunStateMachine(mode=RerunMode.DISABLED) |
| 103 | + reject = Mock(return_value=False) |
| 104 | + for key, value in [("training", 1.0), ("validation", 2.0), ("training", 3.0)]: |
| 105 | + with machine.capture_deferred_validations(key): |
| 106 | + machine.validate_result(torch.tensor(value, device="cuda"), reject, key) |
| 107 | + reject.assert_not_called() |
| 108 | + machine.run_deferred_validations("training") |
| 109 | + reject.assert_called_once() |
| 110 | + assert reject.call_args.args[0].item() == 3.0 |
| 111 | + |
| 112 | + wrapper = FullCudaGraphWrapper(lambda **_: None) |
| 113 | + with patch("megatron.core.full_cuda_graph.get_rerun_state_machine", return_value=machine): |
| 114 | + wrapper.reset_cuda_graph("training") |
| 115 | + machine.run_deferred_validations("training") |
| 116 | + reject.assert_called_once() |
| 117 | + machine.run_deferred_validations("validation") |
| 118 | + assert reject.call_count == 2 |
| 119 | + assert reject.call_args.args[0].item() == 2.0 |
| 120 | + wrapper.reset_cuda_graph() |
| 121 | + machine.run_deferred_validations("validation") |
| 122 | + assert reject.call_count == 2 |
| 123 | + |
| 124 | + |
| 125 | +def test_validation_capture_restores_state_after_error(): |
| 126 | + """A failed capture must discard partial checks and restore immediate validation.""" |
| 127 | + machine = RerunStateMachine(mode=RerunMode.DISABLED) |
| 128 | + reject = Mock(return_value=False) |
| 129 | + with pytest.raises(RuntimeError, match="cannot be nested"): |
| 130 | + with machine.capture_deferred_validations("training"): |
| 131 | + machine.validate_result(torch.ones((), device="cuda"), reject, "partial capture") |
| 132 | + with machine.capture_deferred_validations("validation"): |
| 133 | + pass |
| 134 | + machine.run_deferred_validations("training") |
| 135 | + reject.assert_not_called() |
| 136 | + with machine.capture_deferred_validations("training"): |
| 137 | + pass |
| 138 | + with pytest.raises(RuntimeError, match="eager NaN"): |
| 139 | + machine.validate_result(torch.tensor(float("nan")), torch.isnan, "eager NaN") |
| 140 | + |
| 141 | + |
| 142 | +def test_validation_capture_rejects_host_results(): |
| 143 | + """Host values cannot reflect updates made by graph replay.""" |
| 144 | + machine = RerunStateMachine(mode=RerunMode.DISABLED) |
| 145 | + with machine.capture_deferred_validations("training"): |
| 146 | + with pytest.raises(TypeError, match="CUDA tensor"): |
| 147 | + machine.validate_result(torch.tensor(1.0), torch.isnan, "host result") |
0 commit comments