Open
[fix] 补齐 ebdfc8c 升级后的 TorchFT 初始化与故障 step 生命周期 #1210
[fix] 补齐 ebdfc8c 升级后的 TorchFT 初始化与故障 step 生命周期 #1210
Open
zhangyifan999Add on 27 days ago
Total: 11 files changed+210-63
@@ -695,7 +695,7 @@ def test_config_manager_preserves_recipe_optimizer_type_and_fields(monkeypatch,
695 695 
696 696 
697@pytest.mark.parametrize("detector", ["typed", "native"])697@pytest.mark.parametrize("detector", ["typed", "native"])
698-def test_config_manager_rejects_sdc_detection_with_replay(monkeypatch, tmp_path, detector):698+def test_config_manager_rejects_sdc_detection_with_replay(monkeypatch, tmp_path, capsys, detector):
699 monkeypatch.setenv("NPU_ASD_CONFIG", "enable:false")699 monkeypatch.setenv("NPU_ASD_CONFIG", "enable:false")
700 monkeypatch.setenv("NPU_ASD_ENABLE", "1" if detector == "native" else "0")700 monkeypatch.setenv("NPU_ASD_ENABLE", "1" if detector == "native" else "0")
701 source = Trainer.Config(701 source = Trainer.Config(
@@ -711,8 +711,15 @@ def test_config_manager_rejects_sdc_detection_with_replay(monkeypatch, tmp_path,
711 args.append("--sdc.gradient-enabled")711 args.append("--sdc.gradient-enabled")
712 712 
713 diagnostic = "config.sdc detection" if detector == "typed" else "SDC replay requires native SDC disabled"713 diagnostic = "config.sdc detection" if detector == "typed" else "SDC replay requires native SDC disabled"
714- with pytest.raises(ValueError, match=diagnostic):714+ with pytest.raises((ValueError, SystemExit)) as raised:
715 ConfigManager().parse_args(args)715 ConfigManager().parse_args(args)
716+ if isinstance(raised.value, SystemExit):
717+ # Tyro reports errors raised during CLI instantiation through stderr.
718+ assert raised.value.code == 2
719+ message = " ".join(capsys.readouterr().err.replace("\u2502", " ").split())
720+ else:
721+ message = str(raised.value)
722+ assert diagnostic in message
716 723 
717 724 
718@pytest.mark.parametrize("replay_enabled", [False, True], ids=("detector-only", "replay-only"))725@pytest.mark.parametrize("replay_enabled", [False, True], ids=("detector-only", "replay-only"))
@@ -1,12 +1,18 @@
1# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.1# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2# This source code is licensed under the BSD-style license found in LICENSE.2# This source code is licensed under the BSD-style license found in LICENSE.
3 3 
4+from types import SimpleNamespace
4from unittest.mock import Mock5from unittest.mock import Mock
5 6 
6import pytest7import pytest
8+import torch
7 9 
8from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import TorchFTCommitTimeoutError10from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import TorchFTCommitTimeoutError
9from torchtitan_npu.extensions.torchtitan.experiments.torchft.recovery import step_recovery11from torchtitan_npu.extensions.torchtitan.experiments.torchft.recovery import step_recovery
12+from torchtitan_npu.extensions.torchtitan.experiments.torchft.trainer import (
13+ FaultTolerantTrainerEx,
14+ FaultTolerantTrainingEngineEx,
15+)
10 16 
11 17 
12def test_device_recovery_discards_attempt_without_loading_training_state(monkeypatch):18def test_device_recovery_discards_attempt_without_loading_training_state(monkeypatch):
@@ -15,9 +21,11 @@ def test_device_recovery_discards_attempt_without_loading_training_state(monkeyp
15 hccl.recover.side_effect = lambda _: events.append("device restarted") or True21 hccl.recover.side_effect = lambda _: events.append("device restarted") or True
16 manager = Mock()22 manager = Mock()
17 manager.discard_interrupted_step.side_effect = lambda _: events.append("attempt discarded")23 manager.discard_interrupted_step.side_effect = lambda _: events.append("attempt discarded")
18- state = Mock()24+ state = object.__new__(FaultTolerantTrainingEngineEx)
19- state.state_dict.return_value = {"step": 1}25+ state.num_completed_steps = 14
20- schedulers = Mock()26+ state.ntokens_seen = 0
27+ state.optim = Mock()
28+ state.load_state_dict = Mock()
21 monkeypatch.setattr(step_recovery, "reset_failed_iteration", lambda _: events.append("iteration reset"))29 monkeypatch.setattr(step_recovery, "reset_failed_iteration", lambda _: events.append("iteration reset"))
22 monkeypatch.setattr(step_recovery.torch_npu.npu, "empty_cache", lambda: events.append("cache released"))30 monkeypatch.setattr(step_recovery.torch_npu.npu, "empty_cache", lambda: events.append("cache released"))
23 recovery = step_recovery.StepRecovery(31 recovery = step_recovery.StepRecovery(
@@ -25,7 +33,7 @@ def test_device_recovery_discards_attempt_without_loading_training_state(monkeyp
25 manager=manager,33 manager=manager,
26 model_parts=[],34 model_parts=[],
27 train_state=state,35 train_state=state,
28- lr_schedulers=schedulers,36+ finish_discarded_step=state.finish_discarded_step,
29 max_consecutive_recoveries=3,37 max_consecutive_recoveries=3,
30 reset_auxiliary_state=lambda: events.append("auxiliary reset"),38 reset_auxiliary_state=lambda: events.append("auxiliary reset"),
31 )39 )
@@ -39,7 +47,11 @@ def test_device_recovery_discards_attempt_without_loading_training_state(monkeyp
39 state.load_state_dict.assert_not_called()47 state.load_state_dict.assert_not_called()
40 manager.restore_committed_state.assert_not_called()48 manager.restore_committed_state.assert_not_called()
41 manager.discard_interrupted_step.assert_called_once_with(error)49 manager.discard_interrupted_step.assert_called_once_with(error)
42- schedulers.step.assert_called_once_with()50+ assert state.num_completed_steps == 15
51+ state.optim.lr_schedulers.step.assert_called_once_with()
52+ state.optim.step.assert_not_called()
53+ state.optim.optimizers.step.assert_not_called()
54+ state.optim.ema.step.assert_not_called()
43 step.assert_called_once_with(iterator)55 step.assert_called_once_with(iterator)
44 56 
45 57 
@@ -52,7 +64,7 @@ def test_commit_timeout_exits_instead_of_discarding_and_continuing():
52 manager=manager,64 manager=manager,
53 model_parts=[],65 model_parts=[],
54 train_state=state,66 train_state=state,
55- lr_schedulers=schedulers,67+ finish_discarded_step=schedulers.step,
56 max_consecutive_recoveries=3,68 max_consecutive_recoveries=3,
57 reset_auxiliary_state=Mock(),69 reset_auxiliary_state=Mock(),
58 )70 )
@@ -66,23 +78,71 @@ def test_commit_timeout_exits_instead_of_discarding_and_continuing():
66 78 
67@pytest.mark.parametrize("commit_authorized", [False, True])79@pytest.mark.parametrize("commit_authorized", [False, True])
68def test_completed_rejected_step_clears_transient_auxiliary_state(monkeypatch, commit_authorized):80def test_completed_rejected_step_clears_transient_auxiliary_state(monkeypatch, commit_authorized):
69- hccl = Mock(enabled=True, optimizer_update_completed=commit_authorized)81+ engine = object.__new__(FaultTolerantTrainingEngineEx)
82+ engine.num_completed_steps = 14
83+ engine.optim = Mock()
84+ engine.optim.lr_schedulers.schedulers = [Mock(get_last_lr=Mock(return_value=[0.01]))]
85+ engine.parallelism_context = SimpleNamespace(dp_enabled=False, dp_cp_enabled=False)
86+ engine.device = torch.device("cpu")
87+ engine.ntokens_seen = 1
88+ engine.loss = torch.tensor(1.0)
89+ engine.forward_backward = Mock(return_value=SimpleNamespace(loss=engine.loss))
90+ hccl = Mock(optimizer_update_completed=commit_authorized)
91+ hccl.recover.return_value = True
70 manager = Mock(commit_authorized=commit_authorized)92 manager = Mock(commit_authorized=commit_authorized)
71- auxiliary_reset = Mock()93+ auxiliary_reset, moe_reset = Mock(), Mock()
72- moe_reset = Mock()
73 monkeypatch.setattr(step_recovery, "reset_rejected_moe_state", moe_reset)94 monkeypatch.setattr(step_recovery, "reset_rejected_moe_state", moe_reset)
95+ finish_discarded_step = Mock(wraps=engine.finish_discarded_step)
74 recovery = step_recovery.StepRecovery(96 recovery = step_recovery.StepRecovery(
75 hccl,97 hccl,
76 manager=manager,98 manager=manager,
77 model_parts=[],99 model_parts=[],
78- train_state=Mock(),100+ train_state=engine,
79- lr_schedulers=Mock(),101+ finish_discarded_step=finish_discarded_step,
80 max_consecutive_recoveries=3,102 max_consecutive_recoveries=3,
81 reset_auxiliary_state=auxiliary_reset,103 reset_auxiliary_state=auxiliary_reset,
82 )104 )
105+ trainer = SimpleNamespace(
106+ engine=engine,
107+ recovery=recovery,
108+ metrics_processor=Mock(should_log=Mock(return_value=True)),
109+ gradient_accumulation_steps=1,
110+ num_pp_microbatches=1,
111+ )
83 112 
84- result = recovery.run_step(lambda _: "done", iter([]))113+ def optimizer_attempt(*args, **kwargs):
114+ engine.optim.lr_schedulers.step()
115+ return torch.tensor(1.0)
85 116 
86- assert result == "done"117+ engine.optim.step.side_effect = optimizer_attempt
118+ recovery.run_step(
119+ lambda iterator: FaultTolerantTrainerEx._train_step(trainer, iterator),
120+ iter([SimpleNamespace(num_valid_tokens=1)]),
121+ )
122+ assert engine.num_completed_steps == 15
123+ engine.optim.lr_schedulers.step.assert_called_once_with()
87 assert moe_reset.call_count == (0 if commit_authorized else 1)124 assert moe_reset.call_count == (0 if commit_authorized else 1)
88 assert auxiliary_reset.call_count == (0 if commit_authorized else 1)125 assert auxiliary_reset.call_count == (0 if commit_authorized else 1)
126+ finish_discarded_step.assert_not_called()
127+ 
128+ if not commit_authorized:
129+ # A late error after a rejected, finalized attempt must not consume it twice.
130+ auxiliary_reset.reset_mock()
131+ moe_reset.reset_mock()
132+ engine.optim.lr_schedulers.step.reset_mock()
133+ trainer.metrics_processor.log.reset_mock()
134+ error = RuntimeError("FORCE STOP after rejected optimizer step")
135+ trainer.metrics_processor.log.side_effect = error
136+ with pytest.raises(RuntimeError, match="finalized step requires restarting") as raised:
137+ recovery.run_step(
138+ lambda iterator: FaultTolerantTrainerEx._train_step(trainer, iterator),
139+ iter([SimpleNamespace(num_valid_tokens=1)]),
140+ )
141+ assert raised.value.__cause__ is error
142+ assert engine.num_completed_steps == 16
143+ engine.optim.lr_schedulers.step.assert_called_once_with()
144+ trainer.metrics_processor.log.assert_called_once()
145+ manager.discard_interrupted_step.assert_not_called()
146+ finish_discarded_step.assert_not_called()
147+ auxiliary_reset.assert_not_called()
148+ moe_reset.assert_not_called()
@@ -19,6 +19,7 @@ with patch.object(module, 'ManagerEx') as manager, \\
19 )19 )
20 assert not hasattr(config, 'enable_hccl_recovery')20 assert not hasattr(config, 'enable_hccl_recovery')
21 assert not hasattr(config, 'state_dict_on_training_thread')21 assert not hasattr(config, 'state_dict_on_training_thread')
22+ assert config.use_async_quorum is False
22 ft = module.FTManagerEx(config)23 ft = module.FTManagerEx(config)
23 assert not ft.use_async_quorum24 assert not ft.use_async_quorum
24 assert ft.group_size == config.group_size25 assert ft.group_size == config.group_size
@@ -37,6 +38,7 @@ for overrides in (
37 {'enable': False},38 {'enable': False},
38 {'process_group': 'gloo'},39 {'process_group': 'gloo'},
39 {'semi_sync_method': 'local_sgd'},40 {'semi_sync_method': 'local_sgd'},
41+ {'use_async_quorum': True},
40 {'group_size': 1},42 {'group_size': 1},
41 {'group_size': 2, 'min_replica_size': 3},43 {'group_size': 2, 'min_replica_size': 3},
42 {'group_size': 2, 'replica_id': 2},44 {'group_size': 2, 'replica_id': 2},
@@ -8,14 +8,19 @@ import sys
8 8 
9def test_ft_trainer_config_and_npu_lifecycle():9def test_ft_trainer_config_and_npu_lifecycle():
10 program = """10 program = """
11+from types import SimpleNamespace
11from unittest.mock import Mock, patch12from unittest.mock import Mock, patch
12import torch13import torch
14+import torchtitan.experiments.torchft.trainer as upstream
13from torchtitan.config import ConfigManager15from torchtitan.config import ConfigManager
14 16 
15from torchtitan_npu.extensions.torchtitan.experiments.torchft import trainer as module17from torchtitan_npu.extensions.torchtitan.experiments.torchft import trainer as module
16from torchtitan_npu.extensions.torchtitan import trainer as npu_trainer18from torchtitan_npu.extensions.torchtitan import trainer as npu_trainer
17from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash, deepseek_v4_flash_8p_torchft19from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash, deepseek_v4_flash_8p_torchft
18 20 
21+# Check the real import-time binding before any initializer is mocked.
22+assert upstream.FaultTolerantTrainingEngine is module.FaultTolerantTrainingEngineEx
23+ 
19def make_config():24def make_config():
20 return ConfigManager().parse_args([25 return ConfigManager().parse_args([
21 '--module', 'torchtitan_npu.models.deepseek_v4',26 '--module', 'torchtitan_npu.models.deepseek_v4',
@@ -83,7 +88,7 @@ unsupported = (
83for path, value, message in unsupported:88for path, value, message in unsupported:
84 candidate = deepseek_v4_flash_8p_torchft()89 candidate = deepseek_v4_flash_8p_torchft()
85 set_path(candidate, path, value)90 set_path(candidate, path, value)
86- with patch.object(npu_trainer.Trainer, '__init__') as initialize:91+ with patch.object(module.FaultTolerantTrainer, '__init__') as initialize:
87 try:92 try:
88 module.FaultTolerantTrainerEx(candidate)93 module.FaultTolerantTrainerEx(candidate)
89 except ValueError as error:94 except ValueError as error:
@@ -92,29 +97,44 @@ for path, value, message in unsupported:
92 raise AssertionError(f'accepted unsupported TorchFT configuration: {path}={value!r}')97 raise AssertionError(f'accepted unsupported TorchFT configuration: {path}={value!r}')
93 initialize.assert_not_called()98 initialize.assert_not_called()
94 99 
95-initialize_ft = Mock()100+config.fault_tolerance.replica_id = 1
96-def initialize_engine(trainer, cfg):101+config.override.imports = []
97- initialize_ft(cfg)102+config.tokenizer = None
98- engine = Mock()103+config.validator = None
99- engine.model_parts = []104+ft = object.__new__(module.FTManagerEx)
100- engine.optim = Mock(lr_schedulers=Mock())105+ft.group_size, ft.replica_id, ft._manager = 2, 1, Mock(spec=module.ManagerEx)
101- engine.ft_manager = Mock(106+ft.process_group = Mock()
102- spec=module.FTManagerEx,107+mesh = Mock()
103- process_group=Mock(recovery=object()),108+mesh.size.return_value, mesh.get_local_rank.return_value = 4, 1
104- manager=Mock(spec=module.ManagerEx),109+engine = Mock(
105- )110+ ft_manager=ft,
106- trainer.engine = engine111+ model_parts=[],
107- trainer.gradient_accumulation_steps = 1112+ device=torch.device('cpu'),
113+ model_device_mem_stats=SimpleNamespace(max_reserved_gib=0.0, max_reserved_pct=0.0),
114+ parallelism_context=SimpleNamespace(dp_enabled=True, pp_enabled=False, get_mesh=lambda _: mesh),
115+)
108 116 
109-with patch.object(npu_trainer.Trainer, '__init__', initialize_engine), \\117+# Exercise the actual FT initializer; only resource creation is mocked.
118+with patch.object(upstream, 'FaultTolerantTrainingEngine', return_value=engine), \\
119+ patch.object(type(config.model), 'update_from_config'), \\
120+ patch.object(type(config), '__post_init__'), \\
121+ patch.object(type(config), 'maybe_log'), \\
122+ patch.object(type(config.dataloader), 'build') as build_data, \\
123+ patch.object(type(config.metrics), 'build') as build_metrics, \\
124+ patch.object(upstream, 'cuda_graphs_supported', return_value=False), \\
125+ patch.object(upstream.utils, 'get_peak_flops', return_value=1.0), \\
110 patch.object(npu_trainer, 'set_allow_hf32') as set_hf32, \\126 patch.object(npu_trainer, 'set_allow_hf32') as set_hf32, \\
111 patch.object(type(config.sdc), 'build') as build_sdc, \\127 patch.object(type(config.sdc), 'build') as build_sdc, \\
112 patch.object(module, 'StepRecovery') as recovery:128 patch.object(module, 'StepRecovery') as recovery:
113 trainer = module.FaultTolerantTrainerEx(config)129 trainer = module.FaultTolerantTrainerEx(config)
114- initialize_ft.assert_called_once_with(config)130+ assert trainer.gradient_accumulation_steps == 2
131+ assert build_data.call_args.kwargs['dp_world_size'] == 8
132+ assert build_data.call_args.kwargs['dp_rank'] == 5
133+ assert build_metrics.call_args.kwargs['ft_replica_id'] == 1
134+ engine.initialize.assert_called_once()
115 set_hf32.assert_called_once_with(config.training.extension.allow_hf32)135 set_hf32.assert_called_once_with(config.training.extension.allow_hf32)
116 build_sdc.assert_called_once_with(136 build_sdc.assert_called_once_with(
117- trainer_config=config, model_parts=[], gradient_accumulation_steps=1137+ trainer_config=config, model_parts=[], gradient_accumulation_steps=2
118 )138 )
119 assert trainer.engine._sdc is build_sdc.return_value139 assert trainer.engine._sdc is build_sdc.return_value
120 recovery.assert_called_once()140 recovery.assert_called_once()
@@ -125,18 +145,15 @@ with patch.object(npu_trainer.Trainer, '__init__', initialize_engine), \\
125 (Mock(), 'requires FTManagerEx'),145 (Mock(), 'requires FTManagerEx'),
126 (Mock(spec=module.FTManagerEx, manager=Mock()), 'requires ManagerEx'),146 (Mock(spec=module.FTManagerEx, manager=Mock()), 'requires ManagerEx'),
127 ):147 ):
128- def initialize_wrong_manager(trainer, cfg):148+ ft_manager.get_dp_info = Mock(return_value=(8, 5))
129- initialize_engine(trainer, cfg)149+ engine.ft_manager = ft_manager
130- trainer.engine.ft_manager = ft_manager
131- 
132 recovery.reset_mock()150 recovery.reset_mock()
133- with patch.object(npu_trainer.Trainer, '__init__', initialize_wrong_manager):151+ try:
134- try:152+ module.FaultTolerantTrainerEx(config)
135- module.FaultTolerantTrainerEx(config)153+ except TypeError as error:
136- except TypeError as error:154+ assert message in str(error)
137- assert message in str(error)155+ else:
138- else:156+ raise AssertionError('accepted incompatible TorchFT manager')
139- raise AssertionError('accepted incompatible TorchFT manager')
140 recovery.assert_not_called()157 recovery.assert_not_called()
141 158 
142class AuxiliaryLoss(torch.nn.Module):159class AuxiliaryLoss(torch.nn.Module):
@@ -157,7 +174,7 @@ assert AuxiliaryLoss.group_acc == {}
157 assert result.returncode == 0, result.stderr174 assert result.returncode == 0, result.stderr
158 175 
159 176 
160-def test_ft_train_step_consumes_collated_valid_tokens(monkeypatch):177+def test_ft_train_step_consumes_collated_valid_tokens():
161 from types import SimpleNamespace178 from types import SimpleNamespace
162 from unittest.mock import Mock179 from unittest.mock import Mock
163 180 
@@ -198,6 +215,7 @@ def test_ft_train_step_consumes_collated_valid_tokens(monkeypatch):
198 215 
199 trainer = SimpleNamespace(216 trainer = SimpleNamespace(
200 engine=engine,217 engine=engine,
218+ recovery=Mock(),
201 metrics_processor=Mock(should_log=Mock(return_value=False)),219 metrics_processor=Mock(should_log=Mock(return_value=False)),
202 gradient_accumulation_steps=2,220 gradient_accumulation_steps=2,
203 num_pp_microbatches=1,221 num_pp_microbatches=1,
@@ -210,4 +228,5 @@ def test_ft_train_step_consumes_collated_valid_tokens(monkeypatch):
210 assert groups == [[microbatches[0]], [microbatches[1]]]228 assert groups == [[microbatches[0]], [microbatches[1]]]
211 assert valid_tokens == 3229 assert valid_tokens == 3
212 engine.optim_step.assert_called_once_with()230 engine.optim_step.assert_called_once_with()
231+ trainer.recovery.mark_step_finished.assert_called_once_with()
213 trainer.metrics_processor.log.assert_not_called()232 trainer.metrics_processor.log.assert_not_called()
@@ -194,6 +194,18 @@ def test_sdc_submits_only_at_configured_accumulation_boundaries(
194 assert torch.equal(gradient, model.weight.grad)194 assert torch.equal(gradient, model.weight.grad)
195 assert name == "weight_backward"195 assert name == "weight_backward"
196 196 
197+ # Discard a partial window and require a full new window before detection.
198+ sdc.discard_step()
199+ for _ in range(accumulation_steps - 1):
200+ sdc.finalize_sdc_step()
201+ sdc.discard_step()
202+ before = len(checker.detected)
203+ for _ in range(accumulation_steps - 1):
204+ sdc.finalize_sdc_step()
205+ assert len(checker.detected) == before
206+ sdc.finalize_sdc_step()
207+ assert len(checker.detected) == before + 1
208+ 
197 209 
198@pytest.mark.parametrize(210@pytest.mark.parametrize(
199 ("dtype", "expected_flag"),211 ("dtype", "expected_flag"),
@@ -141,6 +141,11 @@ class SDC(Configurable):
141 "disable the native switch before importing torch-npu or disable typed SDC"141 "disable the native switch before importing torch-npu or disable typed SDC"
142 )142 )
143 143 
144+ @torch.no_grad()
145+ def discard_step(self) -> None:
146+ """Discard a partial accumulation window without reading failed gradients."""
147+ self._microbatch = 0
148+ 
144 @torch.no_grad()149 @torch.no_grad()
145 def finalize_sdc_step(self) -> None:150 def finalize_sdc_step(self) -> None:
146 """Submit a complete accumulation window after a successful backward step."""151 """Submit a complete accumulation window after a successful backward step."""
@@ -16,5 +16,22 @@ except ModuleNotFoundError as error:
16 name="torchft",16 name="torchft",
17 ) from error17 ) from error
18 18 
19-from torchtitan_npu.patches import torchft as _torchft_patches # noqa: F40119+from torchtitan_npu.patches import torchft as _torchft_patches # noqa: F401, I001
20from torchtitan_npu.patches.torchtitan.experiments import torchft as _torchtitan_torchft_patches # noqa: F40120from torchtitan_npu.patches.torchtitan.experiments import torchft as _torchtitan_torchft_patches # noqa: F401
21+ 
22+# Activate only after the optional dependency and its device patches are ready.
23+import torchtitan.experiments.torchft.trainer
24+ 
25+from .trainer import FaultTolerantTrainingEngineEx
26+ 
27+ 
28+def apply() -> None:
29+ """Select the NPU engine for the upstream FT constructor.
30+ 
31+ This opt-in package is the sole owner of the binding. Unlike the ordinary
32+ Trainer, the pinned FT constructor does not consult ``engine_cls``.
33+ """
34+ torchtitan.experiments.torchft.trainer.FaultTolerantTrainingEngine = FaultTolerantTrainingEngineEx
35+ 
36+ 
37+apply()
@@ -61,6 +61,7 @@ class FTManagerEx(TorchFTManager):
61 class Config(TorchFTManager.Config):61 class Config(TorchFTManager.Config):
62 enable: bool = True62 enable: bool = True
63 process_group: str = "hccl"63 process_group: str = "hccl"
64+ use_async_quorum: bool = False
64 quorum_timeout_seconds: int = 6065 quorum_timeout_seconds: int = 60
65 """Allow time for replica-local state export, loading and disk operations."""66 """Allow time for replica-local state export, loading and disk operations."""
66 device_recovery_timeout_seconds: int = 6067 device_recovery_timeout_seconds: int = 60
@@ -73,6 +74,8 @@ class FTManagerEx(TorchFTManager):
73 raise ValueError("NPU TorchFT requires enabled HCCL fault tolerance")74 raise ValueError("NPU TorchFT requires enabled HCCL fault tolerance")
74 if config.semi_sync_method is not None:75 if config.semi_sync_method is not None:
75 raise ValueError("NPU TorchFT supports synchronous training only; LocalSGD and DiLoCo are unsupported")76 raise ValueError("NPU TorchFT supports synchronous training only; LocalSGD and DiLoCo are unsupported")
77+ if config.use_async_quorum:
78+ raise ValueError("NPU TorchFT requires synchronous quorum; use_async_quorum must be False")
76 if config.group_size < 2:79 if config.group_size < 2:
77 raise ValueError("NPU TorchFT requires at least two elastic DP replicas")80 raise ValueError("NPU TorchFT requires at least two elastic DP replicas")
78 if not 1 <= config.min_replica_size <= config.group_size:81 if not 1 <= config.min_replica_size <= config.group_size:
@@ -20,7 +20,6 @@ if TYPE_CHECKING:
20 20 
21 from torch import nn21 from torch import nn
22 from torch.distributed.checkpoint.stateful import Stateful22 from torch.distributed.checkpoint.stateful import Stateful
23- from torchtitan.components.optim import LRSchedulersContainer
24 23 
25 from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import ManagerEx24 from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import ManagerEx
26 25 
@@ -62,7 +61,7 @@ class StepRecovery:
62 manager: ManagerEx,61 manager: ManagerEx,
63 model_parts: list[nn.Module],62 model_parts: list[nn.Module],
64 train_state: Stateful,63 train_state: Stateful,
65- lr_schedulers: LRSchedulersContainer,64+ finish_discarded_step: Callable[[], None],
66 max_consecutive_recoveries: int,65 max_consecutive_recoveries: int,
67 reset_auxiliary_state: Callable[[], None],66 reset_auxiliary_state: Callable[[], None],
68 ):67 ):
@@ -70,12 +69,18 @@ class StepRecovery:
70 self._manager = manager69 self._manager = manager
71 self._model_parts = model_parts70 self._model_parts = model_parts
72 self._train_state = train_state71 self._train_state = train_state
73- self._lr_schedulers = lr_schedulers72+ self._finish_discarded_step = finish_discarded_step
74 self._max_consecutive_recoveries = max_consecutive_recoveries73 self._max_consecutive_recoveries = max_consecutive_recoveries
75 self._reset_auxiliary_state = reset_auxiliary_state74 self._reset_auxiliary_state = reset_auxiliary_state
76 self._consecutive_recoveries = 075 self._consecutive_recoveries = 0
76+ self._step_finished = False
77+ 
78+ def mark_step_finished(self) -> None:
79+ """Record that the engine advanced its clock, even for a rejected vote."""
80+ self._step_finished = True
77 81 
78 def run_step(self, step, data_iterator):82 def run_step(self, step, data_iterator):
83+ self._step_finished = False
79 try:84 try:
80 result = step(data_iterator)85 result = step(data_iterator)
81 except RuntimeError as error:86 except RuntimeError as error:
@@ -83,6 +88,10 @@ class StepRecovery:
83 raise88 raise
84 if self._hccl.optimizer_update_completed:89 if self._hccl.optimizer_update_completed:
85 raise RuntimeError("HCCL recovery after an optimizer commit is not supported") from error90 raise RuntimeError("HCCL recovery after an optimizer commit is not supported") from error
91+ if self._step_finished:
92+ # A rejected vote may already have advanced TorchFT and the LR
93+ # scheduler. Never vote again or advance that attempt twice.
94+ raise RuntimeError("HCCL recovery after a finalized step requires restarting the replica") from error
86 self._consecutive_recoveries += 195 self._consecutive_recoveries += 1
87 if self._consecutive_recoveries > self._max_consecutive_recoveries:96 if self._consecutive_recoveries > self._max_consecutive_recoveries:
88 raise RuntimeError("Exceeded the consecutive HCCL recovery limit") from error97 raise RuntimeError("Exceeded the consecutive HCCL recovery limit") from error
@@ -93,10 +102,10 @@ class StepRecovery:
93 # operator workspaces outside the PyTorch caching allocator.102 # operator workspaces outside the PyTorch caching allocator.
94 torch_npu.npu.empty_cache()103 torch_npu.npu.empty_cache()
95 self._manager.discard_interrupted_step(error)104 self._manager.discard_interrupted_step(error)
96- self._lr_schedulers.step()105+ self._finish_discarded_step()
97 logger.warning(106 logger.warning(
98 "Discarded interrupted TorchFT attempt %d after device recovery; next step reads new data",107 "Discarded interrupted TorchFT attempt %d after device recovery; next step reads new data",
99- attempt_state["step"],108+ attempt_state["step"] + 1,
100 )109 )
101 return110 return
102 if not self._manager.commit_authorized:111 if not self._manager.commit_authorized:
@@ -28,19 +28,17 @@ from torchtitan_npu.models.deepseek_v4.model import DeepSeekV4Model
28class FaultTolerantTrainingEngineEx(NPUTrainingEngineMixin, FaultTolerantTrainingEngine):28class FaultTolerantTrainingEngineEx(NPUTrainingEngineMixin, FaultTolerantTrainingEngine):
29 """TorchFT training engine with the NPU microbatch lifecycle hooks."""29 """TorchFT training engine with the NPU microbatch lifecycle hooks."""
30 30 
31- def __init__(self, config, *, model_config, max_num_documents, output_dir):31+ def finish_discarded_step(self) -> None:
titan-npu-reviewer

实际位置是 torchtitan_npu/extensions/torchtitan/experiments/torchft/trainer.py:31-34。

一般(S2): finish_discarded_step() 对丢弃的 attempt 也执行 num_completed_steps += 1,但这一步没有做任何参数更新;而 should_continue_training() 和最终保存的 last_step=(num_completed_steps == config.training.steps) 都以 num_completed_steps 为准。触发条件:一次中断 backward 后设备恢复成功,本函数被调用。后果:发生 N 次可恢复故障时,真实 optimizer 更新比 training.steps 少 N 次,训练却仍在配置步数处判定完成并写 last_step=True,步号与真实更新数不再一致。建议把 attempt 编号与“已完成优化步”拆成两个计数(或显式扣除恢复次数),避免恢复次数悄悄改变训练长度。

问题编号:R1210-001

审查版本:34d11d06c00ba1b93f368f2b9efeb77f0c85b13a

likedislike
zhangyifan999
zhangyifan999
26 days ago Comments:
likedislike
32- super().__init__(32+ """Advance the consumed attempt without updating weights or EMA.
33- config,33+ 
34- model_config=model_config,34+ Match upstream FT rejection: training.steps counts consumed attempts,
35- max_num_documents=max_num_documents,35+ including rejected ones, rather than successful parameter updates.
36- output_dir=output_dir,36+ """
37- fault_tolerance=config.fault_tolerance,37+ self.optim.lr_schedulers.step()
38- )38+ self.num_completed_steps += 1
39 39 
40 40 
41class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer):41class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer):
42- engine_cls = FaultTolerantTrainingEngineEx
43- 
44 @dataclass(kw_only=True, slots=True)42 @dataclass(kw_only=True, slots=True)
45 class Config(TrainerEx.Config): # pyrefly: ignore [bad-override]43 class Config(TrainerEx.Config): # pyrefly: ignore [bad-override]
46 optim: OptimConfig = field(default_factory=lambda: OptimConfig(optimizer=TorchFTOptimizersContainerEx.Config()))44 optim: OptimConfig = field(default_factory=lambda: OptimConfig(optimizer=TorchFTOptimizersContainerEx.Config()))
@@ -70,11 +68,17 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer):
70 manager=manager,68 manager=manager,
71 model_parts=cast("list[nn.Module]", engine.model_parts),69 model_parts=cast("list[nn.Module]", engine.model_parts),
72 train_state=engine,70 train_state=engine,
73- lr_schedulers=engine.optim.lr_schedulers,71+ finish_discarded_step=engine.finish_discarded_step,
74 max_consecutive_recoveries=config.fault_tolerance.max_consecutive_hccl_recoveries,72 max_consecutive_recoveries=config.fault_tolerance.max_consecutive_hccl_recoveries,
75 reset_auxiliary_state=self._reset_auxiliary_state,73 reset_auxiliary_state=self._reset_auxiliary_state,
76 )74 )
77 75 
76+ def _initialize_trainer(self, config: TrainerEx.Config) -> None:
77+ # Native FT initialization accounts for all replicas in dataloader
78+ # sharding and accumulation; the ordinary Trainer cannot do that.
79+ # The NPU config declares the same FT fields on its own TrainerEx base.
80+ FaultTolerantTrainer.__init__(self, cast("FaultTolerantTrainer.Config", config))
81+ 
78 @staticmethod82 @staticmethod
79 def _validate_supported_config(config: Config) -> None:83 def _validate_supported_config(config: Config) -> None:
80 FTManagerEx.validate_config(config.fault_tolerance)84 FTManagerEx.validate_config(config.fault_tolerance)
@@ -100,6 +104,9 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer):
100 104 
101 @torch.no_grad()105 @torch.no_grad()
102 def _reset_auxiliary_state(self) -> None:106 def _reset_auxiliary_state(self) -> None:
107+ engine = cast("FaultTolerantTrainingEngineEx", self.engine)
108+ if engine._sdc is not None:
109+ engine._sdc.discard_step()
103 # Auxiliary-loss modules expose a local accumulator and shared step metrics.110 # Auxiliary-loss modules expose a local accumulator and shared step metrics.
104 # Inspect that state without coupling recovery to a model's patch class.111 # Inspect that state without coupling recovery to a model's patch class.
105 for part in self.engine.model_parts:112 for part in self.engine.model_parts:
@@ -147,6 +154,7 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer):
147 154 
148 if not should_log:155 if not should_log:
149 engine.optim_step()156 engine.optim_step()
157+ self.recovery.mark_step_finished()
150 return158 return
151 159 
152 # No new cross-replica collective may be issued after a successful vote,160 # No new cross-replica collective may be issued after a successful vote,
@@ -169,6 +177,7 @@ class FaultTolerantTrainerEx(TrainerEx, FaultTolerantTrainer):
169 global_ntokens_seen = engine.ntokens_seen177 global_ntokens_seen = engine.ntokens_seen
170 178 
171 grad_norm = engine.optim_step()179 grad_norm = engine.optim_step()
180+ self.recovery.mark_step_finished()
172 181 
173 self.metrics_processor.log(182 self.metrics_processor.log(
174 current_step,183 current_step,
@@ -251,10 +251,10 @@ class TrainerEx(Trainer):
251 251 
252 pool = PinnedFlatPool("fsdp-offload")252 pool = PinnedFlatPool("fsdp-offload")
253 with pool.pinned_pin_window():253 with pool.pinned_pin_window():
254- super().__init__(config)254+ self._initialize_trainer(config)
255 self._carve_grad_slots(pool)255 self._carve_grad_slots(pool)
256 else:256 else:
257- super().__init__(config)257+ self._initialize_trainer(config)
258 engine = cast("NPUTrainingEngine", self.engine)258 engine = cast("NPUTrainingEngine", self.engine)
259 engine._sdc = config.sdc.build(259 engine._sdc = config.sdc.build(
260 trainer_config=config,260 trainer_config=config,
@@ -275,6 +275,10 @@ class TrainerEx(Trainer):
275 self.anticipatory_schedule = AnticipatorySchedule(self) if config.anticipatory.enable else None275 self.anticipatory_schedule = AnticipatorySchedule(self) if config.anticipatory.enable else None
276 engine.anticipatory_schedule = self.anticipatory_schedule276 engine.anticipatory_schedule = self.anticipatory_schedule
277 277 
278+ def _initialize_trainer(self, config: Config) -> None:
279+ """Build the trainer while allowing experiments to own data partitioning."""
280+ super().__init__(config)
hwcaifubi
hwcaifubihwcaifubi23 days ago

This code comment section is from+254To+280

这个修改是为什么?

likedislike
zhangyifan999
zhangyifan999
23 days ago Comments:
likedislike
281+ 
278 def train_step(self, data_iterator):282 def train_step(self, data_iterator):
279 if self.anticipatory_schedule is not None:283 if self.anticipatory_schedule is not None:
280 with self.anticipatory_schedule.training_step_context(data_iterator) as batches:284 with self.anticipatory_schedule.training_step_context(data_iterator) as batches: