Closed
feat: 增加 TorchFT HCCL runtime 与 rejoin #676
zhangyifan999Add on Sep 1Closed at Oct 12
feat: 增加 TorchFT HCCL runtime 与 rejoin #676
Closed
Total: 10 files changed+1592-0
| @@ -28,6 +28,7 @@ ignore-missing-imports = [ | |||
| 28 | "torchao.*", | 28 | "torchao.*", |
| 29 | "torchao_npu.*", | 29 | "torchao_npu.*", |
| 30 | "torchft", | 30 | "torchft", |
| 31 | + "torchft.*", | ||
| 31 | "cann_ops_transformer", | 32 | "cann_ops_transformer", |
| 32 | "cann_ops_transformer.*", | 33 | "cann_ops_transformer.*", |
| 33 | "tile_kernels", | 34 | "tile_kernels", |
| @@ -0,0 +1,6 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# | ||
| 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. | ||
| 5 | + | ||
| 6 | +"""NPU-specific service interfaces used by optional integrations.""" | ||
| @@ -0,0 +1,18 @@ | |||
| 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 runtime and HCCL interfaces for TorchFT.""" | ||
| 8 | + | ||
| 9 | +from .managed_process_group import LossManagedProcessGroupEx | ||
| 10 | +from .process_group import ProcessGroupHCCLEx | ||
| 11 | +from .runtime import ManagerEx, OptimizerWrapperEx | ||
| 12 | + | ||
| 13 | +__all__ = [ | ||
| 14 | + "LossManagedProcessGroupEx", | ||
| 15 | + "ManagerEx", | ||
| 16 | + "OptimizerWrapperEx", | ||
| 17 | + "ProcessGroupHCCLEx", | ||
| 18 | +] | ||
| @@ -0,0 +1,32 @@ | |||
| 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 | +"""Managed process-group behavior used by NPU TorchFT integration.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["LossManagedProcessGroupEx"] | ||
| 12 | + | ||
| 13 | +from typing import TYPE_CHECKING | ||
| 14 | + | ||
| 15 | +from torch.distributed.distributed_c10d import ReduceOp, Work | ||
| 16 | +from torchft.process_group import ManagedProcessGroup | ||
| 17 | + | ||
| 18 | +if TYPE_CHECKING: | ||
| 19 | + import torch | ||
| 20 | + from torchft.manager import Manager | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class LossManagedProcessGroupEx(ManagedProcessGroup): | ||
| 24 | + """Average floating-point losses while preserving other reduction ops.""" | ||
| 25 | + | ||
| 26 | + _manager: Manager | ||
| 27 | + | ||
| 28 | + def allreduce(self, tensors: list[torch.Tensor], opts: object) -> Work: | ||
| 29 | + reduce_op = opts if isinstance(opts, ReduceOp) else getattr(opts, "reduceOp", None) | ||
| 30 | + if len(tensors) == 1 and tensors[0].is_floating_point() and reduce_op == ReduceOp.SUM: | ||
| 31 | + return self._manager.allreduce(tensors[0], reduce_op=ReduceOp.AVG) | ||
| 32 | + return super().allreduce(tensors, opts) | ||
| @@ -0,0 +1,677 @@ | |||
| 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 | +"""Experimental whole-device recovery for a TorchFT HCCL process group.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +__all__ = ["ProcessGroupHCCLEx"] | ||
| 12 | + | ||
| 13 | +import logging | ||
| 14 | +import os | ||
| 15 | +import threading | ||
| 16 | +from contextlib import contextmanager | ||
| 17 | +from dataclasses import dataclass | ||
| 18 | +from datetime import timedelta | ||
| 19 | +from typing import TYPE_CHECKING, Any | ||
| 20 | + | ||
| 21 | +import torch | ||
| 22 | +from torch.distributed import ProcessGroup as BaseProcessGroup | ||
| 23 | +from torch.distributed import Store | ||
| 24 | +from torchft.futures import context_timeout | ||
| 25 | +from torchft.process_group import ProcessGroupWrapper | ||
| 26 | + | ||
| 27 | +from .work import TrackedHcclWork | ||
| 28 | +from .work_tracker import HcclWorkTracker | ||
| 29 | + | ||
| 30 | +if TYPE_CHECKING: | ||
| 31 | + from collections.abc import Callable, Generator | ||
| 32 | + | ||
| 33 | + from torch.distributed.distributed_c10d import Work | ||
| 34 | + | ||
| 35 | +logger = logging.getLogger(__name__) | ||
| 36 | +_WATCHDOG_STATUS_STOP = 2 | ||
| 37 | +_DEFAULT_TIMEOUT = timedelta(seconds=60) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def _hccl_group_id( | ||
| 41 | + quorum_id: int | None, | ||
| 42 | + group_rank: int | None, | ||
| 43 | + group_world_size: int | None, | ||
| 44 | +) -> str: | ||
| 45 | + group_id = f"torchft_quorum_{quorum_id}" | ||
| 46 | + if group_rank is not None and group_world_size: | ||
| 47 | + group_id += f"_rank_{group_rank % group_world_size}" | ||
| 48 | + return group_id | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +class _StepReplayError(RuntimeError): | ||
| 52 | + """Signal that the step interrupted by NPU device restart must be replayed.""" | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +@dataclass(frozen=True, slots=True) | ||
| 56 | +class _AbortPlan: | ||
| 57 | + process_group: BaseProcessGroup | ||
| 58 | + current_device: int | None | ||
| 59 | + backend: Any | None | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def _private_attr(owner: Any, name: str) -> Any: | ||
| 63 | + """Access a fixed-version backend API that PyTorch does not expose publicly.""" | ||
| 64 | + return getattr(owner, name) | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +def _set_private_attr(owner: Any, name: str, value: Any) -> None: | ||
| 68 | + setattr(owner, name, value) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _get_process_group_backend(process_group: BaseProcessGroup, device: torch.device) -> Any: | ||
| 72 | + return _private_attr(process_group, "_get_backend")(device) | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +def _configure_hccl_options(options: Any, timeout: timedelta) -> None: | ||
| 76 | + _set_private_attr(options, "_timeout", timeout) | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +def _initialize_process_group_backend(process_group: BaseProcessGroup, backend: Any) -> None: | ||
| 80 | + _private_attr(backend, "_set_sequence_number_for_group")() | ||
| 81 | + _private_attr(process_group, "_set_default_backend")(BaseProcessGroup.BackendType.CUSTOM) | ||
| 82 | + _private_attr(process_group, "_register_backend")( | ||
| 83 | + torch.device("npu"), | ||
| 84 | + BaseProcessGroup.BackendType.CUSTOM, | ||
| 85 | + backend, | ||
| 86 | + ) | ||
| 87 | + | ||
| 88 | + | ||
| 89 | +def _local_npu_process_groups(excluded_group: BaseProcessGroup) -> tuple[BaseProcessGroup, ...]: | ||
| 90 | + from torch.distributed import distributed_c10d | ||
| 91 | + | ||
| 92 | + npu_device = torch.device("npu") | ||
| 93 | + groups = [ | ||
| 94 | + process_group | ||
| 95 | + for process_group in tuple(_private_attr(distributed_c10d, "_pg_map")) | ||
| 96 | + if process_group is not excluded_group and npu_device in _private_attr(process_group, "_device_types") | ||
| 97 | + ] | ||
| 98 | + groups.sort(key=lambda process_group: str(process_group.group_name)) | ||
| 99 | + return tuple(groups) | ||
| 100 | + | ||
| @@ -0,0 +1,111 @@ | |||
| 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 | +"""Replay state for transactional NPU training steps.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +import random | ||
| 12 | +from collections.abc import Callable, Iterator | ||
| 13 | +from dataclasses import dataclass | ||
| 14 | +from typing import Any | ||
| 15 | + | ||
| 16 | +import numpy as np | ||
| 17 | +import torch | ||
| 18 | +import torch_npu | ||
| 19 | + | ||
| 20 | +Batch = tuple[dict[str, torch.Tensor], torch.Tensor] | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _clone_batch(batch: Batch) -> Batch: | ||
| 24 | + input_dict, labels = batch | ||
| 25 | + return ({name: value.clone() for name, value in input_dict.items()}, labels.clone()) | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def _snapshot_batch(batch: Batch) -> Batch: | ||
| 29 | + input_dict, labels = batch | ||
| 30 | + return ( | ||
| 31 | + {name: value.detach().to(device="cpu", copy=True) for name, value in input_dict.items()}, | ||
| 32 | + labels.detach().to(device="cpu", copy=True), | ||
| 33 | + ) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +@dataclass | ||
| 37 | +class _ComputeRngState: | ||
| 38 | + python: tuple[int, tuple[int, ...], float | None] | ||
| 39 | + numpy: tuple[Any, ...] | dict[str, Any] | ||
| 40 | + cpu: torch.Tensor | ||
| 41 | + npu: torch.Tensor | ||
| 42 | + | ||
| 43 | + @classmethod | ||
| 44 | + def capture(cls) -> _ComputeRngState: | ||
| 45 | + return cls( | ||
| 46 | + python=random.getstate(), | ||
| 47 | + numpy=np.random.get_state(), | ||
| 48 | + cpu=torch.get_rng_state(), | ||
| 49 | + npu=torch_npu.npu.get_rng_state(), | ||
| 50 | + ) | ||
| 51 | + | ||
| 52 | + def restore(self) -> None: | ||
| 53 | + random.setstate(self.python) | ||
| 54 | + np.random.set_state(self.numpy) | ||
| 55 | + torch.set_rng_state(self.cpu) | ||
| 56 | + torch_npu.npu.set_rng_state(self.npu) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +class _ReplayableStepIterator(Iterator[Batch]): | ||
| 60 | + """Cache one gradient-accumulation window for an exact compute replay.""" | ||
| 61 | + | ||
| 62 | + def __init__( | ||
| 63 | + self, | ||
| 64 | + source: Iterator[Batch], | ||
| 65 | + batches_per_step: int, | ||
| 66 | + restore_pending_rng: Callable[[], object] | None = None, | ||
| 67 | + ) -> None: | ||
| 68 | + self.source = source | ||
| 69 | + self.batches_per_step = batches_per_step | ||
| 70 | + self.restore_pending_rng = restore_pending_rng | ||
| 71 | + self._batches: list[Batch] = [] | ||
| 72 | + self._compute_rng_states: list[_ComputeRngState] = [] | ||
| 73 | + self._cursor = 0 | ||
| 74 | + self._replaying = False | ||
| 75 | + | ||
| 76 | + def __iter__(self) -> _ReplayableStepIterator: | ||
| 77 | + return self | ||
| 78 | + | ||
| 79 | + def __next__(self) -> Batch: | ||
| 80 | + if self._cursor < len(self._batches): | ||
| 81 | + batch = self._batches[self._cursor] | ||
| 82 | + if not self._replaying: | ||
| 83 | + raise RuntimeError("Cached batches may only be consumed during a replay") | ||
| 84 | + self._compute_rng_states[self._cursor].restore() | ||
| 85 | + else: | ||
| 86 | + if self._cursor == 0 and self.restore_pending_rng is not None: | ||
| 87 | + self.restore_pending_rng() | ||
| 88 | + # stop_device() may invalidate prefetched NPU input tensors. | ||
| 89 | + batch = _snapshot_batch(next(self.source)) | ||
| 90 | + self._batches.append(batch) | ||
| 91 | + self._compute_rng_states.append(_ComputeRngState.capture()) | ||
| 92 | + | ||
| 93 | + self._cursor += 1 | ||
| 94 | + return _clone_batch(batch) | ||
| 95 | + | ||
| 96 | + def begin_attempt(self) -> None: | ||
| 97 | + if self._cursor != 0: | ||
| 98 | + raise RuntimeError("A replayable step attempt is already active") | ||
| 99 | + self._replaying = bool(self._batches) | ||
| 100 | + | ||
| 101 | + def commit(self) -> None: | ||
| 102 | + if self._cursor != self.batches_per_step: | ||
| 103 | + raise RuntimeError("Cannot commit an incomplete replayable step") | ||
| 104 | + self._batches.clear() | ||
| 105 | + self._compute_rng_states.clear() | ||
| 106 | + self._cursor = 0 | ||
| 107 | + self._replaying = False | ||
| 108 | + | ||
| 109 | + def rollback(self) -> None: | ||
| 110 | + self._cursor = 0 | ||
| 111 | + self._replaying = bool(self._batches) | ||
| @@ -0,0 +1,486 @@ | |||
| 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 runtime adaptations for the fixed TorchFT dependency.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +import logging | ||
| 12 | +import threading | ||
| 13 | +from typing import TYPE_CHECKING, Any, cast | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | +import torch.distributed as dist | ||
| 17 | +import torch_npu | ||
| 18 | +from torch.distributed.tensor import DTensor | ||
| 19 | +from torch.utils._pytree import tree_flatten, tree_unflatten | ||
| 20 | +from torchft.manager import Manager | ||
| 21 | +from torchft.optim import OptimizerWrapper | ||
| 22 | + | ||
| 23 | +from .process_group import ProcessGroupHCCLEx, _StepReplayError | ||
| 24 | + | ||
| 25 | +if TYPE_CHECKING: | ||
| 26 | + from collections.abc import Callable | ||
| 27 | + from concurrent.futures import Future | ||
| 28 | + from datetime import timedelta | ||
| 29 | + | ||
| 30 | + from torch.optim import Optimizer | ||
| 31 | + from torchft.process_group import ProcessGroup | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +logger = logging.getLogger(__name__) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def _clone_containers[T](value: T) -> T: | ||
| 38 | + """Clone a pytree's containers while preserving tensor identities.""" | ||
| 39 | + leaves, spec = tree_flatten(value) | ||
| 40 | + return cast("T", tree_unflatten(leaves, spec)) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +def _registered_training_state( | ||
| 44 | + callbacks: dict[str, Callable[[], object]], | ||
| 45 | + training_thread_keys: set[str], | ||
| 46 | +) -> dict[str, object]: | ||
| 47 | + """Materialize callbacks that must run on every rank's training thread.""" | ||
| 48 | + return {key: callback() for key, callback in callbacks.items() if key in training_thread_keys} | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _lazy_state_dict_callbacks( | ||
| 52 | + callbacks: dict[str, Callable[[], object]], | ||
| 53 | + training_thread_keys: set[str], | ||
| 54 | +) -> dict[str, Callable[[], object]]: | ||
| 55 | + """Return callbacks that remain safe to execute on recovery workers.""" | ||
| 56 | + return {key: callback for key, callback in callbacks.items() if key not in training_thread_keys} | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _barrier_initial_replica_ranks(quorum_id: int, group_world_size: int) -> None: | ||
| 60 | + """Keep replica-local ranks aligned before the first quorum transition.""" | ||
| 61 | + if quorum_id == -1 and group_world_size > 1 and dist.is_initialized(): | ||
| 62 | + dist.barrier() | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def _npu_synchronize() -> None: | ||
| 66 | + torch_npu.npu.synchronize() | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _to_cpu[T](values: list[T], pin_memory: bool) -> list[T]: | ||
| 70 | + out: list[Any] = [] | ||
| 71 | + for value in values: | ||
| 72 | + if isinstance(value, torch.Tensor) and value.device.type == "npu": | ||
| 73 | + if pin_memory: | ||
| 74 | + cpu = torch.empty(*tuple(value.size()), dtype=value.dtype, pin_memory=True) | ||
| 75 | + cpu.copy_(value, non_blocking=False) | ||
| 76 | + out.append(cpu) | ||
严重(S1): ![]() ![]() | |||
| 77 | + else: | ||
| 78 | + out.append(value.cpu()) | ||
| 79 | + else: | ||
| 80 | + out.append(value) | ||
| 81 | + return out | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +class _RecoveryStateStager: | ||
| 85 | + """Cache NPU tensors in CPU memory without copying CPU optimizer state.""" | ||
| 86 | + | ||
| 87 | + def __init__(self) -> None: | ||
| 88 | + self._copy_pending = False | ||
| 89 | + self._cpu_npu_state: dict[str, torch.Tensor] | None = None | ||
| 90 | + self._pending_state: dict[str, object] | None = None | ||
| 91 | + self._staged_state: dict[str, object] | None = None | ||
| 92 | + self._lock = threading.Lock() | ||
| 93 | + self._ready = threading.Event() | ||
| 94 | + | ||
| 95 | + def stage( | ||
| 96 | + self, | ||
| 97 | + state_dict: dict[str, object], | ||
| 98 | + ) -> dict[str, object]: | ||
| 99 | + self.wait() | ||
| 100 | + leaves, spec = tree_flatten(state_dict) | ||
| 101 | + npu_state = { | ||
| 102 | + str(index): value | ||
| 103 | + for index, value in enumerate(leaves) | ||
| 104 | + if isinstance(value, torch.Tensor) and value.device.type == "npu" | ||
| 105 | + } | ||
| 106 | + if not npu_state: | ||
| 107 | + staged = cast("dict[str, object]", tree_unflatten(leaves, spec)) | ||
| 108 | + self.replace(staged) | ||
| 109 | + return staged | ||
| 110 | + | ||
| 111 | + self._resize_cache(npu_state) | ||
| 112 | + cpu_npu_state = self._cpu_npu_state | ||
| 113 | + if cpu_npu_state is None: | ||
| 114 | + raise RuntimeError("NPU recovery state cache was not initialized") | ||
| 115 | + | ||
| 116 | + with self._lock: | ||
| 117 | + self._ready.clear() | ||
| 118 | + self._copy_pending = True | ||
| 119 | + for key, value in npu_state.items(): | ||
| 120 | + local_value = value.to_local() if isinstance(value, DTensor) else value | ||
| 121 | + cpu_npu_state[key].copy_(local_value, non_blocking=True) | ||
| 122 | + | ||
| 123 | + staged_leaves = list(leaves) | ||
| 124 | + for index, value in cpu_npu_state.items(): | ||
| 125 | + staged_leaves[int(index)] = value | ||
| 126 | + staged = cast("dict[str, object]", tree_unflatten(staged_leaves, spec)) | ||
| 127 | + self._pending_state = staged | ||
| 128 | + return staged | ||
| 129 | + | ||
| 130 | + def _resize_cache(self, npu_state: dict[str, torch.Tensor]) -> None: | ||
| 131 | + old_cache = self._cpu_npu_state or {} | ||
| 132 | + new_cache = {} | ||
| 133 | + for key, value in npu_state.items(): | ||
| 134 | + local_value = value.to_local() if isinstance(value, DTensor) else value | ||
| 135 | + cached_value = old_cache.get(key) | ||
| 136 | + if cached_value is None or ( | ||
| 137 | + cached_value.shape != local_value.shape | ||
| 138 | + or cached_value.stride() != local_value.stride() | ||
| 139 | + or cached_value.dtype != local_value.dtype | ||
| 140 | + ): | ||
| 141 | + cached_value = self._allocate_cpu_tensor(value) | ||
| 142 | + new_cache[key] = cached_value | ||
| 143 | + self._cpu_npu_state = new_cache | ||
严重(S1): ![]() ![]() | |||
| 144 | + | ||
| 145 | + @staticmethod | ||
| 146 | + def _allocate_cpu_tensor(value: torch.Tensor) -> torch.Tensor: | ||
| 147 | + local_tensor = value.to_local() if isinstance(value, DTensor) else value | ||
| 148 | + return torch.empty_strided( | ||
| 149 | + local_tensor.size(), | ||
| 150 | + local_tensor.stride(), | ||
| 151 | + dtype=local_tensor.dtype, | ||
| 152 | + device="cpu", | ||
| 153 | + pin_memory=True, | ||
| 154 | + ) | ||
| 155 | + | ||
| 156 | + def wait(self) -> dict[str, object] | None: | ||
| 157 | + with self._lock: | ||
| 158 | + copy_pending = self._copy_pending | ||
| 159 | + if copy_pending: | ||
| 160 | + _npu_synchronize() | ||
| 161 | + with self._lock: | ||
| 162 | + if self._copy_pending: | ||
| 163 | + self._copy_pending = False | ||
| 164 | + self._staged_state = self._pending_state | ||
| 165 | + self._pending_state = None | ||
| 166 | + self._ready.set() | ||
| 167 | + with self._lock: | ||
| 168 | + return self._staged_state | ||
| 169 | + | ||
| 170 | + def snapshot(self) -> dict[str, object] | None: | ||
| 171 | + """Return a published snapshot without calling NPU APIs.""" | ||
| 172 | + while True: | ||
| 173 | + self._ready.wait() | ||
| 174 | + with self._lock: | ||
| 175 | + if self._copy_pending: | ||
| 176 | + continue | ||
| 177 | + state = self._staged_state | ||
| 178 | + if state is None: | ||
| 179 | + return None | ||
| 180 | + leaves, spec = tree_flatten(state) | ||
| 181 | + immutable_leaves = [ | ||
| 182 | + value.detach().clone() if isinstance(value, torch.Tensor) else value for value in leaves | ||
| 183 | + ] | ||
| 184 | + return cast("dict[str, object]", tree_unflatten(immutable_leaves, spec)) | ||
| 185 | + | ||
| 186 | + def replace(self, state_dict: dict[str, object]) -> None: | ||
| 187 | + self.wait() | ||
| 188 | + with self._lock: | ||
| 189 | + self._staged_state = state_dict | ||
| 190 | + self._pending_state = None | ||
| 191 | + self._ready.set() | ||
| 192 | + | ||
| 193 | + | ||
| 194 | +def install_torchft_npu_runtime_patches() -> None: | ||
| 195 | + """Install the NPU-specific HTTP staging extension.""" | ||
| 196 | + import torchft.checkpointing.http_transport as http_transport | ||
| 197 | + | ||
| 198 | + http_transport._to_cpu = _to_cpu | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +class ManagerEx(Manager): | ||
| 202 | + """TorchFT manager with FSDP-safe state staging on the training thread.""" | ||
| 203 | + | ||
| 204 | + _apply_pending_state_dict: Callable[[], None] | ||
| 205 | + _group_world_size: int | ||
| 206 | + _healing: bool | ||
| 207 | + _is_state_dict_read_allowed: bool | ||
| 208 | + _pg: ProcessGroup | ||
| 209 | + _quorum_future: Future[object] | None | ||
| 210 | + _quorum_id: int | ||
| 211 | + _state_dict_lock: Any | ||
| 212 | + _load_state_dict_fns: dict[str, Callable[[object], None]] | ||
| 213 | + _pending_state_dict: dict[str, object] | None | ||
| 214 | + _user_state_dicts: dict[str, Callable[[], object]] | ||
| 215 | + state_dict: Callable[[], dict[str, int]] | ||
| 216 | + | ||
| 217 | + def __init__(self, *args: Any, **kwargs: Any) -> None: | ||
| 218 | + install_torchft_npu_runtime_patches() | ||
| 219 | + super().__init__(*args, **kwargs) | ||
| 220 | + self._state_dicts_on_training_thread: set[str] = set() | ||
| 221 | + self._staged_user_state_dict: dict[str, object] | None = None | ||
| 222 | + self._recovery_state_stager = _RecoveryStateStager() | ||
| 223 | + self._healing_snapshot_prepared = False | ||
| 224 | + set_snapshot_ready = getattr(self._pg, "set_recovery_state_ready_callback", None) | ||
| 225 | + if callable(set_snapshot_ready): | ||
| 226 | + self._recovery_snapshot_supported = True | ||
| 227 | + set_snapshot_ready(self.wait_for_recovery_snapshot) | ||
| 228 | + else: | ||
| 229 | + self._recovery_snapshot_supported = False | ||
| 230 | + | ||
| 231 | + @property | ||
| 232 | + def process_group(self) -> object | None: | ||
| 233 | + return self._pg | ||
| 234 | + | ||
| 235 | + @property | ||
| 236 | + def quorum_is_uninitialized(self) -> bool: | ||
| 237 | + return self._quorum_id == -1 | ||
| 238 | + | ||
| 239 | + def _recovery_snapshot_enabled(self) -> bool: | ||
| 240 | + return self._recovery_snapshot_supported and bool(getattr(self._pg, "rejoin_workaround_enabled", False)) | ||
| 241 | + | ||
| 242 | + def apply_pending_healing_state(self) -> None: | ||
| 243 | + if not self._healing: | ||
| 244 | + return | ||
| 245 | + pending_state_dict = self._pending_state_dict | ||
| 246 | + pending_user_state = ( | ||
| 247 | + _clone_containers(cast("dict[str, object]", pending_state_dict["user"])) | ||
| 248 | + if pending_state_dict is not None | ||
| 249 | + else None | ||
| 250 | + ) | ||
| 251 | + self._apply_pending_state_dict() | ||
| 252 | + if pending_user_state is not None: | ||
| 253 | + self._recovery_state_stager.replace(pending_user_state) | ||
| 254 | + self._staged_user_state_dict = pending_user_state | ||
| 255 | + self._healing = False | ||
| 256 | + | ||
| 257 | + def wait_for_recovery_snapshot(self) -> dict[str, object] | None: | ||
| 258 | + """Wait for the last committed NPU state to finish staging on CPU.""" | ||
| 259 | + staged = self._recovery_state_stager.wait() | ||
| 260 | + if staged is not None: | ||
| 261 | + self._staged_user_state_dict = staged | ||
| 262 | + return self._staged_user_state_dict | ||
| 263 | + | ||
| 264 | + def published_recovery_snapshot(self) -> dict[str, object] | None: | ||
| 265 | + """Read recovery state from TorchFT worker threads without touching NPU.""" | ||
| 266 | + staged = self._recovery_state_stager.snapshot() | ||
| 267 | + if staged is not None: | ||
| 268 | + self._staged_user_state_dict = staged | ||
| 269 | + return self._staged_user_state_dict | ||
| 270 | + | ||
| 271 | + def prepare_healing_snapshot(self) -> None: | ||
| 272 | + """Materialize deferred state only when a peer actually needs healing.""" | ||
| 273 | + if self._quorum_future is not None: | ||
| 274 | + self._quorum_future.result() | ||
| 275 | + staged = {key: callback() for key, callback in self._user_state_dicts.items()} | ||
| 276 | + self._recovery_state_stager.stage(staged) | ||
| 277 | + self.wait_for_recovery_snapshot() | ||
| 278 | + self._healing_snapshot_prepared = True | ||
| 279 | + | ||
| 280 | + def restore_committed_state(self) -> None: | ||
| 281 | + """Restore state damaged by whole-device abort before replaying a step.""" | ||
| 282 | + staged = self.wait_for_recovery_snapshot() | ||
| 283 | + if not staged: | ||
| 284 | + raise RuntimeError("TorchFT committed recovery state is not initialized") | ||
| 285 | + for key, load_state_dict in self._load_state_dict_fns.items(): | ||
| 286 | + load_state_dict(_clone_containers(staged[key])) | ||
| 287 | + logger.warning("Restored the last committed TorchFT state after NPU restart") | ||
| 288 | + | ||
| 289 | + @staticmethod | ||
| 290 | + def _restore_npu_leaves(staged_state: object, live_state: object) -> object: | ||
| 291 | + staged_leaves, staged_spec = tree_flatten(staged_state) | ||
| 292 | + live_leaves, live_spec = tree_flatten(live_state) | ||
| 293 | + if staged_spec != live_spec or len(staged_leaves) != len(live_leaves): | ||
| 294 | + raise RuntimeError("TorchFT recovery state structure changed between steps") | ||
| 295 | + | ||
| 296 | + restored_leaves = [] | ||
| 297 | + for staged, live in zip(staged_leaves, live_leaves, strict=True): | ||
| 298 | + if isinstance(live, torch.Tensor) and live.device.type == "npu": | ||
| 299 | + if not isinstance(staged, torch.Tensor): | ||
| 300 | + raise TypeError("NPU recovery tensor was replaced by a non-tensor value") | ||
| 301 | + target = live.to_local() if isinstance(live, DTensor) else live | ||
| 302 | + source = staged.to_local() if isinstance(staged, DTensor) else staged | ||
| 303 | + target.copy_(source) | ||
| 304 | + restored_leaves.append(live) | ||
| 305 | + else: | ||
| 306 | + restored_leaves.append(staged) | ||
| 307 | + return tree_unflatten(restored_leaves, live_spec) | ||
| 308 | + | ||
| 309 | + def allow_state_dict_read(self) -> None: | ||
| 310 | + if self._is_state_dict_read_allowed: | ||
| 311 | + return | ||
| 312 | + _npu_synchronize() | ||
| 313 | + self._is_state_dict_read_allowed = True | ||
| 314 | + self._state_dict_lock.w_release() | ||
| 315 | + | ||
| 316 | + def register_state_dict_fn( | ||
| 317 | + self, | ||
| 318 | + key: str, | ||
| 319 | + load_state_dict, | ||
| 320 | + state_dict, | ||
| 321 | + state_dict_on_training_thread: bool = False, | ||
| 322 | + ) -> None: | ||
| 323 | + def load_recovery_state(staged_state: object) -> None: | ||
| 324 | + if self._recovery_snapshot_enabled(): | ||
| 325 | + staged_state = self._restore_npu_leaves(staged_state, state_dict()) | ||
| 326 | + load_state_dict(staged_state) | ||
| 327 | + | ||
| 328 | + super().register_state_dict_fn(key, load_recovery_state, state_dict) | ||
| 329 | + if state_dict_on_training_thread: | ||
| 330 | + self._state_dicts_on_training_thread.add(key) | ||
| 331 | + | ||
| 332 | + def start_quorum( | ||
| 333 | + self, | ||
| 334 | + allow_heal: bool = True, | ||
| 335 | + shrink_only: bool = False, | ||
| 336 | + timeout: timedelta | None = None, | ||
| 337 | + ) -> None: | ||
| 338 | + if self._quorum_future is not None: | ||
| 339 | + self._quorum_future.result() | ||
| 340 | + | ||
| 341 | + if self._healing_snapshot_prepared: | ||
| 342 | + self._healing_snapshot_prepared = False | ||
| 343 | + else: | ||
| 344 | + staged = self._registered_training_state() | ||
| 345 | + if self._recovery_snapshot_enabled() and staged: | ||
| 346 | + self._staged_user_state_dict = self._recovery_state_stager.stage(staged) | ||
| 347 | + else: | ||
| 348 | + self._staged_user_state_dict = staged or None | ||
| 349 | + | ||
| 350 | + _barrier_initial_replica_ranks(self._quorum_id, self._group_world_size) | ||
| 351 | + | ||
| 352 | + super().start_quorum( | ||
| 353 | + allow_heal=allow_heal, | ||
| 354 | + shrink_only=shrink_only, | ||
| 355 | + timeout=timeout, | ||
| 356 | + ) | ||
| 357 | + | ||
| 358 | + def _registered_training_state(self) -> dict[str, object]: | ||
| 359 | + return _registered_training_state( | ||
| 360 | + self._user_state_dicts, | ||
| 361 | + self._state_dicts_on_training_thread, | ||
| 362 | + ) | ||
| 363 | + | ||
| 364 | + def _manager_state_dict(self) -> dict[str, object]: | ||
| 365 | + staged_state = ( | ||
| 366 | + self.published_recovery_snapshot() if self._recovery_snapshot_enabled() else self._staged_user_state_dict | ||
| 367 | + ) | ||
| 368 | + user_state_dict = dict(staged_state or {}) | ||
| 369 | + lazy_state_dicts = _lazy_state_dict_callbacks( | ||
| 370 | + self._user_state_dicts, | ||
| 371 | + self._state_dicts_on_training_thread, | ||
| 372 | + ) | ||
| 373 | + lazy_state_dicts = {key: callback for key, callback in lazy_state_dicts.items() if key not in user_state_dict} | ||
| 374 | + if lazy_state_dicts: | ||
| 375 | + with self._state_dict_lock.r_lock(): | ||
| 376 | + user_state_dict.update({key: callback() for key, callback in lazy_state_dicts.items()}) | ||
| 377 | + | ||
| 378 | + if not user_state_dict: | ||
| 379 | + raise RuntimeError("TorchFT recovery state is not initialized") | ||
| 380 | + leaves, _ = tree_flatten(user_state_dict) | ||
| 381 | + if any(isinstance(value, torch.Tensor) and value.device.type == "npu" for value in leaves): | ||
| 382 | + if not self._recovery_snapshot_enabled(): | ||
| 383 | + raise RuntimeError("TorchFT healing state was requested before deferred NPU state was materialized") | ||
| 384 | + | ||
| 385 | + # Materialize deferred NPU leaves only after TorchFT selects this | ||
| 386 | + # replica as a live-healing source. | ||
| 387 | + self._recovery_state_stager.stage(user_state_dict) | ||
| 388 | + staged_state = self.wait_for_recovery_snapshot() | ||
| 389 | + if staged_state is None: | ||
| 390 | + raise RuntimeError("TorchFT deferred healing state could not be materialized") | ||
| 391 | + user_state_dict = dict(staged_state) | ||
| 392 | + return {"user": user_state_dict, "torchft": self.state_dict()} | ||
| 393 | + | ||
| 394 | + | ||
| 395 | +class OptimizerWrapperEx(OptimizerWrapper): | ||
| 396 | + """TorchFT optimizer boundary with recovery-safe synchronous commit.""" | ||
| 397 | + | ||
| 398 | + manager: Manager | ||
| 399 | + optim: Optimizer | ||
| 400 | + | ||
| 401 | + def __init__(self, manager: ManagerEx, optim: Optimizer) -> None: | ||
| 402 | + super().__init__(manager, optim) | ||
| 403 | + | ||
| 404 | + @property | ||
| 405 | + def npu_manager(self) -> ManagerEx: | ||
| 406 | + return cast("ManagerEx", self.manager) | ||
| 407 | + | ||
| 408 | + def zero_grad(self, set_to_none: bool = True) -> None: | ||
| 409 | + manager = self.npu_manager | ||
| 410 | + process_group = self._process_group() | ||
| 411 | + is_first_quorum = manager.quorum_is_uninitialized | ||
| 412 | + needs_synchronous_recovery = bool( | ||
| 413 | + process_group is not None | ||
| 414 | + and process_group.rejoin_workaround_enabled | ||
| 415 | + and (process_group.recovery_quorum_required or is_first_quorum) | ||
| 416 | + ) | ||
| 417 | + if needs_synchronous_recovery: | ||
| 418 | + if process_group is not None and process_group.recovery_quorum_required: | ||
| 419 | + manager.prepare_healing_snapshot() | ||
| 420 | + manager.start_quorum() | ||
| 421 | + manager.wait_for_recovery_snapshot() | ||
| 422 | + manager.wait_quorum() | ||
| 423 | + manager.apply_pending_healing_state() | ||
| 424 | + if process_group is None: | ||
| 425 | + raise RuntimeError("Synchronous recovery requires an HCCL process group") | ||
| 426 | + process_group.mark_recovery_quorum_ready() | ||
| 427 | + else: | ||
| 428 | + manager.start_quorum() | ||
| 429 | + | ||
| 430 | + if process_group is not None: | ||
| 431 | + if process_group.rejoin_workaround_enabled and not needs_synchronous_recovery: | ||
| 432 | + manager.wait_for_recovery_snapshot() | ||
| 433 | + process_group.mark_step_in_flight() | ||
| 434 | + manager.disallow_state_dict_read() | ||
| 435 | + self.optim.zero_grad(set_to_none) | ||
| 436 | + | ||
| 437 | + def step_if_committed(self, closure: object | None = None) -> bool: | ||
| 438 | + if closure is not None: | ||
| 439 | + raise ValueError("optimizers that use closures are not supported") | ||
| 440 | + manager = self.npu_manager | ||
| 441 | + manager.wait_for_recovery_snapshot() | ||
| 442 | + manager.allow_state_dict_read() | ||
| 443 | + process_group = self._process_group() | ||
| 444 | + if process_group is not None and process_group.fatal_recovery_error: | ||
| 445 | + raise RuntimeError("The NPU device recovery failed") from process_group.fatal_recovery_error | ||
| 446 | + force_replay = bool( | ||
| 447 | + process_group is not None and process_group.rejoin_workaround_enabled and process_group.step_replay_required | ||
| 448 | + ) | ||
| 449 | + if force_replay: | ||
| 450 | + manager.report_error(RuntimeError("The current step used an aborted HCCL quorum")) | ||
| 451 | + should_commit = manager.should_commit() | ||
| 452 | + | ||
| 453 | + if process_group is not None and process_group.fatal_recovery_error: | ||
| 454 | + raise RuntimeError("The NPU device recovery failed") from process_group.fatal_recovery_error | ||
| 455 | + rejected_recovery_quorum = bool( | ||
| 456 | + not should_commit and process_group is not None and process_group.rejoin_workaround_enabled | ||
| 457 | + ) | ||
| 458 | + if force_replay or rejected_recovery_quorum: | ||
| 459 | + if process_group is None: | ||
| 460 | + raise RuntimeError("Rejected recovery quorum requires an HCCL process group") | ||
| 461 | + process_group.request_step_replay() | ||
| 462 | + raise _StepReplayError("TorchFT rejected the synchronous quorum; replay the step") | ||
| 463 | + if should_commit: | ||
| 464 | + if process_group is not None: | ||
| 465 | + process_group.commit_step(self.optim.step) | ||
| 466 | + else: | ||
| 467 | + self.optim.step() | ||
| 468 | + return True | ||
| 469 | + return False | ||
| 470 | + | ||
| 471 | + def step(self, closure: object | None = None) -> None: | ||
| 472 | + self.step_if_committed(closure) | ||
| 473 | + | ||
| 474 | + def _process_group(self) -> ProcessGroupHCCLEx | None: | ||
| 475 | + process_group = self.npu_manager.process_group | ||
| 476 | + return process_group if isinstance(process_group, ProcessGroupHCCLEx) else None | ||
| 477 | + | ||
| 478 | + | ||
| 479 | +install_torchft_npu_runtime_patches() | ||
| 480 | + | ||
| 481 | + | ||
| 482 | +__all__ = [ | ||
| 483 | + "ManagerEx", | ||
| 484 | + "OptimizerWrapperEx", | ||
| 485 | + "install_torchft_npu_runtime_patches", | ||
| 486 | +] | ||
| @@ -0,0 +1,62 @@ | |||
| 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 | +"""Cross-replica synchronization helpers for NPU TorchFT.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +import torch | ||
| 12 | +import torch.distributed as dist | ||
| 13 | +import torch.nn as nn | ||
| 14 | +from torch.distributed.distributed_c10d import ReduceOp | ||
| 15 | +from torch.distributed.tensor import DTensor | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def _all_reduce_with_recovery_completion( | ||
| 19 | + output: torch.Tensor, | ||
| 20 | + *, | ||
| 21 | + replicate_pg: dist.ProcessGroup, | ||
| 22 | +) -> None: | ||
| 23 | + # ProcessGroupHCCL launches on its communication stream. The synchronous | ||
| 24 | + # API establishes stream ordering for FSDP's post-reduce operations but | ||
| 25 | + # does not synchronize the whole device, so other backward work can overlap. | ||
| 26 | + dist.all_reduce(output, group=replicate_pg, op=ReduceOp.AVG) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _iter_moe_load_balance_states( | ||
| 30 | + model_parts: list[nn.Module], | ||
| 31 | +) -> list[tuple[torch.Tensor, torch.Tensor]]: | ||
| 32 | + """Return per-step counters and the persistent bias they update.""" | ||
| 33 | + states: list[tuple[torch.Tensor, torch.Tensor]] = [] | ||
| 34 | + seen_modules: set[int] = set() | ||
| 35 | + seen_counters: set[int] = set() | ||
| 36 | + for model_part in model_parts: | ||
| 37 | + for module in model_part.modules(): | ||
| 38 | + if id(module) in seen_modules: | ||
| 39 | + continue | ||
| 40 | + seen_modules.add(id(module)) | ||
| 41 | + if getattr(module, "load_balance_coeff", None) is None: | ||
| 42 | + continue | ||
| 43 | + counter = getattr(module, "tokens_per_expert_E", None) | ||
| 44 | + expert_bias = getattr(module, "expert_bias_E", None) | ||
| 45 | + if ( | ||
| 46 | + isinstance(counter, torch.Tensor) | ||
| 47 | + and isinstance(expert_bias, torch.Tensor) | ||
| 48 | + and id(counter) not in seen_counters | ||
| 49 | + ): | ||
| 50 | + seen_counters.add(id(counter)) | ||
| 51 | + states.append((counter, expert_bias)) | ||
| 52 | + return states | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def _iter_moe_load_balance_counts( | ||
| 56 | + model_parts: list[nn.Module], | ||
| 57 | +) -> list[torch.Tensor]: | ||
| 58 | + return [counter for counter, _bias in _iter_moe_load_balance_states(model_parts)] | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def _local_tensor(tensor: torch.Tensor) -> torch.Tensor: | ||
| 62 | + return tensor.to_local() if isinstance(tensor, DTensor) else tensor | ||
| @@ -0,0 +1,61 @@ | |||
| 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 Work wrapper that reports HCCL completion to its owner.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +from contextlib import contextmanager | ||
| 12 | +from typing import TYPE_CHECKING, Protocol, cast | ||
| 13 | + | ||
| 14 | +from torchft.process_group import ProcessGroupWrapper, _WorkAcceleratorTimeout | ||
| 15 | + | ||
| 16 | +if TYPE_CHECKING: | ||
| 17 | + from collections.abc import Generator | ||
| 18 | + from datetime import timedelta | ||
| 19 | + | ||
| 20 | + from torch.distributed import ProcessGroup as BaseProcessGroup | ||
| 21 | + from torch.distributed.distributed_c10d import Work | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class _WorkOwner(Protocol): | ||
| 25 | + def track_work(self, timeout: timedelta | None = None) -> tuple[int, int]: | ||
| 26 | + raise NotImplementedError | ||
| 27 | + | ||
| 28 | + def record_work_completion(self, token: int) -> None: | ||
| 29 | + pass | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +class TrackedHcclWork(_WorkAcceleratorTimeout): | ||
| 33 | + def __init__( | ||
| 34 | + self, | ||
| 35 | + owner: _WorkOwner, | ||
| 36 | + work: Work, | ||
| 37 | + timeout: timedelta, | ||
| 38 | + ) -> None: | ||
| 39 | + super().__init__(cast("ProcessGroupWrapper", owner), work, timeout) | ||
| 40 | + self._owner = owner | ||
| 41 | + self._work_token, _generation = owner.track_work(timeout) | ||
| 42 | + | ||
| 43 | + @classmethod | ||
| 44 | + @contextmanager | ||
| 45 | + def _stream_timeout( | ||
| 46 | + cls, | ||
| 47 | + pg: BaseProcessGroup, | ||
| 48 | + timeout: timedelta, | ||
| 49 | + ) -> Generator[None, None, None]: | ||
| 50 | + del timeout | ||
| 51 | + if not hasattr(pg, "track_work") or not hasattr(pg, "record_work_completion"): | ||
| 52 | + raise TypeError("Tracked HCCL work requires a work-tracking process group") | ||
| 53 | + # The generation-aware owner timer is retired after the completion | ||
| 54 | + # event is observed or at the trainer transaction boundary. | ||
| 55 | + yield | ||
| 56 | + | ||
| 57 | + def wait(self, timeout: timedelta | None = None) -> bool: | ||
| 58 | + completed = super().wait(timeout) | ||
| 59 | + if completed: | ||
| 60 | + self._owner.record_work_completion(self._work_token) | ||
| 61 | + return completed | ||
| @@ -0,0 +1,138 @@ | |||
| 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 | +"""Generation-aware lifecycle tracking for cross-replica HCCL Work.""" | ||
| 8 | + | ||
| 9 | +from __future__ import annotations | ||
| 10 | + | ||
| 11 | +import logging | ||
| 12 | +import threading | ||
| 13 | +import time | ||
| 14 | +from typing import TYPE_CHECKING, Protocol | ||
| 15 | + | ||
| 16 | +if TYPE_CHECKING: | ||
| 17 | + from collections.abc import Callable | ||
| 18 | + from datetime import timedelta | ||
| 19 | + | ||
| 20 | +logger = logging.getLogger(__name__) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class _CompletionEvent(Protocol): | ||
| 24 | + def query(self) -> bool: | ||
| 25 | + raise NotImplementedError | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class HcclWorkTracker: | ||
| 29 | + def __init__( | ||
| 30 | + self, | ||
| 31 | + schedule_timeout_abort: Callable[[int], None], | ||
| 32 | + active_work_grace_ms: Callable[[], int], | ||
| 33 | + ) -> None: | ||
| 34 | + self.boundary_lock = threading.RLock() | ||
| 35 | + self._lock = threading.Lock() | ||
| 36 | + self._active: set[int] = set() | ||
| 37 | + self._stuck: set[int] = set() | ||
| 38 | + self._timers: dict[int, threading.Timer] = {} | ||
| 39 | + self._completion_events: dict[int, _CompletionEvent] = {} | ||
| 40 | + self._next_token = 0 | ||
| 41 | + self._generation = 0 | ||
| 42 | + self._schedule_timeout_abort = schedule_timeout_abort | ||
| 43 | + self._active_work_grace_ms = active_work_grace_ms | ||
| 44 | + | ||
| 45 | + @property | ||
| 46 | + def generation(self) -> int: | ||
| 47 | + with self._lock: | ||
| 48 | + return self._generation | ||
| 49 | + | ||
| 50 | + def track(self, timeout: timedelta | None = None) -> tuple[int, int]: | ||
| 51 | + with self._lock: | ||
| 52 | + token = self._next_token | ||
| 53 | + self._next_token += 1 | ||
| 54 | + self._active.add(token) | ||
| 55 | + generation = self._generation | ||
| 56 | + if timeout is not None: | ||
| 57 | + timer = threading.Timer( | ||
| 58 | + timeout.total_seconds(), | ||
| 59 | + self._mark_stuck, | ||
| 60 | + args=(token, generation), | ||
| 61 | + ) | ||
| 62 | + timer.daemon = True | ||
| 63 | + self._timers[token] = timer | ||
| 64 | + timer.start() | ||
| 65 | + return token, generation | ||
| 66 | + | ||
| 67 | + def record_completion(self, token: int) -> None: | ||
| 68 | + import torch_npu | ||
| 69 | + | ||
| 70 | + event = torch_npu.npu.Event() | ||
| 71 | + torch_npu.npu.current_stream().record_event(event) | ||
| 72 | + with self._lock: | ||
| 73 | + if token in self._active: | ||
| 74 | + self._completion_events[token] = event | ||
| 75 | + | ||
| 76 | + def num_active(self) -> int: | ||
| 77 | + self.retire_completed() | ||
| 78 | + with self._lock: | ||
| 79 | + return len(self._active) | ||
| 80 | + | ||
| 81 | + def complete(self, token: int) -> None: | ||
| 82 | + with self._lock: | ||
| 83 | + self._active.discard(token) | ||
| 84 | + self._stuck.discard(token) | ||
| 85 | + timer = self._timers.pop(token, None) | ||
| 86 | + self._completion_events.pop(token, None) | ||
| 87 | + if timer is not None: | ||
| 88 | + timer.cancel() | ||
| 89 | + | ||
| 90 | + def retire_completed(self) -> None: | ||
| 91 | + with self._lock: | ||
| 92 | + completion_events = tuple(self._completion_events.items()) | ||
| 93 | + for token, event in completion_events: | ||
| 94 | + try: | ||
| 95 | + completed = event.query() | ||
| 96 | + except RuntimeError: | ||
| 97 | + logger.debug("Could not query HCCL completion event", exc_info=True) | ||
| 98 | + continue | ||
| 99 | + if completed: | ||
| 100 | + self.complete(token) | ||
| 101 | + | ||
| 102 | + def clear(self) -> None: | ||
| 103 | + with self.boundary_lock, self._lock: | ||
| 104 | + timers = tuple(self._timers.values()) | ||
| 105 | + self._timers.clear() | ||
| 106 | + self._completion_events.clear() | ||
| 107 | + self._active.clear() | ||
| 108 | + self._stuck.clear() | ||
| 109 | + self._generation += 1 | ||
| 110 | + for timer in timers: | ||
| 111 | + timer.cancel() | ||
| 112 | + | ||
| 113 | + def has_active_after_grace(self) -> bool: | ||
| 114 | + deadline = time.monotonic() + self._active_work_grace_ms() / 1000 | ||
| 115 | + while True: | ||
| 116 | + self.retire_completed() | ||
| 117 | + with self._lock: | ||
| 118 | + if not self._active: | ||
| 119 | + return False | ||
| 120 | + if self._stuck: | ||
| 121 | + return True | ||
| 122 | + if time.monotonic() >= deadline: | ||
| 123 | + return True | ||
| 124 | + time.sleep(0.01) | ||
| 125 | + | ||
| 126 | + def is_stale(self, expected_generation: int | None) -> bool: | ||
| 127 | + if expected_generation is None: | ||
| 128 | + return False | ||
| 129 | + with self._lock: | ||
| 130 | + return expected_generation != self._generation | ||
| 131 | + | ||
| 132 | + def _mark_stuck(self, token: int, generation: int) -> None: | ||
| 133 | + self.retire_completed() | ||
| 134 | + with self._lock: | ||
| 135 | + if generation != self._generation or token not in self._active: | ||
| 136 | + return | ||
| 137 | + self._stuck.add(token) | ||
| 138 | + self._schedule_timeout_abort(generation) | ||


This code comment section is from+28To+31
这部分是为什么?