Closed
test: 增加 TorchFT NPU 定向 UT 与门禁 #679
zhangyifan999Add on Sep 1Closed at Oct 12
test: 增加 TorchFT NPU 定向 UT 与门禁 #679
Closed
Total: 9 files changed+1886-3
| @@ -17,6 +17,7 @@ echo "[CANN] LD_LIBRARY_PATH=${LD_LIBRARY_PATH:-<unset>}" | |||
| 17 | 17 | ||
| 18 | PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" | 18 | PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" |
| 19 | cd "${PROJECT_ROOT}" | 19 | cd "${PROJECT_ROOT}" |
| 20 | +export TORCH_DEVICE_BACKEND_AUTOLOAD=0 | ||
| 20 | 21 | ||
| 21 | PYTHON_BIN="${PYTHON_BIN:-python3.12}" | 22 | PYTHON_BIN="${PYTHON_BIN:-python3.12}" |
| 22 | TORCHTITAN_REPO="${TORCHTITAN_REPO:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" | 23 | TORCHTITAN_REPO="${TORCHTITAN_REPO:-https://gitcode.com/GitHub_Trending/to/torchtitan.git}" |
| @@ -51,6 +52,7 @@ git -C "${TORCHTITAN_DIR}" fetch --depth 1 origin "${TORCHTITAN_COMMIT}" | |||
| 51 | git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" | 52 | git -C "${TORCHTITAN_DIR}" checkout --detach --quiet "${TORCHTITAN_COMMIT}" |
| 52 | 53 | ||
| 53 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}" | 54 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}" |
| 55 | +"${PYTHON_BIN}" -m pip install --break-system-packages --no-cache-dir "torchft-nightly==2026.7.17" | ||
| 54 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}" | 56 | "${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}" |
| 55 | "${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu' | 57 | "${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu' |
| 56 | 58 | ||
| @@ -65,8 +67,16 @@ SMOKE_TESTS_START="$(date +%s)" | |||
| 65 | SMOKE_TESTS_END="$(date +%s)" | 67 | SMOKE_TESTS_END="$(date +%s)" |
| 66 | 68 | ||
| 67 | INTEGRATION_TESTS_START="$(date +%s)" | 69 | INTEGRATION_TESTS_START="$(date +%s)" |
| 70 | +# TorchFT uses a custom integration runner because one case coordinates a | ||
| 71 | +# Lighthouse plus two independent torchrun process trees. | ||
| 68 | "${PYTHON_BIN}" -m tests.integration_tests.run_tests \ | 72 | "${PYTHON_BIN}" -m tests.integration_tests.run_tests \ |
| 69 | - "${OUTPUT_DIR}" \ | 73 | + "${OUTPUT_DIR}/torchft" \ |
| 74 | + --test_suite torchft \ | ||
| 75 | + --module "${MODULE}" \ | ||
| 76 | + --ngpu "${NGPU}" | ||
| 77 | + | ||
| 78 | +"${PYTHON_BIN}" -m tests.integration_tests.run_tests \ | ||
| 79 | + "${OUTPUT_DIR}/models" \ | ||
| 70 | --test_suite models \ | 80 | --test_suite models \ |
| 71 | --module "${MODULE}" \ | 81 | --module "${MODULE}" \ |
| 72 | --config "${CONFIG}" \ | 82 | --config "${CONFIG}" \ |
| @@ -44,6 +44,10 @@ export TORCH_DEVICE_BACKEND_AUTOLOAD=0 | |||
| 44 | cd "${PROJECT_ROOT}" | 44 | cd "${PROJECT_ROOT}" |
| 45 | export PYTHONPATH="${PROJECT_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" | 45 | export PYTHONPATH="${PROJECT_ROOT}${PYTHONPATH:+:${PYTHONPATH}}" |
| 46 | pip install -r requirements-dev.txt | 46 | pip install -r requirements-dev.txt |
| 47 | +# This wheel is built from the TorchFT commit pinned by the ``torchft`` | ||
| 48 | +# optional dependency in pyproject.toml. Using the wheel keeps the CPU UT job | ||
| 49 | +# independent of the Rust/maturin toolchain required for a source build. | ||
| 50 | +pip install "torchft-nightly==2026.7.17" | ||
| 47 | 51 | ||
| 48 | if [[ ! -d "${TORCHTITAN_DIR}/.git" ]]; then | 52 | if [[ ! -d "${TORCHTITAN_DIR}/.git" ]]; then |
| 49 | mkdir -p "$(dirname "${TORCHTITAN_DIR}")" | 53 | mkdir -p "$(dirname "${TORCHTITAN_DIR}")" |
| @@ -20,6 +20,8 @@ torchtitan 迁移而来。 | |||
| 20 | | `dsv3_2_dsa_ep2_fsdp2` | DeepSeek-V3.2 | DSA + EP2/FSDP2 | 2 | - | 是 | - | | 20 | | `dsv3_2_dsa_ep2_fsdp2` | DeepSeek-V3.2 | DSA + EP2/FSDP2 | 2 | - | 是 | - | |
| 21 | | `dsv3_2_dsa_cp2` | DeepSeek-V3.2 | DSA + CP2 | 2 | - | 否 | ST 仅验证训练触发;CPU metadata oracle 单独覆盖,暂未生成 CP2 golden loss | | 21 | | `dsv3_2_dsa_cp2` | DeepSeek-V3.2 | DSA + CP2 | 2 | - | 否 | ST 仅验证训练触发;CPU metadata oracle 单独覆盖,暂未生成 CP2 golden loss | |
| 22 | | `dsv4_ema_ep2_fsdp2` | DeepSeek-V4 | Golden + EP2/FSDP2 + EMA CPU offload | 2 | - | 否 | 校验完整 DCP metadata 包含 `ema_optimizer.*` | | 22 | | `dsv4_ema_ep2_fsdp2` | DeepSeek-V4 | Golden + EP2/FSDP2 + EMA CPU offload | 2 | - | 否 | 校验完整 DCP metadata 包含 `ema_optimizer.*` | |
| 23 | +| `torchft_training` | DeepSeek-V4 | TorchFT 2 replicas x 2 ranks | 4 | - | 否 | 验证真实多 replica 训练流程 | | ||
| 24 | +| `torchft_rejoin` | DeepSeek-V4 | TorchFT 2 replicas x 2 ranks | 4 | - | 否 | 验证故障退出、replacement、replay 与 peer healing | | ||
| 23 | 25 | ||
| 24 | `use_golden` 与 `check_loss` 是两个独立维度:`use_golden` 仅决定使用 Golden 参考算子 | 26 | `use_golden` 与 `check_loss` 是两个独立维度:`use_golden` 仅决定使用 Golden 参考算子 |
| 25 | 还是 SMLA/NPU override;`check_loss` 决定是否启用 deterministic、读取参考 loss 并执行 | 27 | 还是 SMLA/NPU override;`check_loss` 决定是否启用 deterministic、读取参考 loss 并执行 |
| @@ -103,3 +105,63 @@ runner 迁移自 torchtitan 的 GPUPool 机制:默认将用例并发打包到 | |||
| 103 | 105 | ||
| 104 | 调度器本身不设独立单元测试:其正确性(设备不重叠、失败/超时释放、并发打包、 | 106 | 调度器本身不设独立单元测试:其正确性(设备不重叠、失败/超时释放、并发打包、 |
| 105 | golden loss 等价)由集成测试自身的 canary 运行直接验证。 | 107 | golden loss 等价)由集成测试自身的 canary 运行直接验证。 |
| 108 | + | ||
| 109 | +### 自定义 runner 扩展点 | ||
| 110 | + | ||
| 111 | +默认的 integration runner 适用于单个训练任务:它为每个 case 调用一次 | ||
| 112 | +`scripts/run_train.sh`,然后按配置执行 loss 检查。TorchFT 场景还需要启动 | ||
| 113 | +Lighthouse、两个独立 replica,并在 rejoin 用例中终止和重新拉起指定 replica, | ||
| 114 | +因此不能使用这条单进程编排路径。 | ||
| 115 | + | ||
| 116 | +`OverrideDefinitions.runner` 为这类 case 提供可选的自定义执行入口,其类型由 | ||
| 117 | +`IntegrationTestRunner` Protocol 描述。`run_single_test()` 只在 case 显式配置 | ||
| 118 | +`runner` 时调用该回调;没有配置的既有 case 继续使用原来的 | ||
| 119 | +`scripts/run_train.sh`、golden loss 和 TensorBoard 检查流程。 | ||
| 120 | + | ||
| 121 | +TorchFT 的调用关系如下: | ||
| 122 | + | ||
| 123 | +```text | ||
| 124 | +run_tests.py | ||
| 125 | + -> build_torchft_test_list() | ||
| 126 | + -> run_single_test() | ||
| 127 | + -> OverrideDefinitions.runner | ||
| 128 | + -> run_torchft_case() | ||
| 129 | + -> _TorchFTScenarioRunner | ||
| 130 | + -> start Lighthouse | ||
| 131 | + -> start replica 0 and replica 1 | ||
| 132 | + -> optionally kill and relaunch replica 1 | ||
| 133 | + -> validate logs and clean up processes | ||
| 134 | +``` | ||
| 135 | + | ||
| 136 | +`IntegrationTestRunner` 只是通用回调接口;具体的 TorchFT 进程、端口、日志、超时和 | ||
| 137 | +清理逻辑均封装在 `torchft.py` 的 `_TorchFTScenarioRunner` 中。 | ||
| 138 | + | ||
| 139 | +### TorchFT 单机 ST | ||
| 140 | + | ||
| 141 | +TorchFT 通过 integration runner 在 4 张 NPU 上验证两个真实多进程场景: | ||
| 142 | + | ||
| 143 | +```bash | ||
| 144 | +# 顺序执行 2 replicas x 2 ranks 正常训练和故障恢复 | ||
| 145 | +python -m tests.integration_tests.run_tests \ | ||
| 146 | + test_reports/torchft \ | ||
| 147 | + --test_suite torchft \ | ||
| 148 | + --ngpu 4 | ||
| 149 | + | ||
| 150 | +# 也可以单独执行 | ||
| 151 | +python -m tests.integration_tests.run_tests \ | ||
| 152 | + test_reports/torchft_training \ | ||
| 153 | + --test_suite torchft \ | ||
| 154 | + --test_name torchft_training \ | ||
| 155 | + --ngpu 4 | ||
| 156 | +python -m tests.integration_tests.run_tests \ | ||
| 157 | + test_reports/torchft_rejoin \ | ||
| 158 | + --test_suite torchft \ | ||
| 159 | + --test_name torchft_rejoin \ | ||
| 160 | + --ngpu 4 | ||
| 161 | +``` | ||
| 162 | + | ||
| 163 | +`training` 要求两个 replica 都完成训练。`rejoin` 在 step 2 后终止 replica 1 | ||
| 164 | +的完整进程树,再以同一 replica ID 拉起 replacement;用例要求 survivor 完成 | ||
| 165 | +HCCL stop/restart 和失败 step replay,replacement 完成 peer healing,最终双方均 | ||
| 166 | +打印 `Training completed`。环境可通过 `NPU_DEVICES`、输出目录参数、端口基址和 | ||
| 167 | +`ST_TIMEOUT_SECONDS` 覆盖,默认只保留日志并清理 dump/checkpoint。 | ||
| @@ -6,14 +6,34 @@ | |||
| 6 | # This source code is licensed under the BSD-style license found in the | 6 | # This source code is licensed under the BSD-style license found in the |
| 7 | # LICENSE file in the root directory of this source tree. | 7 | # LICENSE file in the root directory of this source tree. |
| 8 | 8 | ||
| 9 | -from collections.abc import Mapping, Sequence | 9 | +from __future__ import annotations |
| 10 | -from dataclasses import dataclass | 10 | + |
| 11 | +from dataclasses import dataclass, field | ||
| 12 | +from typing import TYPE_CHECKING, Protocol | ||
| 13 | + | ||
| 14 | +if TYPE_CHECKING: | ||
| 15 | + from collections.abc import Mapping, Sequence | ||
| 16 | + from pathlib import Path | ||
| 11 | 17 | ||
| 12 | __all__ = [ | 18 | __all__ = [ |
| 19 | + "IntegrationTestRunner", | ||
| 13 | "OverrideDefinitions", | 20 | "OverrideDefinitions", |
| 14 | ] | 21 | ] |
| 15 | 22 | ||
| 16 | 23 | ||
| 24 | +class IntegrationTestRunner(Protocol): | ||
| 25 | + """Run an integration case that needs custom process orchestration.""" | ||
| 26 | + | ||
| 27 | + def __call__( | ||
| 28 | + self, | ||
| 29 | + test_case: OverrideDefinitions, | ||
| 30 | + case_dir: Path, | ||
| 31 | + module: str | None, | ||
| 32 | + config: str | None, | ||
| 33 | + ) -> None: | ||
| 34 | + pass | ||
| 35 | + | ||
| 36 | + | ||
| 17 | @dataclass | 37 | @dataclass |
| 18 | class OverrideDefinitions: | 38 | class OverrideDefinitions: |
| 19 | """ | 39 | """ |
| @@ -33,6 +53,7 @@ class OverrideDefinitions: | |||
| 33 | expected_steps: Sequence[Sequence[int]] | None = None | 53 | expected_steps: Sequence[Sequence[int]] | None = None |
| 34 | check_resume: bool = False | 54 | check_resume: bool = False |
| 35 | verify_ema_checkpoint: bool = False | 55 | verify_ema_checkpoint: bool = False |
| 56 | + runner: IntegrationTestRunner | None = field(default=None, repr=False, compare=False) | ||
| 36 | 57 | ||
| 37 | def __repr__(self): | 58 | def __repr__(self): |
| 38 | return self.test_descr | 59 | return self.test_descr |
| @@ -36,6 +36,7 @@ from tests.integration_tests.loss_compare import ( | |||
| 36 | log_print, | 36 | log_print, |
| 37 | read_losses_from_file, | 37 | read_losses_from_file, |
| 38 | ) | 38 | ) |
| 39 | +from tests.integration_tests.torchft import build_torchft_test_list | ||
| 39 | 40 | ||
| 40 | 41 | ||
| 41 | def build_models_test_list() -> list[OverrideDefinitions]: | 42 | def build_models_test_list() -> list[OverrideDefinitions]: |
| @@ -56,6 +57,7 @@ _TEST_SUITES_FUNCTION = { | |||
| 56 | "deepseek_v4": build_deepseek_v4_test_list, | 57 | "deepseek_v4": build_deepseek_v4_test_list, |
| 57 | "deepseek_v4_checkpoint": build_deepseek_v4_checkpoint_resume_test_list, | 58 | "deepseek_v4_checkpoint": build_deepseek_v4_checkpoint_resume_test_list, |
| 58 | "ema": build_ema_test_list, | 59 | "ema": build_ema_test_list, |
| 60 | + "torchft": build_torchft_test_list, | ||
| 59 | } | 61 | } |
| 60 | 62 | ||
| 61 | # Held while a test writes its captured output so concurrent tests do not | 63 | # Held while a test writes its captured output so concurrent tests do not |
| @@ -397,6 +399,10 @@ def run_single_test( | |||
| 397 | 399 | ||
| 398 | test_name = test_flavor.test_name | 400 | test_name = test_flavor.test_name |
| 399 | case_dir = Path(output_dir) / test_name | 401 | case_dir = Path(output_dir) / test_name |
| 402 | + if test_flavor.runner is not None: | ||
| 403 | + test_flavor.runner(test_flavor, case_dir, module, config) | ||
| 404 | + return | ||
| 405 | + | ||
| 400 | all_ranks = ",".join(map(str, range(test_flavor.ngpu))) | 406 | all_ranks = ",".join(map(str, range(test_flavor.ngpu))) |
| 401 | 407 | ||
| 402 | if test_flavor.expected_steps is not None and len(test_flavor.expected_steps) != len( | 408 | if test_flavor.expected_steps is not None and len(test_flavor.expected_steps) != len( |
| @@ -0,0 +1,526 @@ | |||
| 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 | +"""Single-node TorchFT integration scenarios.""" | ||
| 7 | + | ||
| 8 | +from __future__ import annotations | ||
| 9 | + | ||
| 10 | +import os | ||
| 11 | +import shutil | ||
| 12 | +import signal | ||
| 13 | +import subprocess | ||
| 14 | +import sys | ||
| 15 | +import time | ||
| 16 | +from contextlib import suppress | ||
| 17 | +from dataclasses import dataclass | ||
| 18 | +from pathlib import Path | ||
| 19 | +from typing import TYPE_CHECKING | ||
| 20 | + | ||
| 21 | +from tests.integration_tests import OverrideDefinitions | ||
| 22 | + | ||
| 23 | +if TYPE_CHECKING: | ||
| 24 | + from typing import BinaryIO | ||
| 25 | + | ||
| 26 | +_PROJECT_ROOT = Path(__file__).parents[2] | ||
| 27 | +_FATAL_LOG_PATTERNS = ( | ||
| 28 | + "Watchdog caught collective operation timeout", | ||
| 29 | + "Traceback (most recent call last)", | ||
| 30 | +) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _env_int(name: str, default: int) -> int: | ||
| 34 | + return int(os.environ.get(name, default)) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def _env_path(name: str, default: str) -> Path: | ||
| 38 | + path = Path(os.environ.get(name, default)) | ||
| 39 | + return path if path.is_absolute() else _PROJECT_ROOT / path | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +@dataclass(frozen=True) | ||
| 43 | +class _Settings: | ||
| 44 | + python: str | ||
| 45 | + lighthouse: str | ||
| 46 | + module: str | ||
| 47 | + config: str | ||
| 48 | + hf_assets_path: Path | ||
| 49 | + dataset_path: Path | ||
| 50 | + overrides: str | ||
| 51 | + devices: tuple[str, str, str, str] | ||
| 52 | + lighthouse_port_base: int | ||
| 53 | + rendezvous_port_base: int | ||
| 54 | + hccl_port_base: int | ||
| 55 | + process_group_timeout_ms: int | ||
| 56 | + training_steps: int | ||
| 57 | + rejoin_steps: int | ||
| 58 | + timeout_seconds: int | ||
| 59 | + keep_artifacts: bool | ||
| 60 | + | ||
| 61 | + @classmethod | ||
| 62 | + def from_environment(cls, module: str | None) -> _Settings: | ||
| 63 | + lighthouse = shutil.which("torchft_lighthouse") | ||
| 64 | + if lighthouse is None: | ||
| 65 | + raise RuntimeError("torchft_lighthouse is required; install the project's torchft optional dependency") | ||
| 66 | + | ||
| 67 | + parsed_devices = tuple(device.strip() for device in os.environ.get("NPU_DEVICES", "0,1,2,3").split(",")) | ||
| 68 | + if len(parsed_devices) != 4 or any(not device for device in parsed_devices): | ||
| 69 | + raise ValueError("NPU_DEVICES must contain exactly four comma-separated device IDs") | ||
| 70 | + devices = (parsed_devices[0], parsed_devices[1], parsed_devices[2], parsed_devices[3]) | ||
| 71 | + | ||
| 72 | + default_overrides = ",".join( | ||
| 73 | + ( | ||
| 74 | + "torchtitan_npu.override.common.rope.workaround", | ||
| 75 | + "torchtitan_npu.override.deepseek_v4.sparse_attn.golden", | ||
| 76 | + ) | ||
| 77 | + ) | ||
| 78 | + return cls( | ||
| 79 | + python=os.environ.get("PYTHON_BIN", sys.executable), | ||
| 80 | + lighthouse=lighthouse, | ||
| 81 | + module=module or "torchtitan_npu.models.deepseek_v4", | ||
| 82 | + config=os.environ.get("TORCHFT_CONFIG", "deepseek_v4_torchft_debugmodel"), | ||
| 83 | + hf_assets_path=_env_path("HF_ASSETS_PATH", "tests/assets/deepseek_v3"), | ||
| 84 | + dataset_path=_env_path("DATASET_PATH", "tests/assets/c4_test"), | ||
| 85 | + overrides=os.environ.get("OVERRIDES", default_overrides), | ||
| 86 | + devices=devices, | ||
| 87 | + lighthouse_port_base=_env_int("LIGHTHOUSE_PORT_BASE", 33800), | ||
| 88 | + rendezvous_port_base=_env_int("RDZV_PORT_BASE", 33900), | ||
| 89 | + hccl_port_base=_env_int("HCCL_PORT_BASE", 61000), | ||
| 90 | + process_group_timeout_ms=_env_int("PROCESS_GROUP_TIMEOUT_MS", 5000), | ||
| 91 | + training_steps=_env_int("TRAINING_STEPS", 3), | ||
| 92 | + rejoin_steps=_env_int("REJOIN_STEPS", 8), | ||
| 93 | + timeout_seconds=_env_int("ST_TIMEOUT_SECONDS", 900), | ||
| 94 | + keep_artifacts=os.environ.get("KEEP_ST_ARTIFACTS", "0") == "1", | ||
| 95 | + ) | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +@dataclass | ||
| 99 | +class _ManagedProcess: | ||
| 100 | + name: str | ||
| @@ -0,0 +1,82 @@ | |||
| 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 | +from datetime import timedelta | ||
| 7 | +from importlib import import_module | ||
| 8 | +from types import SimpleNamespace | ||
| 9 | +from typing import Any | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | +from torchft.process_group import ProcessGroupWrapper | ||
| 13 | + | ||
| 14 | +from torchtitan_npu.patches import torchft as torchft_patches | ||
| 15 | + | ||
| 16 | +torchft_patches.apply() | ||
| 17 | + | ||
| 18 | +manager_module = import_module("torchtitan_npu.extensions.torchft.manager") | ||
| 19 | +process_group_module = import_module("torchtitan_npu.interface.torchft.process_group") | ||
| 20 | +ProcessGroupHCCLEx = process_group_module.ProcessGroupHCCLEx | ||
| 21 | +_hccl_group_id = vars(process_group_module)["_hccl_group_id"] | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def _config( | ||
| 25 | + *, | ||
| 26 | + process_group: str = "hccl", | ||
| 27 | + group_size: int = 2, | ||
| 28 | + replica_id: int = 0, | ||
| 29 | + min_replica_size: int = 2, | ||
| 30 | + semi_sync_method: str | None = None, | ||
| 31 | +): | ||
| 32 | + return SimpleNamespace( | ||
| 33 | + process_group=process_group, | ||
| 34 | + group_size=group_size, | ||
| 35 | + replica_id=replica_id, | ||
| 36 | + min_replica_size=min_replica_size, | ||
| 37 | + semi_sync_method=semi_sync_method, | ||
| 38 | + hccl_rejoin_max_step_replays=3, | ||
| 39 | + ) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def test_registered_hccl_process_group_contract(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| 43 | + assert _hccl_group_id(12, 0, 2) == "torchft_quorum_12_rank_0" | ||
| 44 | + assert _hccl_group_id(12, 3, 2) == "torchft_quorum_12_rank_1" | ||
| 45 | + assert _hccl_group_id(12, None, None) == "torchft_quorum_12" | ||
| 46 | + timeout = timedelta(seconds=17) | ||
| 47 | + received_timeout = None | ||
| 48 | + | ||
| 49 | + def capture_timeout(_self: ProcessGroupWrapper, *, timeout: timedelta) -> None: | ||
| 50 | + nonlocal received_timeout | ||
| 51 | + received_timeout = timeout | ||
| 52 | + | ||
| 53 | + monkeypatch.setattr(ProcessGroupWrapper, "__init__", capture_timeout) | ||
| 54 | + | ||
| 55 | + process_group = manager_module.create_process_group("hccl", timeout) | ||
| 56 | + | ||
| 57 | + assert isinstance(process_group, ProcessGroupHCCLEx) | ||
| 58 | + assert received_timeout == timeout | ||
| 59 | + assert process_group.get_backend_name() == "torchft-hccl" | ||
| 60 | + assert process_group.getBackendName() == "torchft-hccl" | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +@pytest.mark.parametrize( | ||
| 64 | + ("overrides", "message"), | ||
| 65 | + [ | ||
| 66 | + ({}, None), | ||
| 67 | + ({"process_group": "gloo"}, "process_group='hccl'"), | ||
| 68 | + ({"process_group": "nccl"}, "process_group='hccl'"), | ||
| 69 | + ({"process_group": "mccl"}, "process_group='hccl'"), | ||
| 70 | + ({"semi_sync_method": "local_sgd"}, "synchronous quorum only"), | ||
| 71 | + ({"semi_sync_method": "diloco"}, "synchronous quorum only"), | ||
| 72 | + ({"group_size": 2, "min_replica_size": 3}, "min_replica_size"), | ||
| 73 | + ({"group_size": 2, "replica_id": -1}, "replica_id"), | ||
| 74 | + ({"group_size": 2, "replica_id": 2}, "replica_id"), | ||
| 75 | + ], | ||
| 76 | +) | ||
| 77 | +def test_npu_process_group_config_contract(overrides: dict[str, Any], message: str | None) -> None: | ||
| 78 | + if message is None: | ||
| 79 | + manager_module.validate_npu_process_group_config(_config(**overrides)) | ||
| 80 | + return | ||
| 81 | + with pytest.raises(ValueError, match=message): | ||
| 82 | + manager_module.validate_npu_process_group_config(_config(**overrides)) | ||
| @@ -0,0 +1,673 @@ | |||
| 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 | +import threading | ||
| 8 | +from datetime import timedelta | ||
| 9 | +from types import SimpleNamespace | ||
| 10 | +from unittest import TestCase | ||
| 11 | +from unittest.mock import MagicMock, call, patch | ||
| 12 | + | ||
| 13 | +import torch | ||
| 14 | +import torch.nn as nn | ||
| 15 | +from torchft.process_group import _WorkAcceleratorTimeout | ||
| 16 | +from torchtitan.components.optimizer import OptimizersContainer | ||
| 17 | +from torchtitan.experiments.torchft.trainer import ( | ||
| 18 | + FaultTolerantTrainer as UpstreamFaultTolerantTrainer, | ||
| 19 | +) | ||
| 20 | + | ||
| 21 | +from torchtitan_npu.patches import torchft as torchft_patches | ||
| 22 | + | ||
| 23 | +torchft_patches.apply() | ||
| 24 | + | ||
| 25 | +from torchtitan_npu.extensions.torchft import ( | ||
| 26 | + FaultTolerantTrainerEx, | ||
| 27 | + TorchFTOptimizersContainerEx, | ||
| 28 | +) | ||
| 29 | +from torchtitan_npu.interface.torchft import process_group as process_group_module | ||
| 30 | +from torchtitan_npu.interface.torchft.process_group import ( | ||
| 31 | + ProcessGroupHCCLEx, | ||
| 32 | + _StepReplayError, | ||
| 33 | + _TrackedHcclWork, | ||
| 34 | +) | ||
| 35 | +from torchtitan_npu.interface.torchft.replay import _ReplayableStepIterator | ||
| 36 | +from torchtitan_npu.interface.torchft.runtime import ( | ||
| 37 | + ManagerEx, | ||
| 38 | + OptimizerWrapperEx, | ||
| 39 | + _RecoveryStateStager, | ||
| 40 | + _to_cpu, | ||
| 41 | +) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def _configured_rejoin_process_group( | ||
| 45 | + timeout: timedelta = timedelta(seconds=1), | ||
| 46 | +) -> ProcessGroupHCCLEx: | ||
| 47 | + process_group = ProcessGroupHCCLEx(timeout) | ||
| 48 | + process_group.configure_rejoin_workaround( | ||
| 49 | + active_work_grace_ms=0, | ||
| 50 | + device_restart_wait_timeout_ms=1000, | ||
| 51 | + watchdog_timeout_margin_ms=1000, | ||
| 52 | + ) | ||
| 53 | + process_group.arm_rejoin_workaround() | ||
| 54 | + return process_group | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def _tracked_work_fixture() -> SimpleNamespace: | ||
| 58 | + process_group = _configured_rejoin_process_group() | ||
| 59 | + timer = MagicMock() | ||
| 60 | + with patch( | ||
| 61 | + "torchtitan_npu.interface.torchft.work_tracker.threading.Timer", | ||
| 62 | + return_value=timer, | ||
| 63 | + ) as timer_factory: | ||
| 64 | + tracked = _TrackedHcclWork( | ||
| 65 | + process_group, | ||
| 66 | + MagicMock(), | ||
| 67 | + timedelta(seconds=1), | ||
| 68 | + ) | ||
| 69 | + return SimpleNamespace( | ||
| 70 | + process_group=process_group, | ||
| 71 | + timer=timer, | ||
| 72 | + timer_factory=timer_factory, | ||
| 73 | + tracked=tracked, | ||
| 74 | + ) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def _run_abort_path(has_active_work: bool) -> SimpleNamespace: | ||
| 78 | + process_group = _configured_rejoin_process_group() | ||
| 79 | + recovery_order: list[str] = [] | ||
| 80 | + torchft_pg = MagicMock() | ||
| 81 | + process_group._pg = torchft_pg | ||
| 82 | + backend = MagicMock() | ||
| 83 | + backend.abort_hccl_comm.side_effect = lambda *_args: recovery_order.append("abort") | ||
| 84 | + process_group._pg._get_backend.return_value = backend | ||
| 85 | + process_group._device_index = 0 | ||
| 86 | + if has_active_work: | ||
| 87 | + process_group.mark_step_in_flight() | ||
| 88 | + | ||
| 89 | + with ( | ||
| 90 | + patch.object(process_group, "_has_active_work_after_grace", return_value=has_active_work), | ||
| 91 | + patch.object(process_group._force_stop_observed, "wait", return_value=True), | ||
| 92 | + patch("torch_npu.npu.stop_device", side_effect=lambda _device: recovery_order.append("stop") or 0) as stop, | ||
| 93 | + patch( | ||
| 94 | + "torch_npu.npu.restart_device", side_effect=lambda *_args, **_kwargs: recovery_order.append("restart") | ||
| 95 | + ) as restart, | ||
| 96 | + patch( | ||
| 97 | + "torchtitan_npu.interface.torchft.process_group._reinitialize_local_hccl_groups", | ||
| 98 | + side_effect=lambda _group: recovery_order.append("reinit"), | ||
| 99 | + ) as reinitialize, | ||
| 100 | + patch( | ||
| @@ -0,0 +1,499 @@ | |||
| 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 | +from types import SimpleNamespace | ||
| 8 | +from unittest.mock import MagicMock, call, patch | ||
| 9 | + | ||
| 10 | +import torch | ||
| 11 | +import torch.nn as nn | ||
| 12 | +from torchtitan.components.checkpoint import CheckpointManager | ||
| 13 | +from torchtitan.components.optimizer import OptimizersContainer | ||
| 14 | +from torchtitan.experiments.torchft.trainer import ( | ||
| 15 | + FaultTolerantTrainer as UpstreamFaultTolerantTrainer, | ||
| 16 | +) | ||
| 17 | + | ||
| 18 | +from torchtitan_npu.extensions.trainer import TrainerEx | ||
| 19 | +from torchtitan_npu.patches import torchft as torchft_patches | ||
| 20 | + | ||
| 21 | +torchft_patches.apply() | ||
| 22 | + | ||
| 23 | +import torchtitan_npu.interface.torchft.synchronization as synchronization_module | ||
| 24 | +import torchtitan_npu.patches.torchtitan.experiments.torchft.manager as hooks_module | ||
| 25 | +from torchtitan_npu.extensions.torchft import ( | ||
| 26 | + FaultTolerantTrainerEx, | ||
| 27 | + FTManagerEx, | ||
| 28 | + TorchFTCheckpointManagerEx, | ||
| 29 | + TorchFTOptimizersContainerEx, | ||
| 30 | +) | ||
| 31 | +from torchtitan_npu.interface.torchft.checkpoint_state import ( | ||
| 32 | + _TorchRngState, | ||
| 33 | +) | ||
| 34 | +from torchtitan_npu.interface.torchft.managed_process_group import ( | ||
| 35 | + LossManagedProcessGroupEx, | ||
| 36 | +) | ||
| 37 | +from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def _initialize_fault_tolerant_trainer(config, order, initialize_upstream) -> None: | ||
| 41 | + with ( | ||
| 42 | + patch.object( | ||
| 43 | + UpstreamFaultTolerantTrainer, | ||
| 44 | + "__init__", | ||
| 45 | + new=initialize_upstream, | ||
| 46 | + ), | ||
| 47 | + patch( | ||
| 48 | + "torchtitan_npu.extensions.torchft.trainer.set_chunked_loss_lm_head", | ||
| 49 | + side_effect=lambda _trainer: order.set_chunked_loss(), | ||
| 50 | + ), | ||
| 51 | + patch.object(FaultTolerantTrainerEx, "_rejoin_process_group", return_value=None), | ||
| 52 | + ): | ||
| 53 | + FaultTolerantTrainerEx(config) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def test_deepseek_v4_config_late_binds_torchft_after_enable(): | ||
| 57 | + base = deepseek_v4_debugmodel() | ||
| 58 | + assert isinstance(base, TrainerEx.Config) | ||
| 59 | + npu_config = base | ||
| 60 | + npu_config.extension.torchft.enable = True | ||
| 61 | + config = npu_config._as_torchft_config() | ||
| 62 | + | ||
| 63 | + assert isinstance(config, FaultTolerantTrainerEx.Config) | ||
| 64 | + assert isinstance(config.optimizer, TorchFTOptimizersContainerEx.Config) | ||
| 65 | + assert isinstance(config.checkpoint, TorchFTCheckpointManagerEx.Config) | ||
| 66 | + assert isinstance(config.fault_tolerance, FTManagerEx.Config) | ||
| 67 | + assert config.checkpoint.enable is False | ||
| 68 | + assert config.checkpoint.enable_ft_dataloader_checkpoints is True | ||
| 69 | + assert config.debug == base.debug | ||
| 70 | + assert ( | ||
| 71 | + config.fault_tolerance.process_group, | ||
| 72 | + config.fault_tolerance.group_size, | ||
| 73 | + config.fault_tolerance.min_replica_size, | ||
| 74 | + config.fault_tolerance.init_sync, | ||
| 75 | + ) == ("hccl", 2, 2, False) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def test_deepseek_v4_config_does_not_eagerly_import_torchft(): | ||
| 79 | + import subprocess | ||
| 80 | + import sys | ||
| 81 | + | ||
| 82 | + script = """ | ||
| 83 | +import sys | ||
| 84 | +import torchtitan_npu | ||
| 85 | +from torchtitan.config.manager import ConfigManager | ||
| 86 | +config = ConfigManager().parse_args([ | ||
| 87 | + '--module', 'torchtitan_npu.models.deepseek_v4', | ||
| 88 | + '--config', 'deepseek_v4_debugmodel', | ||
| 89 | +]) | ||
| 90 | +assert not config.extension.torchft.enable | ||
| 91 | +assert not any(name == 'torchft' or name.startswith('torchft.') for name in sys.modules) | ||
| 92 | +""" | ||
| 93 | + subprocess.run([sys.executable, "-c", script], check=True) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def test_deepseek_v4_config_exposes_torchft_cli_without_preimport(): | ||
| 97 | + import subprocess | ||
| 98 | + import sys | ||
| 99 | + | ||
| 100 | + script = """ | ||
| 101 | +from torchtitan.config.manager import ConfigManager | ||
| 102 | +config = ConfigManager().parse_args([ | ||
| 103 | + '--module', 'torchtitan_npu.models.deepseek_v4', | ||
| 104 | + '--config', 'deepseek_v4_debugmodel', | ||
| 105 | + '--extension.torchft.enable', | ||
| 106 | + '--extension.torchft.replica-id', '1', | ||
| 107 | +]) | ||
| 108 | +assert config.extension.torchft.enable | ||
| 109 | +assert config.extension.torchft.replica_id == 1 | ||
| 110 | +""" | ||
| 111 | + subprocess.run([sys.executable, "-c", script], check=True) | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +def test_deepseek_v4_torchft_recipe_defers_implementation_imports(): | ||
| 115 | + import subprocess | ||
| 116 | + import sys | ||
| 117 | + | ||
| 118 | + script = """ | ||
| 119 | +import sys | ||
| 120 | +from torchtitan.config.manager import ConfigManager | ||
| 121 | +config = ConfigManager().parse_args([ | ||
| 122 | + '--module', 'torchtitan_npu.models.deepseek_v4', | ||
| 123 | + '--config', 'deepseek_v4_torchft_debugmodel', | ||
| 124 | +]) | ||
| 125 | +assert config.extension.torchft.enable | ||
| 126 | +assert config.checkpoint.enable | ||
| 127 | +assert not any( | ||
| 128 | + name == 'torchtitan_npu.extensions.torchft' | ||
| 129 | + or name.startswith('torchtitan_npu.extensions.torchft.') | ||
| 130 | + for name in sys.modules | ||
| 131 | +) | ||
| 132 | +""" | ||
| 133 | + subprocess.run([sys.executable, "-c", script], check=True) | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +def test_npu_ft_trainer_initializes_configured_spmd_backend(): | ||
| 137 | + trainer = FaultTolerantTrainerEx.__new__(FaultTolerantTrainerEx) | ||
| 138 | + trainer.config = MagicMock() | ||
| 139 | + trainer.config.parallelism.spmd_backend = "spmd_types" | ||
| 140 | + trainer.config.override.imports = [] | ||
| 141 | + parallel_dims = MagicMock() | ||
| 142 | + | ||
| 143 | + with ( | ||
| 144 | + patch.object( | ||
| 145 | + UpstreamFaultTolerantTrainer, | ||
| 146 | + "init_distributed", | ||
| 147 | + return_value=parallel_dims, | ||
| 148 | + ), | ||
| 149 | + patch("torchtitan_npu.extensions.torchft.trainer.dist_utils.set_spmd_backend") as set_spmd_backend, | ||
| 150 | + ): | ||
| 151 | + result = trainer.init_distributed() | ||
| 152 | + | ||
| 153 | + assert result is parallel_dims | ||
| 154 | + set_spmd_backend.assert_called_once_with("spmd_types") | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def test_model_overrides_run_after_update_and_before_build(): | ||
| 158 | + class BaseModelConfig: | ||
| 159 | + def update_from_config(self, *, config): | ||
| 160 | + self.stage = "updated" | ||
| 161 | + order.update_model_config() | ||
| 162 | + | ||
| 163 | + class ModelConfig(BaseModelConfig): | ||
| 164 | + def build(self): | ||
| 165 | + assert self.stage == "overridden" | ||
| 166 | + order.build_model() | ||
| 167 | + | ||
| 168 | + order = MagicMock() | ||
| 169 | + model_config = ModelConfig() | ||
| 170 | + original_update = ModelConfig.update_from_config | ||
| 171 | + config = MagicMock() | ||
| 172 | + config.model_spec.model = model_config | ||
| 173 | + config.override.imports = ["override.factory"] | ||
| 174 | + config._validate_cuda_graphs.side_effect = lambda: order.validate_cuda_graphs() | ||
| 175 | + | ||
| 176 | + def apply_override(_override, _config): | ||
| 177 | + model_config.stage = "overridden" | ||
| 178 | + order.apply_overrides() | ||
| 179 | + | ||
| 180 | + def initialize_upstream(_trainer, trainer_config): | ||
| 181 | + trainer_config.model_spec.model.update_from_config(config=trainer_config) | ||
| 182 | + trainer_config.model_spec.model.build() | ||
| 183 | + | ||
| 184 | + with patch( | ||
| 185 | + "torchtitan_npu.extensions.torchft.trainer.apply_overrides", | ||
| 186 | + side_effect=apply_override, | ||
| 187 | + ): | ||
| 188 | + _initialize_fault_tolerant_trainer(config, order, initialize_upstream) | ||
| 189 | + | ||
| 190 | + assert order.mock_calls == [ | ||
| 191 | + call.update_model_config(), | ||
| 192 | + call.apply_overrides(), | ||
| 193 | + call.validate_cuda_graphs(), | ||
| 194 | + call.build_model(), | ||
| 195 | + call.set_chunked_loss(), | ||
| 196 | + ] | ||
| 197 | + assert ModelConfig.update_from_config is original_update | ||
| 198 | + assert "update_from_config" not in vars(ModelConfig) | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +def test_cuda_graph_validation_runs_without_model_overrides(): | ||
| 202 | + class ModelConfig: | ||
| 203 | + def update_from_config(self, *, config): | ||
| 204 | + order.update_model_config() | ||
| 205 | + | ||
| 206 | + def build(self): | ||
| 207 | + order.build_model() | ||
| 208 | + | ||
| 209 | + order = MagicMock() | ||
| 210 | + model_config = ModelConfig() | ||
| 211 | + config = MagicMock() | ||
| 212 | + config.model_spec.model = model_config | ||
| 213 | + config.override.imports = [] | ||
| 214 | + config._validate_cuda_graphs.side_effect = lambda: order.validate_cuda_graphs() | ||
| 215 | + | ||
| 216 | + def initialize_upstream(_trainer, trainer_config): | ||
| 217 | + trainer_config.model_spec.model.update_from_config(config=trainer_config) | ||
| 218 | + trainer_config.model_spec.model.build() | ||
| 219 | + | ||
| 220 | + _initialize_fault_tolerant_trainer(config, order, initialize_upstream) | ||
| 221 | + | ||
| 222 | + assert order.mock_calls == [ | ||
| 223 | + call.update_model_config(), | ||
| 224 | + call.validate_cuda_graphs(), | ||
| 225 | + call.build_model(), | ||
| 226 | + call.set_chunked_loss(), | ||
| 227 | + ] | ||
| 228 | + | ||
| 229 | + | ||
| 230 | +def test_replicate_dp_hook_uses_stream_ordered_cross_replica_all_reduce(): | ||
| 231 | + class FakeReplicateModule: | ||
| 232 | + def __init__(self) -> None: | ||
| 233 | + self.all_reduce_hook = None | ||
| 234 | + | ||
| 235 | + def _get_fsdp_state(self) -> SimpleNamespace: | ||
| 236 | + return SimpleNamespace(_fsdp_param_groups=[object()]) | ||
| 237 | + | ||
| 238 | + def set_all_reduce_hook(self, hook) -> None: | ||
| 239 | + self.all_reduce_hook = hook | ||
| 240 | + | ||
| 241 | + replicate_module = FakeReplicateModule() | ||
| 242 | + model_part = MagicMock() | ||
| 243 | + model_part.apply.side_effect = lambda callback: callback(replicate_module) | ||
| 244 | + | ||
| 245 | + manager = FTManagerEx.__new__(FTManagerEx) | ||
| 246 | + manager._manager = MagicMock() | ||
| 247 | + manager._manager.process_group = MagicMock() | ||
| 248 | + manager.use_async_quorum = True | ||
| 249 | + manager.group_size = 2 | ||
| 250 | + manager.replicate_pg = MagicMock() | ||
| 251 | + output = MagicMock() | ||
| 252 | + | ||
| 253 | + with ( | ||
| 254 | + patch.object(hooks_module, "ReplicateModule", FakeReplicateModule), | ||
| 255 | + patch.object(synchronization_module.dist, "all_reduce") as all_reduce, | ||
| 256 | + ): | ||
| 257 | + manager.maybe_set_all_reduce_hook([model_part]) | ||
| 258 | + replicate_module.all_reduce_hook(output) | ||
| 259 | + | ||
| 260 | + assert replicate_module.all_reduce_hook is not None | ||
| 261 | + all_reduce.assert_called_once_with( | ||
| 262 | + output, | ||
| 263 | + group=manager.replicate_pg, | ||
| 264 | + op=torch.distributed.ReduceOp.AVG, | ||
| 265 | + ) | ||
| 266 | + | ||
| 267 | + | ||
| 268 | +def test_loss_process_group_averages_float_sum_only(): | ||
| 269 | + process_group = LossManagedProcessGroupEx.__new__(LossManagedProcessGroupEx) | ||
| 270 | + process_group._manager = MagicMock() | ||
| 271 | + float_work = object() | ||
| 272 | + int_work = object() | ||
| 273 | + process_group._manager.allreduce.side_effect = [float_work, int_work] | ||
| 274 | + float_loss = torch.ones(()) | ||
| 275 | + token_count = torch.ones((), dtype=torch.int64) | ||
| 276 | + | ||
| 277 | + float_result = process_group.allreduce( | ||
| 278 | + [float_loss], | ||
| 279 | + torch.distributed.ReduceOp.SUM, | ||
| 280 | + ) | ||
| 281 | + int_result = process_group.allreduce( | ||
| 282 | + [token_count], | ||
| 283 | + torch.distributed.ReduceOp.SUM, | ||
| 284 | + ) | ||
| 285 | + | ||
| 286 | + assert float_result is float_work | ||
| 287 | + assert int_result is int_work | ||
| 288 | + assert process_group._manager.allreduce.call_args_list == [ | ||
| 289 | + call(float_loss, reduce_op=torch.distributed.ReduceOp.AVG), | ||
| 290 | + call(token_count, reduce_op=torch.distributed.ReduceOp.SUM), | ||
| 291 | + ] | ||
| 292 | + | ||
| 293 | + | ||
| 294 | +def test_rejected_quorum_syncs_moe_counts_then_rolls_back_bias(): | ||
| 295 | + calls: list[str] = [] | ||
| 296 | + model = nn.Module() | ||
| 297 | + model.weight = nn.Parameter(torch.zeros(())) | ||
| 298 | + model.load_balance_coeff = 1e-3 | ||
| 299 | + model.register_buffer("tokens_per_expert_E", torch.ones(4)) | ||
| 300 | + model.register_buffer("expert_bias_E", torch.zeros(4)) | ||
| 301 | + ft_manager = MagicMock() | ||
| 302 | + ft_manager.enabled = True | ||
| 303 | + ft_manager.use_async_quorum = True | ||
| 304 | + ft_manager.group_size = 2 | ||
| 305 | + ft_manager.sync_moe_load_balance_counts.side_effect = lambda _parts: calls.append("sync") | ||
| 306 | + ft_manager.manager.should_commit.return_value = False | ||
| 307 | + | ||
| 308 | + def initialize_base(owner, _config, *, model_parts): | ||
| 309 | + torch.optim.Optimizer.__init__(owner, [model.weight], {}) | ||
| 310 | + owner.optimizers = [] | ||
| 311 | + | ||
| 312 | + with patch.object(OptimizersContainer, "__init__", new=initialize_base): | ||
| 313 | + container = TorchFTOptimizersContainerEx(MagicMock(), model_parts=[model], ft_manager=ft_manager) | ||
| 314 | + | ||
| 315 | + def update_expert_bias(*_args, **_kwargs): | ||
| 316 | + calls.append("model") | ||
| 317 | + with torch.no_grad(): | ||
| 318 | + model.expert_bias_E.add_(1) | ||
| 319 | + | ||
| 320 | + container.register_step_pre_hook(update_expert_bias) | ||
| 321 | + container.step() | ||
| 322 | + | ||
| 323 | + assert calls == ["sync", "model"] | ||
| 324 | + assert torch.count_nonzero(model.expert_bias_E).item() == 0 | ||
| 325 | + | ||
| 326 | + | ||
| 327 | +def test_committed_quorum_runs_outer_hooks_and_inner_optimizer_once(): | ||
| 328 | + model = nn.Module() | ||
| 329 | + model.weight = nn.Parameter(torch.zeros(())) | ||
| 330 | + model.register_buffer("tokens_per_expert_E", torch.ones(4)) | ||
| 331 | + model.register_buffer("expert_bias_E", torch.zeros(4)) | ||
| 332 | + inner_optimizer = MagicMock() | ||
| 333 | + ft_manager = MagicMock() | ||
| 334 | + ft_manager.enabled = True | ||
| 335 | + ft_manager.use_async_quorum = True | ||
| 336 | + ft_manager.group_size = 2 | ||
| 337 | + ft_manager.manager.should_commit.return_value = True | ||
| 338 | + | ||
| 339 | + def initialize_base(owner, _config, *, model_parts): | ||
| 340 | + torch.optim.Optimizer.__init__(owner, [model.weight], {}) | ||
| 341 | + owner.optimizers = [inner_optimizer] | ||
| 342 | + | ||
| 343 | + with patch.object(OptimizersContainer, "__init__", new=initialize_base): | ||
| 344 | + container = TorchFTOptimizersContainerEx(MagicMock(), model_parts=[model], ft_manager=ft_manager) | ||
| 345 | + | ||
| 346 | + container.step() | ||
| 347 | + | ||
| 348 | + ft_manager.sync_moe_load_balance_counts.assert_called_once_with([model]) | ||
| 349 | + inner_optimizer.step.assert_called_once_with() | ||
| 350 | + | ||
| 351 | + | ||
| 352 | +def test_persistent_checkpoint_has_single_writer_and_restores_live_lr(): | ||
| 353 | + manager = TorchFTCheckpointManagerEx.__new__(TorchFTCheckpointManagerEx) | ||
| 354 | + manager._persistent_checkpoint_enabled = True | ||
| 355 | + manager.enable_ft_dataloader_checkpoints = False | ||
| 356 | + manager._lr_schedulers = MagicMock() | ||
| 357 | + manager.ft_manager = MagicMock() | ||
| 358 | + manager.ft_manager.participating_rank.return_value = 1 | ||
| 359 | + | ||
| 360 | + with ( | ||
| 361 | + patch.object(manager, "_owns_full_checkpoint", side_effect=[True, False]), | ||
| 362 | + patch( | ||
| 363 | + "torchtitan_npu.extensions.torchft.checkpoint.CheckpointManager.save", | ||
| 364 | + return_value=True, | ||
| 365 | + ) as save, | ||
| 366 | + patch( | ||
| 367 | + "torchtitan_npu.extensions.torchft.checkpoint.CheckpointManager.load", | ||
| 368 | + return_value=True, | ||
| 369 | + ), | ||
| 370 | + patch("torchtitan_npu.extensions.torchft.checkpoint._restore_optimizer_learning_rates") as restore, | ||
| 371 | + ): | ||
| 372 | + assert manager.save(2) is True | ||
| 373 | + assert manager.save(3) is False | ||
| 374 | + assert manager.load(2) is True | ||
| 375 | + | ||
| 376 | + save.assert_called_once_with(2, False) | ||
| 377 | + restore.assert_called_once_with(manager._lr_schedulers) | ||
| 378 | + | ||
| 379 | + | ||
| 380 | +def test_explicit_model_checkpoint_step_also_selects_dataloader_cursor(): | ||
| 381 | + manager = TorchFTCheckpointManagerEx.__new__(TorchFTCheckpointManagerEx) | ||
| 382 | + manager._persistent_checkpoint_enabled = True | ||
| 383 | + manager.enable_ft_dataloader_checkpoints = True | ||
| 384 | + manager._lr_schedulers = MagicMock() | ||
| 385 | + | ||
| 386 | + with ( | ||
| 387 | + patch.object(manager, "_ft_load") as load_dataloader, | ||
| 388 | + patch.object(CheckpointManager, "load", return_value=True) as load_persistent, | ||
| 389 | + patch("torchtitan_npu.extensions.torchft.checkpoint._restore_optimizer_learning_rates"), | ||
| 390 | + ): | ||
| 391 | + assert manager.load(7) is True | ||
| 392 | + | ||
| 393 | + load_dataloader.assert_called_once_with(7) | ||
| 394 | + load_persistent.assert_called_once_with(7) | ||
| 395 | + | ||
| 396 | + | ||
| 397 | +def test_peer_healing_without_persistent_checkpoint_does_not_require_states_attribute(): | ||
| 398 | + manager = TorchFTCheckpointManagerEx.__new__(TorchFTCheckpointManagerEx) | ||
| 399 | + manager._persistent_checkpoint_enabled = False | ||
| 400 | + manager.ft_manager = MagicMock() | ||
| 401 | + manager._lr_schedulers = MagicMock() | ||
| 402 | + input_states = {"train_state": MagicMock()} | ||
| 403 | + model_parts = [nn.Linear(2, 2)] | ||
| 404 | + optimizers = MagicMock() | ||
| 405 | + | ||
| 406 | + healing_states = manager._healing_states(input_states, model_parts, optimizers) | ||
| 407 | + | ||
| 408 | + assert healing_states["train_state"] is input_states["train_state"] | ||
| 409 | + assert healing_states["optimizer"] is optimizers | ||
| 410 | + | ||
| 411 | + | ||
| 412 | +def test_dataloader_checkpoint_storage_does_not_enable_persistent_checkpoint(): | ||
| 413 | + config = TorchFTCheckpointManagerEx.Config( | ||
| 414 | + enable=False, | ||
| 415 | + enable_ft_dataloader_checkpoints=True, | ||
| 416 | + ) | ||
| 417 | + dataloader = MagicMock() | ||
| 418 | + optimizers = MagicMock() | ||
| 419 | + lr_schedulers = MagicMock() | ||
| 420 | + ft_manager = MagicMock() | ||
| 421 | + ft_manager.enabled = True | ||
| 422 | + ft_manager.replica_id = 1 | ||
| 423 | + observed_storage_enable: bool | None = None | ||
| 424 | + | ||
| 425 | + def initialize_storage(owner, storage_config, **kwargs): | ||
| 426 | + nonlocal observed_storage_enable | ||
| 427 | + observed_storage_enable = storage_config.enable | ||
| 428 | + owner.enable = storage_config.enable | ||
| 429 | + owner.states = kwargs["states"] | ||
| 430 | + owner.folder = "/tmp/checkpoint" | ||
| 431 | + owner.pg = None | ||
| 432 | + owner.stager = None | ||
| 433 | + | ||
| 434 | + with ( | ||
| 435 | + patch.object(CheckpointManager, "__init__", new=initialize_storage), | ||
| 436 | + patch( | ||
| 437 | + "torchtitan_npu.extensions.torchft.checkpoint.dist.new_group", | ||
| 438 | + return_value=MagicMock(), | ||
| 439 | + ), | ||
| 440 | + ): | ||
| 441 | + manager = TorchFTCheckpointManagerEx( | ||
| 442 | + config, | ||
| 443 | + dataloader=dataloader, | ||
| 444 | + model_parts=[nn.Linear(2, 2)], | ||
| 445 | + optimizers=optimizers, | ||
| 446 | + lr_schedulers=lr_schedulers, | ||
| 447 | + states={"train_state": MagicMock()}, | ||
| 448 | + sd_adapter=None, | ||
| 449 | + ft_manager=ft_manager, | ||
| 450 | + ) | ||
| 451 | + | ||
| 452 | + assert observed_storage_enable is True | ||
| 453 | + assert manager._persistent_checkpoint_enabled is False | ||
| 454 | + assert manager.enable_ft_dataloader_checkpoints is True | ||
| 455 | + assert manager.ft_states["dataloader"] is dataloader | ||
| 456 | + | ||
| 457 | + with ( | ||
| 458 | + patch.object(manager, "_ft_save") as save_dataloader, | ||
| 459 | + patch.object(manager, "_ft_load") as load_dataloader, | ||
| 460 | + patch.object(CheckpointManager, "save") as save_persistent, | ||
| 461 | + patch.object(CheckpointManager, "load") as load_persistent, | ||
| 462 | + ): | ||
| 463 | + manager.save(curr_step=1) | ||
| 464 | + loaded = manager.load() | ||
| 465 | + | ||
| 466 | + save_dataloader.assert_called_once_with(1) | ||
| 467 | + load_dataloader.assert_called_once_with(-1) | ||
| 468 | + save_persistent.assert_not_called() | ||
| 469 | + load_persistent.assert_not_called() | ||
| 470 | + assert loaded is False | ||
| 471 | + | ||
| 472 | + | ||
| 473 | +def test_torch_rng_state_restores_loaded_cpu_and_npu_streams(): | ||
| 474 | + state = _TorchRngState() | ||
| 475 | + loaded = { | ||
| 476 | + "cpu_rank_3": MagicMock(), | ||
| 477 | + "npu_rank_3": MagicMock(), | ||
| 478 | + } | ||
| 479 | + loaded["cpu_rank_3"].clone.return_value = "cpu-state" | ||
| 480 | + loaded["npu_rank_3"].clone.return_value = "npu-state" | ||
| 481 | + | ||
| 482 | + with ( | ||
| 483 | + patch( | ||
| 484 | + "torchtitan_npu.interface.torchft.checkpoint_state.dist.is_initialized", | ||
| 485 | + return_value=True, | ||
| 486 | + ), | ||
| 487 | + patch( | ||
| 488 | + "torchtitan_npu.interface.torchft.checkpoint_state.dist.get_rank", | ||
| 489 | + return_value=3, | ||
| 490 | + ), | ||
| 491 | + patch("torchtitan_npu.interface.torchft.checkpoint_state.torch.set_rng_state") as set_cpu, | ||
| 492 | + patch("torchtitan_npu.interface.torchft.checkpoint_state.torch_npu.npu.set_rng_state") as set_npu, | ||
| 493 | + ): | ||
| 494 | + state.load_state_dict(loaded) | ||
| 495 | + assert state.restore_pending() is True | ||
| 496 | + assert state.restore_pending() is False | ||
| 497 | + | ||
| 498 | + set_cpu.assert_called_once_with("cpu-state") | ||
| 499 | + set_npu.assert_called_once_with("npu-state") | ||