Closed
feat: 接入 TorchFT NPU 训练流程 #677
zhangyifan999Add on Sep 1Closed at Oct 12
feat: 接入 TorchFT NPU 训练流程 #677
Closed
Total: 11 files changed+1107-17
| @@ -12,6 +12,7 @@ from .configs import ( | |||
| 12 | ProfilerExtensionConfig, | 12 | ProfilerExtensionConfig, |
| 13 | QuantizationExtensionConfig, | 13 | QuantizationExtensionConfig, |
| 14 | QuantizationRecipe, | 14 | QuantizationRecipe, |
| 15 | + TorchFTExtensionConfig, | ||
| 15 | TrainingConfig, | 16 | TrainingConfig, |
| 16 | TrainingExtensionConfig, | 17 | TrainingExtensionConfig, |
| 17 | ) | 18 | ) |
| @@ -24,6 +25,7 @@ __all__ = [ | |||
| 24 | "ProfilerExtensionConfig", | 25 | "ProfilerExtensionConfig", |
| 25 | "QuantizationExtensionConfig", | 26 | "QuantizationExtensionConfig", |
| 26 | "QuantizationRecipe", | 27 | "QuantizationRecipe", |
| 28 | + "TorchFTExtensionConfig", | ||
| 27 | "TrainingConfig", | 29 | "TrainingConfig", |
| 28 | "TrainingExtensionConfig", | 30 | "TrainingExtensionConfig", |
| 29 | ] | 31 | ] |
| @@ -113,6 +113,23 @@ class QuantizationExtensionConfig: | |||
| 113 | dst_type_max: float = 0.0 | 113 | dst_type_max: float = 0.0 |
| 114 | 114 | ||
| 115 | 115 | ||
| 116 | +@dataclass(kw_only=True, slots=True) | ||
| 117 | +class TorchFTExtensionConfig: | ||
| 118 | + """Late-bound synchronous TorchFT options for NPU training.""" | ||
| 119 | + | ||
| 120 | + enable: bool = False | ||
| 121 | + process_group_timeout_ms: int = 600_000 | ||
| 122 | + replica_id: int = 0 | ||
| 123 | + group_size: int = 2 | ||
| 124 | + min_replica_size: int = 2 | ||
| 125 | + init_sync: bool = False | ||
| 126 | + enable_ft_dataloader_checkpoints: bool = True | ||
| 127 | + hccl_active_work_grace_ms: int = 500 | ||
| 128 | + hccl_device_restart_wait_timeout_ms: int = 60_000 | ||
| 129 | + hccl_watchdog_timeout_margin_ms: int = 30_000 | ||
| 130 | + hccl_rejoin_max_step_replays: int = 3 | ||
| 131 | + | ||
| 132 | + | ||
| 116 | @dataclass(kw_only=True, slots=True) | 133 | @dataclass(kw_only=True, slots=True) |
| 117 | class ExtensionConfig: | 134 | class ExtensionConfig: |
| 118 | """Global NPU extensions without an upstream component owner. | 135 | """Global NPU extensions without an upstream component owner. |
| @@ -136,6 +153,9 @@ class ExtensionConfig: | |||
| 136 | quantization: QuantizationExtensionConfig = field( | 153 | quantization: QuantizationExtensionConfig = field( |
| 137 | default_factory=QuantizationExtensionConfig, | 154 | default_factory=QuantizationExtensionConfig, |
| 138 | ) | 155 | ) |
| 156 | + torchft: TorchFTExtensionConfig = field( | ||
| 157 | + default_factory=TorchFTExtensionConfig, | ||
| 158 | + ) | ||
| 139 | 159 | ||
| 140 | 160 | ||
| 141 | @dataclass(kw_only=True, slots=True) | 161 | @dataclass(kw_only=True, slots=True) |
| @@ -3,7 +3,7 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 3 | # This source code is licensed under the BSD-style license found in the |
| 4 | # LICENSE file in the root directory of this source tree. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -"""extensions for torchtitan-npu.""" | 6 | +"""Integration layers that extend existing TorchTitan NPU training flows.""" |
| 7 | 7 | ||
| 8 | from . import ( | 8 | from . import ( |
| 9 | ep_process_group, # noqa: F401 | 9 | ep_process_group, # noqa: F401 |
| @@ -0,0 +1,19 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""TorchFT integration with existing NPU trainer, optimizer, and checkpoint flows.""" | ||
| 8 | + | ||
| 9 | +__all__ = [ | ||
| 10 | + "FTManagerEx", | ||
| 11 | + "FaultTolerantTrainerEx", | ||
| 12 | + "TorchFTCheckpointManagerEx", | ||
| 13 | + "TorchFTOptimizersContainerEx", | ||
| 14 | +] | ||
| 15 | + | ||
| 16 | +from .checkpoint import TorchFTCheckpointManagerEx | ||
| 17 | +from .manager import FTManagerEx | ||
| 18 | +from .optimizer import TorchFTOptimizersContainerEx | ||
| 19 | +from .trainer import FaultTolerantTrainerEx | ||
| @@ -0,0 +1,277 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Persistent checkpoint and peer-healing integration for NPU TorchFT.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["TORCHFT_MANAGER", "TORCH_RNG_STATE", "TorchFTCheckpointManagerEx"] | ||
| 12 | + | ||
| 13 | +from dataclasses import dataclass, replace | ||
| 14 | +from typing import TYPE_CHECKING, Any, cast | ||
| 15 | + | ||
| 16 | +import torch | ||
| 17 | +import torch.distributed as dist | ||
| 18 | +import torch.nn as nn | ||
| 19 | +from torchtitan.components.checkpoint import ( | ||
| 20 | + DATALOADER, | ||
| 21 | + LR_SCHEDULER, | ||
| 22 | + MODEL, | ||
| 23 | + OPTIMIZER, | ||
| 24 | + TRAIN_STATE, | ||
| 25 | + CheckpointManager, | ||
| 26 | + ModelWrapper, | ||
| 27 | +) | ||
| 28 | +from torchtitan.tools.logging import logger | ||
| 29 | + | ||
| 30 | +from torchtitan_npu.interface.torchft.checkpoint_state import ( | ||
| 31 | + _restore_optimizer_learning_rates, | ||
| 32 | + _TorchRngState, | ||
| 33 | +) | ||
| 34 | +from torchtitan_npu.interface.torchft.dataloader_checkpoint import ( | ||
| 35 | + ReplicaDataloaderCheckpoint, | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | +if TYPE_CHECKING: | ||
| 39 | + from torchtitan.components.dataloader import BaseDataLoader | ||
| 40 | + from torchtitan.components.lr_scheduler import LRSchedulersContainer | ||
| 41 | + from torchtitan.components.optimizer import OptimizersContainer | ||
| 42 | + from torchtitan.protocols.state_dict_adapter import BaseStateDictAdapter | ||
| 43 | + | ||
| 44 | + from .manager import FTManagerEx | ||
| 45 | + | ||
| 46 | +TORCHFT_MANAGER = "torchft_manager" | ||
| 47 | +TORCH_RNG_STATE = "torch_rng_state" | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +class TorchFTCheckpointManagerEx(CheckpointManager): | ||
| 51 | + """Coordinate persistent DCP, replica cursors, and peer-healing state.""" | ||
| 52 | + | ||
| 53 | + @dataclass(kw_only=True, slots=True) | ||
| 54 | + class Config(CheckpointManager.Config): | ||
| 55 | + enable_ft_dataloader_checkpoints: bool = True | ||
| 56 | + """Persist each replica's dataloader cursor independently.""" | ||
| 57 | + | ||
| 58 | + def __init__( | ||
| 59 | + self, | ||
| 60 | + config: Config, | ||
| 61 | + *, | ||
| 62 | + dataloader: BaseDataLoader | None, | ||
| 63 | + model_parts: list[nn.Module], | ||
| 64 | + optimizers: OptimizersContainer, | ||
| 65 | + lr_schedulers: LRSchedulersContainer, | ||
| 66 | + states: dict[str, Any], | ||
| 67 | + sd_adapter: BaseStateDictAdapter | None, | ||
| 68 | + base_folder: str = "", | ||
| 69 | + ft_manager: FTManagerEx | None = None, | ||
| 70 | + ) -> None: | ||
| 71 | + self._persistent_checkpoint_enabled = config.enable | ||
| 72 | + enable_dataloader_checkpoint = bool( | ||
| 73 | + ft_manager and ft_manager.enabled and config.enable_ft_dataloader_checkpoints | ||
| 74 | + ) | ||
| 75 | + storage_config = ( | ||
| 76 | + replace(config, enable=True, keep_latest_k=0) | ||
| 77 | + if enable_dataloader_checkpoint and not config.enable | ||
| 78 | + else config | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + self._torch_rng_state = _TorchRngState() | ||
| 82 | + states = {**states, TORCH_RNG_STATE: self._torch_rng_state} | ||
| 83 | + input_states = states | ||
| 84 | + super().__init__( | ||
| 85 | + storage_config, | ||
| 86 | + dataloader=dataloader, | ||
| 87 | + model_parts=model_parts, | ||
| 88 | + optimizers=optimizers, | ||
| 89 | + lr_schedulers=lr_schedulers, | ||
| 90 | + states=states, | ||
| 91 | + sd_adapter=sd_adapter, | ||
| 92 | + base_folder=base_folder, | ||
| 93 | + ) | ||
| 94 | + self._lr_schedulers = lr_schedulers | ||
| 95 | + self._dataloader_checkpoint: ReplicaDataloaderCheckpoint | None = None | ||
| 96 | + | ||
| 97 | + self._configure_ft_state(config, optimizers, model_parts, input_states, ft_manager) | ||
| 98 | + if self.enable_ft_dataloader_checkpoints: | ||
| 99 | + self._configure_dataloader_checkpoint(dataloader) | ||
| 100 | + | ||
| 101 | + @torch.no_grad() | ||
| 102 | + def save(self, curr_step: int, last_step: bool = False) -> bool: | ||
| 103 | + if self.enable_ft_dataloader_checkpoints: | ||
| 104 | + self._ft_save(curr_step) | ||
| 105 | + | ||
| 106 | + if not self._persistent_checkpoint_enabled: | ||
| 107 | + return False | ||
| 108 | + if self._owns_full_checkpoint(): | ||
| 109 | + # Preserve the upstream ordering: finish the per-replica cursor save | ||
| 110 | + # before starting the full checkpoint on the same DCP resources. | ||
| 111 | + self._wait_for_dataloader_checkpoint() | ||
| 112 | + return super().save(curr_step, last_step) | ||
| 113 | + | ||
| 114 | + ft_manager = self.ft_manager | ||
| 115 | + if ft_manager is None: | ||
| 116 | + raise RuntimeError("TorchFT checkpoint ownership requires an enabled manager") | ||
| 117 | + logger.info( | ||
| 118 | + "Replica %s doesn't save the full checkpoint.", | ||
| 119 | + ft_manager.participating_rank(), | ||
| 120 | + ) | ||
| 121 | + return False | ||
| 122 | + | ||
| 123 | + @torch.no_grad() | ||
| 124 | + def load(self, step: int = -1) -> bool: | ||
| 125 | + load_step = step | ||
| 126 | + if self._persistent_checkpoint_enabled and load_step == -1: | ||
| 127 | + load_step = self._find_load_step() | ||
| 128 | + should_load_dataloader = self.enable_ft_dataloader_checkpoints and ( | ||
| 129 | + not self._persistent_checkpoint_enabled or load_step != -1 | ||
| 130 | + ) | ||
| 131 | + if should_load_dataloader: | ||
| 132 | + self._ft_load(load_step) | ||
| 133 | + if not self._persistent_checkpoint_enabled: | ||
| 134 | + return False | ||
| 135 | + loaded = super().load(load_step) | ||
| 136 | + if loaded: | ||
| 137 | + _restore_optimizer_learning_rates(self._lr_schedulers) | ||
| 138 | + return loaded | ||
| 139 | + | ||
| 140 | + def close(self) -> None: | ||
| 141 | + self._wait_for_dataloader_checkpoint() | ||
| 142 | + super().close() | ||
| 143 | + | ||
| 144 | + def restore_pending_compute_rng_state(self) -> bool: | ||
| 145 | + """Reapply RNG loaded from persistent DCP after startup setup completes.""" | ||
| 146 | + return self._torch_rng_state.restore_pending() | ||
| 147 | + | ||
| 148 | + def _configure_ft_state( | ||
| 149 | + self, | ||
| 150 | + config: Config, | ||
| 151 | + optimizers: OptimizersContainer, | ||
| 152 | + model_parts: list[nn.Module], | ||
| 153 | + input_states: dict[str, Any], | ||
| 154 | + ft_manager: FTManagerEx | None, | ||
| 155 | + ) -> None: | ||
| 156 | + self._npu_ft_manager = ft_manager.manager if ft_manager and ft_manager.enabled else None | ||
| 157 | + self.ft_manager = self._npu_ft_manager | ||
| 158 | + self.enable_ft_dataloader_checkpoints = bool(self.ft_manager and config.enable_ft_dataloader_checkpoints) | ||
| 159 | + if self.ft_manager is None: | ||
| 160 | + return | ||
| 161 | + if not self.enable_ft_dataloader_checkpoints: | ||
| 162 | + logger.warning( | ||
| 163 | + "extension.torchft.enable_ft_dataloader_checkpoints is disabled " | ||
| 164 | + "while NPU TorchFT is enabled; a relaunched replica cannot recover " | ||
| 165 | + "its dataset cursor and may replay samples." | ||
| 166 | + ) | ||
| 167 | + if not hasattr(optimizers, "init_cache_state_dict"): | ||
| 168 | + raise TypeError("NPU TorchFT checkpointing requires TorchFTOptimizersContainerEx") | ||
| 169 | + optimizers.init_cache_state_dict() | ||
| 170 | + | ||
| 171 | + healing_states = self._healing_states(input_states, model_parts, optimizers) | ||
| 172 | + self._register_healing_state(healing_states) | ||
| 173 | + if ft_manager is None: | ||
| 174 | + raise RuntimeError("TorchFT wrapper is missing for an enabled manager") | ||
| 175 | + self.ft_replica_id = ft_manager.replica_id | ||
| 176 | + | ||
| 177 | + def _configure_dataloader_checkpoint(self, dataloader: BaseDataLoader | None) -> None: | ||
| 178 | + if self.pg is None: | ||
| 179 | + self.pg = cast("dist.ProcessGroup", dist.new_group(backend="gloo")) | ||
| 180 | + self._dataloader_checkpoint = ReplicaDataloaderCheckpoint( | ||
| 181 | + dataloader=dataloader, | ||
| 182 | + replica_id=self.ft_replica_id, | ||
| 183 | + folder=self.folder, | ||
| 184 | + dcp_save=self.dcp_save, | ||
| 185 | + dcp_load=self.dcp_load, | ||
| 186 | + create_checkpoint_id=self._create_checkpoint_id, | ||
| 187 | + find_load_step=self._find_load_step, | ||
| 188 | + ) | ||
| 189 | + # Retain these public observations for TorchTitan diagnostics and | ||
| 190 | + # compatibility with the upstream experimental manager. | ||
| 191 | + self.ft_states = self._dataloader_checkpoint.states | ||
| 192 | + | ||
| 193 | + def _healing_states( | ||
| 194 | + self, | ||
| 195 | + input_states: dict[str, Any], | ||
| 196 | + model_parts: list[nn.Module], | ||
| 197 | + optimizers: OptimizersContainer, | ||
| 198 | + ) -> dict[str, Any]: | ||
| 199 | + if self._persistent_checkpoint_enabled: | ||
| 200 | + self.states[TORCHFT_MANAGER] = self.ft_manager | ||
| 201 | + return self.states | ||
| 202 | + return { | ||
| 203 | + **input_states, | ||
| 204 | + MODEL: ModelWrapper(model_parts), | ||
| 205 | + OPTIMIZER: optimizers, | ||
| 206 | + LR_SCHEDULER: self._lr_schedulers, | ||
| 207 | + } | ||
| 208 | + | ||
| 209 | + def _register_healing_state(self, healing_states: dict[str, Any]) -> None: | ||
| 210 | + checkpointed_keys = {MODEL, OPTIMIZER, LR_SCHEDULER, TRAIN_STATE, TORCH_RNG_STATE} | ||
| 211 | + | ||
| 212 | + def state_dict() -> dict[str, Any]: | ||
| 213 | + return {key: value.state_dict() for key, value in healing_states.items() if key in checkpointed_keys} | ||
| 214 | + | ||
| 215 | + def load_state_dict(state: dict[str, Any]) -> None: | ||
| 216 | + for key, value in state.items(): | ||
| 217 | + healing_states[key].load_state_dict(value) | ||
| 218 | + _restore_optimizer_learning_rates(self._lr_schedulers) | ||
| 219 | + | ||
| 220 | + manager = self._npu_ft_manager | ||
| 221 | + if manager is None: | ||
| 222 | + raise RuntimeError("TorchFT state registration requires an enabled manager") | ||
| 223 | + manager.register_state_dict_fn( | ||
| 224 | + "torchtitan", | ||
| 225 | + load_state_dict, | ||
| 226 | + state_dict, | ||
| 227 | + state_dict_on_training_thread=True, | ||
| 228 | + ) | ||
| 229 | + | ||
| 230 | + def _ft_save(self, step: int) -> None: | ||
| 231 | + self.maybe_wait_for_saving() | ||
| 232 | + self._require_dataloader_checkpoint().save(step) | ||
| 233 | + | ||
| 234 | + def _ft_load(self, step: int) -> None: | ||
| 235 | + self._require_dataloader_checkpoint().load(step) | ||
| 236 | + | ||
| 237 | + def _wait_for_dataloader_checkpoint(self) -> None: | ||
| 238 | + checkpoint = getattr(self, "_dataloader_checkpoint", None) | ||
| 239 | + if checkpoint is not None: | ||
| 240 | + checkpoint.wait() | ||
| 241 | + | ||
| 242 | + def _require_dataloader_checkpoint(self) -> ReplicaDataloaderCheckpoint: | ||
| 243 | + checkpoint = getattr(self, "_dataloader_checkpoint", None) | ||
| 244 | + if checkpoint is None: | ||
| 245 | + raise RuntimeError("Per-replica dataloader checkpoint is not configured") | ||
| 246 | + return checkpoint | ||
| 247 | + | ||
| 248 | + def _states_to_load(self, model_only: bool) -> dict[str, Any]: | ||
| 249 | + states = super()._states_to_load(model_only) | ||
| 250 | + if self.ft_manager: | ||
| 251 | + states.pop(DATALOADER, None) | ||
| 252 | + return states | ||
| 253 | + | ||
| 254 | + def _flattened_model_states_sd( | ||
| 255 | + self, | ||
| 256 | + state_dict: dict[str, Any] | None = None, | ||
| 257 | + ) -> dict[str, Any]: | ||
| 258 | + states = state_dict if state_dict is not None else self.states | ||
| 259 | + if self.ft_manager: | ||
| 260 | + states = dict(states) | ||
| 261 | + states.pop(DATALOADER, None) | ||
| 262 | + return super()._flattened_model_states_sd(states) | ||
| 263 | + | ||
| 264 | + def _owns_full_checkpoint(self) -> bool: | ||
| 265 | + if self.ft_manager is None: | ||
| 266 | + return True | ||
| 267 | + participating_rank = self.ft_manager.participating_rank() | ||
| 268 | + if participating_rank is not None: | ||
| 269 | + return participating_rank == 0 | ||
| 270 | + return self.ft_replica_id == 0 | ||
| 271 | + | ||
| 272 | + def _should_purge(self) -> bool: | ||
| 273 | + if not self._persistent_checkpoint_enabled: | ||
| 274 | + return False | ||
| 275 | + if not super()._should_purge(): | ||
| 276 | + return False | ||
| 277 | + return self._owns_full_checkpoint() | ||
| @@ -0,0 +1,187 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Self-contained TorchTitan TorchFT manager integration for NPU.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["FTManagerEx"] | ||
| 12 | + | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | +from datetime import timedelta | ||
| 15 | +from typing import TYPE_CHECKING | ||
| 16 | + | ||
| 17 | +import torchft | ||
| 18 | +from torchtitan.config import Configurable | ||
| 19 | +from torchtitan.experiments.torchft.config.job_config import ( | ||
| 20 | + FaultTolerance as _UpstreamFaultTolerance, | ||
| 21 | +) | ||
| 22 | +from torchtitan.experiments.torchft.manager import ( | ||
| 23 | + create_process_group, | ||
| 24 | + install_all_reduce_hooks, | ||
| 25 | + register_process_group_factory, | ||
| 26 | +) | ||
| 27 | +from torchtitan.tools.logging import logger | ||
| 28 | + | ||
| 29 | +from torchtitan_npu.interface.torchft.managed_process_group import LossManagedProcessGroupEx | ||
| 30 | +from torchtitan_npu.interface.torchft.process_group import ProcessGroupHCCLEx | ||
| 31 | +from torchtitan_npu.interface.torchft.runtime import ManagerEx | ||
| 32 | +from torchtitan_npu.interface.torchft.synchronization import ( | ||
| 33 | + _all_reduce_with_recovery_completion, | ||
| 34 | + _iter_moe_load_balance_counts, | ||
| 35 | + _local_tensor, | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | +if TYPE_CHECKING: | ||
| 39 | + import torch | ||
| 40 | + import torch.nn as nn | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def validate_npu_process_group_config(config: FTManagerEx.Config) -> None: | ||
| 44 | + if config.process_group != "hccl": | ||
| 45 | + raise ValueError("NPU TorchFT training requires process_group='hccl'") | ||
| 46 | + if config.group_size < 1: | ||
| 47 | + raise ValueError("fault_tolerance.group_size must be positive") | ||
| 48 | + if config.replica_id < 0 or config.replica_id >= config.group_size: | ||
| 49 | + raise ValueError("replica_id must be in [0, group_size)") | ||
| 50 | + if config.min_replica_size < 1 or config.min_replica_size > config.group_size: | ||
| 51 | + raise ValueError("min_replica_size must be in [1, group_size]") | ||
| 52 | + if config.semi_sync_method is not None: | ||
| 53 | + raise ValueError("NPU TorchFT supports synchronous quorum only; semi_sync_method must be None") | ||
| 54 | + if config.hccl_rejoin_max_step_replays < 1: | ||
| 55 | + raise ValueError("hccl_rejoin_max_step_replays must be positive") | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +class FTManagerEx(Configurable): | ||
| 59 | + """TorchFT manager whose complete backend integration lives in this repo.""" | ||
| 60 | + | ||
| 61 | + @dataclass(kw_only=True, slots=True) | ||
| 62 | + class Config(_UpstreamFaultTolerance): | ||
| 63 | + init_sync: bool = False | ||
| 64 | + """Synchronize initial state through TorchFT before step 0.""" | ||
| 65 | + | ||
| 66 | + hccl_active_work_grace_ms: int = 500 | ||
| 67 | + """Wait this long for tracked HCCL work before stopping the NPU.""" | ||
| 68 | + | ||
| 69 | + hccl_device_restart_wait_timeout_ms: int = 60_000 | ||
| 70 | + """Bound how long process-group creation waits for device restart.""" | ||
| 71 | + | ||
| 72 | + hccl_watchdog_timeout_margin_ms: int = 30_000 | ||
| 73 | + """Keep the HCCL watchdog later than the TorchFT user-space timeout.""" | ||
| 74 | + | ||
| 75 | + hccl_rejoin_max_step_replays: int = 3 | ||
| 76 | + """Maximum retries of one rejected synchronous training step.""" | ||
| 77 | + | ||
| 78 | + _manager: ManagerEx | None | ||
| 79 | + | ||
| 80 | + def __init__(self, config: FTManagerEx.Config) -> None: | ||
| 81 | + if not config.enable: | ||
| 82 | + self._manager = None | ||
| 83 | + self.group_size = config.group_size | ||
| 84 | + self.replica_id = config.replica_id | ||
| 85 | + self.use_async_quorum = True | ||
| 86 | + return | ||
| 87 | + | ||
| 88 | + validate_npu_process_group_config(config) | ||
| 89 | + process_group_timeout = timedelta(milliseconds=config.process_group_timeout_ms) | ||
| 90 | + process_group = self._create_process_group(config.process_group, process_group_timeout) | ||
| 91 | + if not isinstance(process_group, ProcessGroupHCCLEx): | ||
| 92 | + raise RuntimeError("The registered hccl factory did not create ProcessGroupHCCLEx") | ||
| 93 | + process_group.configure_rejoin_workaround( | ||
| 94 | + active_work_grace_ms=config.hccl_active_work_grace_ms, | ||
| 95 | + device_restart_wait_timeout_ms=config.hccl_device_restart_wait_timeout_ms, | ||
| 96 | + watchdog_timeout_margin_ms=config.hccl_watchdog_timeout_margin_ms, | ||
| 97 | + ) | ||
| 98 | + | ||
| 99 | + self.use_async_quorum = True | ||
| 100 | + self._manager = ManagerEx( | ||
| 101 | + pg=process_group, | ||
| 102 | + min_replica_size=config.min_replica_size, | ||
| 103 | + load_state_dict=None, | ||
| 104 | + state_dict=None, | ||
| 105 | + use_async_quorum=self.use_async_quorum, | ||
| 106 | + replica_id=f"torchtitan_ft_{config.replica_id}", | ||
| 107 | + init_sync=config.init_sync, | ||
| 108 | + ) | ||
| 109 | + self.group_size = config.group_size | ||
| 110 | + self.replica_id = config.replica_id | ||
| 111 | + | ||
| 112 | + if self.use_async_quorum and self.group_size > 1: | ||
| 113 | + self.replicate_pg = torchft.process_group.ManagedProcessGroup(self._manager) | ||
| 114 | + self.replicate_pg.register("dp_replicate") | ||
| 115 | + self.loss_replicate_pg = LossManagedProcessGroupEx(self._manager) | ||
| 116 | + self.loss_replicate_pg.register("loss_replicate") | ||
| 117 | + | ||
| 118 | + @property | ||
| 119 | + def enabled(self) -> bool: | ||
| 120 | + return self._manager is not None | ||
| 121 | + | ||
| 122 | + @property | ||
| 123 | + def manager(self) -> ManagerEx: | ||
| 124 | + if self._manager is None: | ||
| 125 | + raise RuntimeError("TorchFT manager is disabled") | ||
| 126 | + return self._manager | ||
| 127 | + | ||
| 128 | + @property | ||
| 129 | + def loss_sync_pg(self): | ||
| 130 | + if self.enabled and self.use_async_quorum and self.group_size > 1: | ||
| 131 | + return self.loss_replicate_pg | ||
| 132 | + return None | ||
| 133 | + | ||
| 134 | + @property | ||
| 135 | + def process_group(self) -> object | None: | ||
| 136 | + """Return TorchFT's active cross-replica process group.""" | ||
| 137 | + return self.manager.process_group | ||
| 138 | + | ||
| 139 | + @classmethod | ||
| 140 | + def _create_process_group(cls, name: str, timeout: timedelta): | ||
| 141 | + return create_process_group(name, timeout) | ||
| 142 | + | ||
| 143 | + def get_dp_info(self, dp_degree: int, dp_rank: int) -> tuple[int, int]: | ||
| 144 | + if not self.enabled: | ||
| 145 | + return dp_degree, dp_rank | ||
| 146 | + return ( | ||
| 147 | + dp_degree * self.group_size, | ||
| 148 | + dp_degree * self.replica_id + dp_rank, | ||
| 149 | + ) | ||
| 150 | + | ||
| 151 | + def maybe_set_all_reduce_hook(self, model_parts: list[torch.nn.Module]) -> None: | ||
| 152 | + if not (self.enabled and self.use_async_quorum) or self.group_size <= 1: | ||
| 153 | + return | ||
| 154 | + | ||
| 155 | + def all_reduce_hook(output: torch.Tensor) -> None: | ||
| 156 | + _all_reduce_with_recovery_completion( | ||
| 157 | + output, | ||
| 158 | + replicate_pg=self.replicate_pg, | ||
| 159 | + ) | ||
| 160 | + | ||
| 161 | + num_replicate_modules, num_fsdp_modules = install_all_reduce_hooks( | ||
| 162 | + model_parts, | ||
| 163 | + all_reduce_hook, | ||
| 164 | + ) | ||
| 165 | + | ||
| 166 | + if num_replicate_modules + num_fsdp_modules == 0: | ||
| 167 | + raise RuntimeError("TorchFT synchronous multi-replica training requires replicate-only DP or FSDP") | ||
| 168 | + logger.info( | ||
| 169 | + "[NPU TorchFT] Installed cross-replica hooks on %d replicate-only DP module(s) and %d FSDP module(s)", | ||
| 170 | + num_replicate_modules, | ||
| 171 | + num_fsdp_modules, | ||
| 172 | + ) | ||
| 173 | + | ||
| 174 | + def sync_moe_load_balance_counts(self, model_parts: list[nn.Module]) -> None: | ||
| 175 | + """Make persistent expert-bias updates identical across replicas.""" | ||
| 176 | + if not (self.enabled and self.use_async_quorum) or self.group_size <= 1: | ||
| 177 | + return | ||
| 178 | + | ||
| 179 | + for counter in _iter_moe_load_balance_counts(model_parts): | ||
| 180 | + local_counter = _local_tensor(counter) | ||
| 181 | + _all_reduce_with_recovery_completion( | ||
| 182 | + local_counter, | ||
| 183 | + replicate_pg=self.replicate_pg, | ||
| 184 | + ) | ||
| 185 | + | ||
| 186 | + | ||
| 187 | +register_process_group_factory("hccl", ProcessGroupHCCLEx) | ||
| @@ -0,0 +1,147 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Non-recursive TorchFT optimizer integration for TorchTitan on NPU.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["TorchFTOptimizersContainerEx"] | ||
| 12 | + | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | +from typing import TYPE_CHECKING, Any, cast, overload | ||
| 15 | + | ||
| 16 | +import torch | ||
| 17 | +from torchtitan.components.checkpoint_utils import init_optim_state | ||
| 18 | +from torchtitan.components.optimizer import OptimizersContainer | ||
| 19 | +from torchtitan.experiments.torchft.optimizer import ( | ||
| 20 | + OptimizerAdapter, | ||
| 21 | +) | ||
| 22 | +from torchtitan.experiments.torchft.optimizer import ( | ||
| 23 | + TorchFTOptimizersContainer as _UpstreamTorchFTOptimizersContainer, | ||
| 24 | +) | ||
| 25 | + | ||
| 26 | +from torchtitan_npu.interface.torchft.runtime import OptimizerWrapperEx | ||
| 27 | +from torchtitan_npu.interface.torchft.synchronization import ( | ||
| 28 | + _iter_moe_load_balance_states, | ||
| 29 | + _local_tensor, | ||
| 30 | +) | ||
| 31 | + | ||
| 32 | +if TYPE_CHECKING: | ||
| 33 | + from collections.abc import Callable | ||
| 34 | + | ||
| 35 | + import torch.nn as nn | ||
| 36 | + from torch.optim import Optimizer | ||
| 37 | + | ||
| 38 | + from .manager import FTManagerEx | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +class TorchFTOptimizersContainerEx(OptimizersContainer): | ||
| 42 | + """TorchTitan optimizer container with one TorchFT transaction per step.""" | ||
| 43 | + | ||
| 44 | + optimizers: list[Optimizer] | ||
| 45 | + | ||
| 46 | + @dataclass(kw_only=True, slots=True) | ||
| 47 | + class Config(_UpstreamTorchFTOptimizersContainer.Config): | ||
| 48 | + pass | ||
| 49 | + | ||
| 50 | + def __init__( | ||
| 51 | + self, | ||
| 52 | + config: Config, | ||
| 53 | + *, | ||
| 54 | + model_parts: list[nn.Module], | ||
| 55 | + ft_manager: FTManagerEx, | ||
| 56 | + ) -> None: | ||
| 57 | + super().__init__(config, model_parts=model_parts) | ||
| 58 | + for optimizer in self.optimizers: | ||
| 59 | + init_optim_state(optimizer) | ||
| 60 | + | ||
| 61 | + self.cache_state_dict: dict[str, Any] = {} | ||
| 62 | + self._inner_optimizer = cast("Optimizer", OptimizerAdapter(self)) | ||
| 63 | + self._use_ft_optimizer = ft_manager.enabled and ft_manager.use_async_quorum and ft_manager.group_size > 1 | ||
| 64 | + self._moe_bias_snapshots: list[tuple[torch.Tensor, torch.Tensor]] = [] | ||
| 65 | + if self._use_ft_optimizer: | ||
| 66 | + # Model-specific hooks are registered after optimizer construction. | ||
| 67 | + # Install this first so MoE counts are global before TorchTitan's | ||
| 68 | + # load-balancing hook derives and clears the persistent expert bias. | ||
| 69 | + torch.optim.Optimizer.register_step_pre_hook( | ||
| 70 | + self, lambda *_args, **_kwargs: self._prepare_moe_load_balance_step(ft_manager, model_parts) | ||
严重(S1):这里把 pre-hook 注册到 ![]() ![]() | |||
| 71 | + ) | ||
| 72 | + self._npu_ft_optimizer = ( | ||
| 73 | + OptimizerWrapperEx( | ||
| 74 | + ft_manager.manager, | ||
| 75 | + self._inner_optimizer, | ||
| 76 | + ) | ||
| 77 | + if self._use_ft_optimizer | ||
| 78 | + else None | ||
| 79 | + ) | ||
| 80 | + | ||
| 81 | + def init_cache_state_dict(self) -> None: | ||
| 82 | + self.cache_state_dict = super().state_dict() | ||
| 83 | + | ||
| 84 | + def state_dict(self) -> dict[str, Any]: | ||
| 85 | + return self.cache_state_dict | ||
| 86 | + | ||
| 87 | + def load_state_dict(self, state_dict: dict[str, Any]) -> None: | ||
| 88 | + self.cache_state_dict = {} | ||
| 89 | + super().load_state_dict(state_dict) | ||
| 90 | + self.init_cache_state_dict() | ||
| 91 | + | ||
| 92 | + @overload | ||
| 93 | + def step(self, closure: None = None) -> None: | ||
| 94 | + pass | ||
| 95 | + | ||
| 96 | + @overload | ||
| 97 | + def step(self, closure: Callable[[], float]) -> float: | ||
| 98 | + raise NotImplementedError | ||
| 99 | + | ||
| 100 | + def step(self, closure: Callable[[], float] | None = None) -> float | None: | ||
| 101 | + if closure is not None: | ||
| 102 | + raise ValueError("TorchFTOptimizersContainerEx does not support closures") | ||
| 103 | + if self._use_ft_optimizer: | ||
| 104 | + ft_optimizer = self._require_ft_optimizer() | ||
| 105 | + try: | ||
| 106 | + committed = ft_optimizer.step_if_committed() | ||
| 107 | + except Exception: | ||
| 108 | + self._restore_moe_bias_snapshots() | ||
| 109 | + raise | ||
| 110 | + if committed: | ||
| 111 | + self._moe_bias_snapshots.clear() | ||
| 112 | + else: | ||
| 113 | + self._restore_moe_bias_snapshots() | ||
| 114 | + return None | ||
| 115 | + return self._inner_optimizer.step() | ||
| 116 | + | ||
| 117 | + def zero_grad(self, *args: Any, **kwargs: Any) -> None: | ||
| 118 | + if self._use_ft_optimizer: | ||
| 119 | + return self._require_ft_optimizer().zero_grad(*args, **kwargs) | ||
| 120 | + return self._inner_optimizer.zero_grad(*args, **kwargs) | ||
| 121 | + | ||
| 122 | + @torch.no_grad() | ||
| 123 | + def _prepare_moe_load_balance_step( | ||
| 124 | + self, | ||
| 125 | + ft_manager: FTManagerEx, | ||
| 126 | + model_parts: list[nn.Module], | ||
| 127 | + ) -> None: | ||
| 128 | + self._moe_bias_snapshots = [] | ||
| 129 | + for _counter, bias in _iter_moe_load_balance_states(model_parts): | ||
| 130 | + local_bias = _local_tensor(bias) | ||
| 131 | + self._moe_bias_snapshots.append((local_bias, local_bias.detach().clone())) | ||
| 132 | + try: | ||
| 133 | + ft_manager.sync_moe_load_balance_counts(model_parts) | ||
| 134 | + except Exception: | ||
| 135 | + self._restore_moe_bias_snapshots() | ||
| 136 | + raise | ||
| 137 | + | ||
| 138 | + @torch.no_grad() | ||
| 139 | + def _restore_moe_bias_snapshots(self) -> None: | ||
| 140 | + for bias, snapshot in self._moe_bias_snapshots: | ||
| 141 | + bias.copy_(snapshot) | ||
| 142 | + self._moe_bias_snapshots.clear() | ||
| 143 | + | ||
| 144 | + def _require_ft_optimizer(self) -> OptimizerWrapperEx: | ||
| 145 | + if self._npu_ft_optimizer is None: | ||
| 146 | + raise RuntimeError("TorchFT optimizer is not initialized") | ||
| 147 | + return self._npu_ft_optimizer | ||
| @@ -0,0 +1,224 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""NPU fault-tolerant trainer with failed-step replay for HCCL rejoin.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["FaultTolerantTrainerEx"] | ||
| 12 | + | ||
| 13 | +from contextlib import contextmanager | ||
| 14 | +from dataclasses import dataclass, field | ||
| 15 | +from functools import wraps | ||
| 16 | +from threading import RLock | ||
| 17 | +from typing import TYPE_CHECKING, Any, cast | ||
| 18 | + | ||
| 19 | +import torch | ||
| 20 | +from torch.distributed._composable.fsdp.fully_shard import FSDPModule | ||
| 21 | +from torchtitan.config import apply_overrides | ||
| 22 | +from torchtitan.distributed import utils as dist_utils | ||
| 23 | +from torchtitan.experiments.torchft.trainer import ( | ||
| 24 | + FaultTolerantTrainer, | ||
| 25 | + set_chunked_loss_lm_head, | ||
| 26 | +) | ||
| 27 | +from torchtitan.tools.logging import logger | ||
| 28 | + | ||
| 29 | +from torchtitan_npu.interface.torchft.process_group import ProcessGroupHCCLEx | ||
| 30 | +from torchtitan_npu.interface.torchft.replay import Batch, _ReplayableStepIterator | ||
| 31 | +from torchtitan_npu.interface.torchft.runtime import ManagerEx | ||
| 32 | + | ||
| 33 | +from .manager import FTManagerEx | ||
| 34 | +from .optimizer import TorchFTOptimizersContainerEx | ||
| 35 | + | ||
| 36 | +if TYPE_CHECKING: | ||
| 37 | + from collections.abc import Iterator | ||
| 38 | + | ||
| 39 | +_OptimizerConfig = TorchFTOptimizersContainerEx.Config | ||
| 40 | +_MODEL_CONFIG_UPDATE_LOCK = RLock() | ||
| 41 | +_MODEL_CONFIG_UPDATE_METHOD = "update_from_config" | ||
| 42 | +_CUDA_GRAPH_VALIDATOR = "_validate_cuda_graphs" | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def _validate_cuda_graphs(config: FaultTolerantTrainer.Config) -> None: | ||
| 46 | + """Invoke TorchTitan's config finalizer without exposing its private API.""" | ||
| 47 | + getattr(config, _CUDA_GRAPH_VALIDATOR)() | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +@contextmanager | ||
| 51 | +def _finalize_config_after_model_update( | ||
| 52 | + config: FaultTolerantTrainer.Config, | ||
| 53 | +) -> Iterator[None]: | ||
| 54 | + """Run post-update config work at the same lifecycle point as ``Trainer``.""" | ||
| 55 | + if config.model_spec is None: | ||
| 56 | + raise RuntimeError("Fault-tolerant training requires a model specification") | ||
| 57 | + | ||
| 58 | + model_config = config.model_spec.model | ||
| 59 | + model_config_type = type(model_config) | ||
| 60 | + had_own_update = _MODEL_CONFIG_UPDATE_METHOD in vars(model_config_type) | ||
| 61 | + original_descriptor = vars(model_config_type).get(_MODEL_CONFIG_UPDATE_METHOD) | ||
| 62 | + original_update = getattr(model_config_type, _MODEL_CONFIG_UPDATE_METHOD) | ||
| 63 | + config_finalized = False | ||
| 64 | + | ||
| 65 | + @wraps(original_update) | ||
| 66 | + def update_and_finalize_config( | ||
| 67 | + current_model_config: Any, | ||
| 68 | + *, | ||
| 69 | + config: Any, | ||
| 70 | + **kwargs: Any, | ||
| 71 | + ) -> None: | ||
| 72 | + nonlocal config_finalized | ||
| 73 | + original_update(current_model_config, config=config, **kwargs) | ||
| 74 | + if current_model_config is model_config and not config_finalized: | ||
| 75 | + config_finalized = True | ||
| 76 | + if config.override.imports: | ||
| 77 | + apply_overrides(config.override, config) | ||
| 78 | + _validate_cuda_graphs(config) | ||
| 79 | + | ||
| 80 | + # FaultTolerantTrainer has no hook between its model-config update and | ||
| 81 | + # model build. Keep this temporary class patch scoped to synchronous trainer | ||
| 82 | + # construction; each distributed rank constructs one trainer per process. | ||
| 83 | + with _MODEL_CONFIG_UPDATE_LOCK: | ||
| 84 | + setattr(model_config_type, _MODEL_CONFIG_UPDATE_METHOD, update_and_finalize_config) | ||
| 85 | + try: | ||
| 86 | + yield | ||
| 87 | + if not config_finalized: | ||
| 88 | + raise RuntimeError("FaultTolerantTrainer did not update the configured model before building it") | ||
| 89 | + finally: | ||
| 90 | + if had_own_update: | ||
| 91 | + setattr(model_config_type, _MODEL_CONFIG_UPDATE_METHOD, original_descriptor) | ||
| 92 | + else: | ||
| 93 | + delattr(model_config_type, _MODEL_CONFIG_UPDATE_METHOD) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +class FaultTolerantTrainerEx(FaultTolerantTrainer): | ||
| 97 | + """FaultTolerantTrainer with transactional synchronous-HCCL step replay.""" | ||
| 98 | + | ||
| 99 | + @dataclass(kw_only=True, slots=True) | ||
| 100 | + class Config(FaultTolerantTrainer.Config): | ||
| 101 | + optimizer: _OptimizerConfig = field( # pyrefly: ignore [bad-override] | ||
| 102 | + default_factory=TorchFTOptimizersContainerEx.Config | ||
| 103 | + ) | ||
| 104 | + fault_tolerance: FTManagerEx.Config = field( # pyrefly: ignore [bad-override] | ||
| 105 | + default_factory=FTManagerEx.Config | ||
| 106 | + ) | ||
| 107 | + | ||
| 108 | + def __init__(self, config: FaultTolerantTrainerEx.Config) -> None: | ||
| 109 | + with _finalize_config_after_model_update(config): | ||
| 110 | + super().__init__(config) | ||
| 111 | + set_chunked_loss_lm_head(self) | ||
| 112 | + self._replay_iterator: _ReplayableStepIterator | None = None | ||
| 113 | + self._replay_source: Iterator[Batch] | None = None | ||
| 114 | + process_group = self._rejoin_process_group() | ||
| 115 | + if process_group is not None: | ||
| 116 | + process_group.arm_rejoin_workaround() | ||
| 117 | + | ||
| 118 | + def init_distributed(self): | ||
| 119 | + parallel_dims = super().init_distributed() | ||
| 120 | + dist_utils.set_spmd_backend(self.config.parallelism.spmd_backend) | ||
| 121 | + return parallel_dims | ||
| 122 | + | ||
| 123 | + def train_step(self, data_iterator: Iterator[Batch]) -> None: | ||
| 124 | + config = cast("FaultTolerantTrainerEx.Config", self.config).fault_tolerance | ||
| 125 | + | ||
| 126 | + restore_rng = getattr( | ||
| 127 | + getattr(self, "checkpointer", None), | ||
| 128 | + "restore_pending_compute_rng_state", | ||
| 129 | + None, | ||
| 130 | + ) | ||
| 131 | + if self._replay_source is not data_iterator: | ||
| 132 | + self._replay_source = data_iterator | ||
| 133 | + self._replay_iterator = _ReplayableStepIterator( | ||
| 134 | + data_iterator, | ||
| 135 | + self.gradient_accumulation_steps * getattr(self, "num_pipeline_parallel_microbatches", 1), | ||
| 136 | + restore_pending_rng=restore_rng, | ||
| 137 | + ) | ||
| 138 | + replay_iterator = self._replay_iterator | ||
| 139 | + if replay_iterator is None: | ||
| 140 | + raise RuntimeError("Failed to initialize the HCCL replay iterator") | ||
| 141 | + | ||
| 142 | + ntokens_before_step = self.ntokens_seen | ||
| 143 | + for attempt in range(config.hccl_rejoin_max_step_replays + 1): | ||
| 144 | + replay_iterator.begin_attempt() | ||
| 145 | + try: | ||
| 146 | + result = super().train_step(replay_iterator) | ||
| 147 | + except RuntimeError as error: | ||
| 148 | + process_group = self._rejoin_process_group() | ||
| 149 | + if process_group is None or not process_group.consume_step_replay(error): | ||
| 150 | + raise | ||
| 151 | + if attempt >= config.hccl_rejoin_max_step_replays: | ||
| 152 | + raise RuntimeError("Exceeded the configured HCCL failed-step replay limit") from error | ||
| 153 | + | ||
| 154 | + self.ntokens_seen = ntokens_before_step | ||
| 155 | + # stop_device() releases blocked accelerator work before the | ||
| 156 | + # abort worker can acquire the commit lock and restart the | ||
| 157 | + # device. FSDP reset_iter_state() also touches NPU streams and | ||
| 158 | + # events, so it must wait for restart just like the replay. | ||
| 159 | + process_group.wait_for_device() | ||
| 160 | + self._reset_failed_iteration() | ||
| 161 | + self._restore_committed_state() | ||
| 162 | + replay_iterator.rollback() | ||
| 163 | + logger.warning( | ||
| 164 | + "[NPU TorchFT] Replaying trainer step %d after HCCL rejoin (attempt %d/%d)", | ||
| 165 | + self.step, | ||
| 166 | + attempt + 1, | ||
| 167 | + config.hccl_rejoin_max_step_replays, | ||
| 168 | + ) | ||
| 169 | + continue | ||
| 170 | + | ||
| 171 | + replay_iterator.commit() | ||
| 172 | + return result | ||
| 173 | + | ||
| 174 | + raise RuntimeError("HCCL step replay loop exited unexpectedly") | ||
| 175 | + | ||
| 176 | + def _rejoin_process_group(self) -> ProcessGroupHCCLEx | None: | ||
| 177 | + if not self.ft_manager.enabled: | ||
| 178 | + return None | ||
| 179 | + npu_ft_manager = cast("FTManagerEx", self.ft_manager) | ||
| 180 | + process_group = npu_ft_manager.process_group | ||
| 181 | + if isinstance(process_group, ProcessGroupHCCLEx): | ||
| 182 | + return process_group | ||
| 183 | + return None | ||
| 184 | + | ||
| 185 | + def _reset_failed_iteration(self) -> None: | ||
| 186 | + reset_roots = 0 | ||
| 187 | + cleared_grads = 0 | ||
| 188 | + cleared_moe_counters = 0 | ||
| 189 | + for model_part in self.model_parts: | ||
| 190 | + if isinstance(model_part, FSDPModule): | ||
| 191 | + model_part.reset_iter_state() | ||
| 192 | + reset_roots += 1 | ||
| 193 | + for parameter in model_part.parameters(): | ||
| 194 | + if parameter.grad is not None: | ||
| 195 | + parameter.grad = None | ||
| 196 | + cleared_grads += 1 | ||
| 197 | + for module in model_part.modules(): | ||
| 198 | + counter = getattr(module, "tokens_per_expert_E", None) | ||
| 199 | + if isinstance(counter, torch.Tensor): | ||
| 200 | + counter.zero_() | ||
| 201 | + cleared_moe_counters += 1 | ||
| 202 | + | ||
| 203 | + self._clear_aux_loss_accumulators() | ||
| 204 | + | ||
| 205 | + logger.warning( | ||
| 206 | + "[NPU TorchFT] Reset failed iteration: %d FSDP root(s), %d gradient(s), %d MoE counter(s)", | ||
| 207 | + reset_roots, | ||
| 208 | + cleared_grads, | ||
| 209 | + cleared_moe_counters, | ||
| 210 | + ) | ||
| 211 | + | ||
| 212 | + def _clear_aux_loss_accumulators(self) -> None: | ||
| 213 | + for model_part in self.model_parts: | ||
| 214 | + for module in model_part.modules(): | ||
| 215 | + accumulator = getattr(module, "_acc", None) | ||
| 216 | + if isinstance(accumulator, torch.Tensor) and hasattr(module, "inject"): | ||
| 217 | + accumulator.zero_() | ||
| 218 | + | ||
| 219 | + def _restore_committed_state(self) -> None: | ||
| 220 | + npu_ft_manager = cast("FTManagerEx", self.ft_manager) | ||
| 221 | + manager = npu_ft_manager.manager | ||
| 222 | + if not isinstance(manager, ManagerEx): | ||
| 223 | + raise RuntimeError("HCCL rejoin requires ManagerEx") | ||
| 224 | + manager.restore_committed_state() | ||
| @@ -57,23 +57,56 @@ class TrainerEx(Trainer): | |||
| 57 | "TP _StridedShard and PP stage-local parameter groups are not admitted yet" | 57 | "TP _StridedShard and PP stage-local parameter groups are not admitted yet" |
| 58 | ) | 58 | ) |
| 59 | 59 | ||
| 60 | + def build(self, **kwargs: Any): | ||
| 61 | + """Build the standard trainer or late-bind TorchFT when enabled.""" | ||
| 62 | + if not self.extension.torchft.enable: | ||
| 63 | + return Trainer.Config.build(self, **kwargs) | ||
| 64 | + | ||
| 65 | + _prepare_npu_training(self) | ||
| 66 | + return self._as_torchft_config().build(**kwargs) | ||
| 67 | + | ||
| 68 | + def _as_torchft_config(self): | ||
| 69 | + """Derive the fault-tolerant trainer config without eager TorchFT imports.""" | ||
| 70 | + from torchtitan.config import derive | ||
| 71 | + | ||
| 72 | + from torchtitan_npu.patches import torchft as torchft_patches | ||
| 73 | + | ||
| 74 | + torchft_patches.apply() | ||
| 75 | + from torchtitan_npu.extensions.torchft import ( | ||
| 76 | + FaultTolerantTrainerEx, | ||
| 77 | + FTManagerEx, | ||
| 78 | + TorchFTCheckpointManagerEx, | ||
| 79 | + TorchFTOptimizersContainerEx, | ||
| 80 | + ) | ||
| 81 | + | ||
| 82 | + torchft = self.extension.torchft | ||
| 83 | + return derive( | ||
| 84 | + self, | ||
| 85 | + FaultTolerantTrainerEx.Config, | ||
| 86 | + optimizer=derive(self.optimizer, TorchFTOptimizersContainerEx.Config), | ||
| 87 | + checkpoint=derive( | ||
| 88 | + self.checkpoint, | ||
| 89 | + TorchFTCheckpointManagerEx.Config, | ||
| 90 | + enable_ft_dataloader_checkpoints=torchft.enable_ft_dataloader_checkpoints, | ||
| 91 | + ), | ||
| 92 | + fault_tolerance=FTManagerEx.Config( | ||
| 93 | + enable=True, | ||
| 94 | + process_group="hccl", | ||
| 95 | + process_group_timeout_ms=torchft.process_group_timeout_ms, | ||
| 96 | + replica_id=torchft.replica_id, | ||
| 97 | + group_size=torchft.group_size, | ||
| 98 | + min_replica_size=torchft.min_replica_size, | ||
| 99 | + semi_sync_method=None, | ||
| 100 | + init_sync=torchft.init_sync, | ||
| 101 | + hccl_active_work_grace_ms=torchft.hccl_active_work_grace_ms, | ||
| 102 | + hccl_device_restart_wait_timeout_ms=torchft.hccl_device_restart_wait_timeout_ms, | ||
| 103 | + hccl_watchdog_timeout_margin_ms=torchft.hccl_watchdog_timeout_margin_ms, | ||
| 104 | + hccl_rejoin_max_step_replays=torchft.hccl_rejoin_max_step_replays, | ||
| 105 | + ), | ||
| 106 | + ) | ||
| 107 | + | ||
| 60 | def __init__(self, config: Config): | 108 | def __init__(self, config: Config): |
| 61 | - quantization_config = config.extension.quantization | 109 | + _prepare_npu_training(config) |
| 62 | - if quantization_config.enable_quantized_training: | ||
| 63 | - from interfaces.torchao_converter import apply_quantization_converter | ||
| 64 | - | ||
| 65 | - logger.info( | ||
| 66 | - "Applying TorchAO-NPU quantization recipe=%s before Trainer initialization", | ||
| 67 | - quantization_config.recipe, | ||
| 68 | - ) | ||
| 69 | - model_compile_enabled = config.compile.enable and "model" in config.compile.components | ||
| 70 | - config.model_spec = apply_quantization_converter( | ||
| 71 | - config.model_spec, | ||
| 72 | - quantization_config, | ||
| 73 | - model_compile_enabled=model_compile_enabled, | ||
| 74 | - ) | ||
| 75 | - | ||
| 76 | - set_allow_hf32(config.training.extension.allow_hf32) | ||
| 77 | super().__init__(config) | 110 | super().__init__(config) |
| 78 | self._sdc = config.sdc.build( | 111 | self._sdc = config.sdc.build( |
| 79 | trainer_config=config, | 112 | trainer_config=config, |
| @@ -89,6 +122,26 @@ class TrainerEx(Trainer): | |||
| 89 | return result | 122 | return result |
| 90 | 123 | ||
| 91 | 124 | ||
| 125 | +def _prepare_npu_training(config: TrainerEx.Config) -> None: | ||
| 126 | + """Apply NPU settings shared by standard and fault-tolerant trainers.""" | ||
| 127 | + quantization_config = config.extension.quantization | ||
| 128 | + if quantization_config.enable_quantized_training: | ||
| 129 | + from interfaces.torchao_converter import apply_quantization_converter | ||
| 130 | + | ||
| 131 | + logger.info( | ||
| 132 | + "Applying TorchAO-NPU quantization recipe=%s before Trainer initialization", | ||
| 133 | + quantization_config.recipe, | ||
| 134 | + ) | ||
| 135 | + model_compile_enabled = config.compile.enable and "model" in config.compile.components | ||
| 136 | + config.model_spec = apply_quantization_converter( | ||
| 137 | + config.model_spec, | ||
| 138 | + quantization_config, | ||
| 139 | + model_compile_enabled=model_compile_enabled, | ||
| 140 | + ) | ||
| 141 | + | ||
| 142 | + set_allow_hf32(config.training.extension.allow_hf32) | ||
| 143 | + | ||
| 144 | + | ||
| 92 | config_manager.register_config_converter( | 145 | config_manager.register_config_converter( |
| 93 | Trainer.Config, | 146 | Trainer.Config, |
| 94 | TrainerConfigConverter( | 147 | TrainerConfigConverter( |
| @@ -0,0 +1,64 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Checkpoint state helpers for NPU TorchFT recovery.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +from typing import TYPE_CHECKING | ||
| 12 | + | ||
| 13 | +import torch | ||
| 14 | +import torch.distributed as dist | ||
| 15 | +import torch_npu | ||
| 16 | + | ||
| 17 | +if TYPE_CHECKING: | ||
| 18 | + from torchtitan.components.lr_scheduler import LRSchedulersContainer | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class _TorchRngState: | ||
| 22 | + """Checkpoint the compute RNG streams needed by a replacement replica.""" | ||
| 23 | + | ||
| 24 | + def __init__(self) -> None: | ||
| 25 | + self._pending: dict[str, torch.Tensor] | None = None | ||
| 26 | + | ||
| 27 | + @staticmethod | ||
| 28 | + def _rank_key(name: str) -> str: | ||
| 29 | + rank = dist.get_rank() if dist.is_initialized() else 0 | ||
| 30 | + return f"{name}_rank_{rank}" | ||
| 31 | + | ||
| 32 | + def state_dict(self) -> dict[str, torch.Tensor]: | ||
| 33 | + return { | ||
| 34 | + self._rank_key("cpu"): torch.get_rng_state().clone(), | ||
| 35 | + self._rank_key("npu"): torch_npu.npu.get_rng_state().clone(), | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + def load_state_dict(self, state_dict: dict[str, torch.Tensor]) -> None: | ||
| 39 | + self._pending = { | ||
| 40 | + "cpu": state_dict[self._rank_key("cpu")].clone(), | ||
| 41 | + "npu": state_dict[self._rank_key("npu")].clone(), | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + def restore_pending(self) -> bool: | ||
| 45 | + if self._pending is None: | ||
| 46 | + return False | ||
| 47 | + torch.set_rng_state(self._pending["cpu"]) | ||
| 48 | + torch_npu.npu.set_rng_state(self._pending["npu"]) | ||
| 49 | + self._pending = None | ||
| 50 | + return True | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +def _restore_optimizer_learning_rates(lr_schedulers: LRSchedulersContainer) -> None: | ||
| 54 | + """Apply restored scheduler rates to their live optimizer param groups.""" | ||
| 55 | + for scheduler in lr_schedulers.schedulers: | ||
| 56 | + last_lrs = scheduler.get_last_lr() | ||
| 57 | + if len(last_lrs) != len(scheduler.optimizer.param_groups): | ||
| 58 | + raise RuntimeError("Restored LR scheduler state does not match optimizer param groups") | ||
| 59 | + for param_group, learning_rate in zip( | ||
| 60 | + scheduler.optimizer.param_groups, | ||
| 61 | + last_lrs, | ||
| 62 | + strict=True, | ||
| 63 | + ): | ||
| 64 | + param_group["lr"] = learning_rate | ||
| @@ -0,0 +1,97 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +"""Per-replica dataloader checkpoint storage independent of model DCP.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["ReplicaDataloaderCheckpoint"] | ||
| 12 | + | ||
| 13 | +import time | ||
| 14 | +from concurrent.futures import Future | ||
| 15 | +from typing import TYPE_CHECKING, Any | ||
| 16 | + | ||
| 17 | +from torchtitan.components.checkpoint import DATALOADER, AsyncMode | ||
| 18 | +from torchtitan.tools import filesystem | ||
| 19 | +from torchtitan.tools.logging import logger | ||
| 20 | +from torchtitan.tools.utils import GarbageCollection | ||
| 21 | + | ||
| 22 | +if TYPE_CHECKING: | ||
| 23 | + from collections.abc import Callable | ||
| 24 | + | ||
| 25 | + from torchtitan.components.dataloader import BaseDataLoader | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class ReplicaDataloaderCheckpoint: | ||
| 29 | + """Own the async future and storage namespace for one replica's cursor.""" | ||
| 30 | + | ||
| 31 | + def __init__( | ||
| 32 | + self, | ||
| 33 | + *, | ||
| 34 | + dataloader: BaseDataLoader | None, | ||
| 35 | + replica_id: int, | ||
| 36 | + folder: str, | ||
| 37 | + dcp_save: Callable[..., Any], | ||
| 38 | + dcp_load: Callable[..., None], | ||
| 39 | + create_checkpoint_id: Callable[..., str], | ||
| 40 | + find_load_step: Callable[..., int], | ||
| 41 | + ) -> None: | ||
| 42 | + self.states = {DATALOADER: dataloader} | ||
| 43 | + self._folder = filesystem.join(folder, f"ft-replicat-{replica_id}") | ||
| 44 | + self._dcp_save = dcp_save | ||
| 45 | + self._dcp_load = dcp_load | ||
| 46 | + self._create_checkpoint_id = create_checkpoint_id | ||
| 47 | + self._find_load_step = find_load_step | ||
| 48 | + self._save_future: Future[Any] | None = None | ||
| 49 | + | ||
| 50 | + def save(self, step: int) -> None: | ||
| 51 | + self.wait() | ||
| 52 | + begin = time.monotonic() | ||
| 53 | + checkpoint_id = self._create_checkpoint_id(step, folder=self._folder) | ||
| 54 | + result = self._dcp_save( | ||
| 55 | + self.states, | ||
| 56 | + checkpoint_id=checkpoint_id, | ||
| 57 | + async_mode=AsyncMode.ASYNC, | ||
| 58 | + ) | ||
| 59 | + if not isinstance(result, Future): | ||
| 60 | + raise RuntimeError("Async dataloader checkpoint did not return a Future") | ||
| 61 | + self._save_future = result | ||
| 62 | + logger.info( | ||
| 63 | + "Staging torchft checkpoint took %s secs.", | ||
| 64 | + time.monotonic() - begin, | ||
| 65 | + ) | ||
| 66 | + | ||
| 67 | + def load(self, step: int = -1) -> None: | ||
| 68 | + self.wait() | ||
| 69 | + if step == -1: | ||
| 70 | + step = self._find_load_step(folder=self._folder) | ||
| 71 | + if step == -1: | ||
| 72 | + return | ||
| 73 | + | ||
| 74 | + begin = time.monotonic() | ||
| 75 | + logger.info("Loading the FT checkpoint at step %s.", step) | ||
| 76 | + checkpoint_id = self._create_checkpoint_id(step, folder=self._folder) | ||
| 77 | + self._dcp_load( | ||
| 78 | + self.states, | ||
| 79 | + checkpoint_id=checkpoint_id, | ||
| 80 | + from_hf=False, | ||
| 81 | + from_quantized=False, | ||
| 82 | + ) | ||
| 83 | + GarbageCollection.collect("GC collection for checkpoint loading.") | ||
| 84 | + logger.info( | ||
| 85 | + "Finished loading the torchft checkpoint in %.2f seconds.", | ||
| 86 | + time.monotonic() - begin, | ||
| 87 | + ) | ||
| 88 | + | ||
| 89 | + def wait(self) -> None: | ||
| 90 | + future = self._save_future | ||
| 91 | + if future is None: | ||
| 92 | + return | ||
| 93 | + future.result() | ||
| 94 | + self._save_future = None | ||
| 95 | + | ||
| 96 | + def close(self) -> None: | ||
| 97 | + self.wait() | ||


一般(S2):配置校验没有检查
replica_id是否在[0, group_size)。例如group_size=2, replica_id=2会使get_dp_info()产生越界全局 DP rank,并可能创建无法匹配的 TorchFT replica 身份;应在启用 FT 时尽早拒绝该配置。