Open
[feat] Port TorchFT last-words checkpoints to dev_0.4.0 #1427
zhangyifan999Add on 6 days ago
[feat] Port TorchFT last-words checkpoints to dev_0.4.0 #1427
Open
Total: 37 files changed+4806-73
| @@ -21,6 +21,8 @@ | |||
| 21 | 21 | ||
| 22 | TorchFT engine 的按需激活、唯一 owner 和顺序见[架构说明](docs/architecture.md#torchft-engine),不得新增第二个直接绑定入口。 | 22 | TorchFT engine 的按需激活、唯一 owner 和顺序见[架构说明](docs/architecture.md#torchft-engine),不得新增第二个直接绑定入口。 |
| 23 | 23 | ||
| 24 | +TorchFT 遗言 service 与 worker 归入 TorchFT extension。训练由节点上的 torchrun 启动,外部调度器管理作业生命周期。 | ||
| 25 | + | ||
| 24 | ## 上游与验证 | 26 | ## 上游与验证 |
| 25 | 27 | ||
| 26 | `requirements.txt` 声明 torchtitan 版本,`.ci/setup_torchtitan.sh` 从该版本推导对应 tag。更新版本时同步核对 patch 目标、接口和测试。 | 28 | `requirements.txt` 声明 torchtitan 版本,`.ci/setup_torchtitan.sh` 从该版本推导对应 tag。更新版本时同步核对 patch 目标、接口和测试。 |
| @@ -71,6 +71,8 @@ TorchFT 通过现有 FT recipe 按需导入 `torchtitan_npu.extensions.torchtita | |||
| 71 | 71 | ||
| 72 | 该绑定针对上游 FT 构造函数运行时读取的 engine 符号;上游 FT 构造函数不使用普通 Trainer 的 `engine_cls`。它不替换已被 dataclass 捕获的 `.Config`,其他模块不得再次直接替换该目标。现有 recipe 名称和模块路径不变。 | 72 | 该绑定针对上游 FT 构造函数运行时读取的 engine 符号;上游 FT 构造函数不使用普通 Trainer 的 `engine_cls`。它不替换已被 dataclass 捕获的 `.Config`,其他模块不得再次直接替换该目标。现有 recipe 名称和模块路径不变。 |
| 73 | 73 | ||
| 74 | +遗言 worker 在训练进程内维护心跳和安全边界,独立 service 为一次故障选择一个完整健康 replica 保存。部署入口和恢复约束见[TorchFT 遗言保存](feature_guides/torchft_last_words.md)。 | ||
| 75 | + | ||
| 74 | ## 目标子层 | 76 | ## 目标子层 |
| 75 | 77 | ||
| 76 | ### patches | 78 | ### patches |
Adocs/feature_guides/torchft_last_words.md+156-0File content is under review, please try again later
| @@ -36,6 +36,8 @@ ASCEND_SET_ENV_PATH=/path/to/ascend-toolkit/set_env.sh \ | |||
| 36 | 36 | ||
| 37 | 环境脚本的默认搜索位置见 [`scripts/run_train.sh`](../../scripts/run_train.sh)。启动脚本负责加载环境和启动训练进程,训练参数在 Python 配置中设置。 | 37 | 环境脚本的默认搜索位置见 [`scripts/run_train.sh`](../../scripts/run_train.sh)。启动脚本负责加载环境和启动训练进程,训练参数在 Python 配置中设置。 |
| 38 | 38 | ||
| 39 | +DeepSeek-V4 Flash 的同步 TorchFT 作业可在 Python recipe 中开启遗言保存。启动 Lighthouse、遗言 service 和各 replica 的步骤见[TorchFT 遗言指南](../feature_guides/torchft_last_words.md#启动方式)。 | ||
| 40 | + | ||
| 39 | ## 集成和数值验证 | 41 | ## 集成和数值验证 |
| 40 | 42 | ||
| 41 | 集成测试入口及用例定义见[集成测试指南](../../tests/integration_tests/README.md)。训练组合的验证状态以实际执行结果为准;按[数值验证要求](../developer_guides/numerical_alignment.md)比较固定 checkpoint 下未截断的 loss 与 grad_norm。 | 43 | 集成测试入口及用例定义见[集成测试指南](../../tests/integration_tests/README.md)。训练组合的验证状态以实际执行结果为准;按[数值验证要求](../developer_guides/numerical_alignment.md)比较固定 checkpoint 下未截断的 loss 与 grad_norm。 |
| @@ -45,6 +45,7 @@ python -m tests.integration_tests.run_tests \ | |||
| 45 | 以下为已注册 Suite 的用途,不表示所有用例均已完成 0.4.0 迁移。实际执行还受 runner 的迁移门禁和硬件条件限制: | 45 | 以下为已注册 Suite 的用途,不表示所有用例均已完成 0.4.0 迁移。实际执行还受 runner 的迁移门禁和硬件条件限制: |
| 46 | * **`models`**:DeepSeek-V4、DeepSeek-V4.1 多卡基础训练冒烟与 Loss 对齐校验; | 46 | * **`models`**:DeepSeek-V4、DeepSeek-V4.1 多卡基础训练冒烟与 Loss 对齐校验; |
| 47 | * **`deepseek_cp`**:V4 和 V4.1 BF16 双卡逐文档 CP 冒烟,只覆盖连续切分,各跑两步;单独运行; | 47 | * **`deepseek_cp`**:V4 和 V4.1 BF16 双卡逐文档 CP 冒烟,只覆盖连续切分,各跑两步;单独运行; |
| 48 | +* **`torchft_last_words`**:单机四卡组成两个 FSDP2/EP2 的 TorchFT 副本,使用 DeepSeek-V4 小模型、MTP 和共享 checkpoint 目录。`dsv4_torchft_last_words_emergency_save_2x2` 在第 3 步开始前退出一个故障 rank,核对健康副本两个 rank 完成保存后正常退出,外部重启从第 2 步的临终 checkpoint 续训至第 6 步。`dsv4_torchft_last_words_numerical_2x2` 使用共同初态与逐 microbatch 输入,对比基线关闭、当前关闭和当前开启遗言时逐步的 loss、grad norm;需将 `LAST_WORDS_BASELINE_REPO` 指向 `d882efb99d92d24e777166689c149aa2a85997bc` 的完整干净源码。运行前安装 TorchFT 0.2.0,准备仓内 C4、DeepSeek tokenizer 测试资产及至少 96 GiB 可用磁盘。 | ||
| 48 | * **`deepseek_v4_checkpoint`**:DeepSeek-V4 分布式断点续训两阶段比对; | 49 | * **`deepseek_v4_checkpoint`**:DeepSeek-V4 分布式断点续训两阶段比对; |
| 49 | * **`deepseek_v4_quantized`**:DeepSeek-V4 Block-FP8 量化(需 Ascend 950 芯片); | 50 | * **`deepseek_v4_quantized`**:DeepSeek-V4 Block-FP8 量化(需 Ascend 950 芯片); |
| 50 | * **`deepseek_v4_1`**:DeepSeek-V4.1 文本和图像 LoRA 训练与 PEFT 导出;同时纳入默认 `models` suite; | 51 | * **`deepseek_v4_1`**:DeepSeek-V4.1 文本和图像 LoRA 训练与 PEFT 导出;同时纳入默认 `models` suite; |
| @@ -40,6 +40,7 @@ class OverrideDefinitions: | |||
| 40 | # Python recipes use the constrained ConfigLoader CLI and own all training settings. | 40 | # Python recipes use the constrained ConfigLoader CLI and own all training settings. |
| 41 | python_config: bool = False | 41 | python_config: bool = False |
| 42 | check_resume_state: bool = False | 42 | check_resume_state: bool = False |
| 43 | + required_env: tuple[str, ...] = () | ||
| 43 | required_checkpoint_keys: tuple[str, ...] = () | 44 | required_checkpoint_keys: tuple[str, ...] = () |
| 44 | require_indexer_audit: bool = False | 45 | require_indexer_audit: bool = False |
| 45 | 46 | ||
| @@ -0,0 +1,482 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +"""Four-NPU single emergency save and numerical cases; launches owned test jobs only.""" | ||
| 5 | + | ||
| 6 | +import argparse | ||
| 7 | +import hashlib | ||
| 8 | +import json | ||
| 9 | +import math | ||
| 10 | +import os | ||
| 11 | +import re | ||
| 12 | +import runpy | ||
| 13 | +import shutil | ||
| 14 | +import signal | ||
| 15 | +import socket | ||
| 16 | +import subprocess | ||
| 17 | +import sys | ||
| 18 | +import threading | ||
| 19 | +import time | ||
| 20 | +import uuid | ||
| 21 | +from contextlib import suppress | ||
| 22 | +from pathlib import Path | ||
| 23 | + | ||
| 24 | +from tests.integration_tests import OverrideDefinitions | ||
| 25 | +from tests.integration_tests.deepseek_v4 import NPU_OVERRIDES | ||
| 26 | + | ||
| 27 | +_SERVICE = runpy.run_path( | ||
| 28 | + str( | ||
| 29 | + Path(__file__).resolve().parents[2] | ||
| 30 | + / "torchtitan_npu/extensions/torchtitan/experiments/torchft/last_words/service.py" | ||
| 31 | + ) | ||
| 32 | +) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def start_child(command, **kwargs): | ||
| 36 | + return subprocess.Popen(command, start_new_session=True, **kwargs) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def stop_children(children): | ||
| 40 | + # The test runner acts as an external job manager; production never kills peers. | ||
| 41 | + for child in children: | ||
| 42 | + with suppress(ProcessLookupError): | ||
| 43 | + os.killpg(child.pid, signal.SIGTERM) | ||
| 44 | + for child in children: | ||
| 45 | + try: | ||
| 46 | + child.wait(timeout=5) | ||
| 47 | + except subprocess.TimeoutExpired: | ||
| 48 | + os.killpg(child.pid, signal.SIGKILL) | ||
| 49 | + child.wait(timeout=5) | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +SCENARIOS = ("emergency_save", "numerical") | ||
| 53 | +# Pre-fix reference for this regression and its LF-normalized Python source manifest. | ||
| 54 | +BASELINE_COMMIT = "d882efb99d92d24e777166689c149aa2a85997bc" | ||
| 55 | +BASELINE_SOURCE_SHA256 = "3d66b52e1ca3cf49f1ec10d58b4eadbcaed68b2dfbeb6e6c29021f56ae784538" | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def build_last_words_test_list(): | ||
| 59 | + return [ | ||
| 60 | + OverrideDefinitions( | ||
| 61 | + test_name=f"dsv4_torchft_last_words_{scenario}_2x2", | ||
| 62 | + ngpu=4, | ||
| 63 | + check_loss=False, | ||
| 64 | + use_golden=False, | ||
| 65 | + python_config=True, | ||
| 66 | + required_env=("LAST_WORDS_BASELINE_REPO",) if scenario == "numerical" else (), | ||
| 67 | + test_descr=( | ||
| 68 | + "TorchFT single-writer emergency save without automatic relaunch" | ||
| 69 | + if scenario == "emergency_save" | ||
| 70 | + else "TorchFT shared-initial-state baseline/off/on numerical equality" | ||
| 71 | + ), | ||
| 72 | + train_script="tests/integration_tests/run_last_words.sh", | ||
| 73 | + train_args=(), | ||
| 74 | + override_args=[(f"--scenario={scenario}",)], | ||
| 75 | + timeout=7200 if os.environ.get("LAST_WORDS_COMPILE_BACKEND") else 2400, | ||
| 76 | + ) | ||
| 77 | + for scenario in SCENARIOS | ||
| 78 | + ] | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def free_port(): | ||
| 82 | + with socket.socket() as sock: | ||
| 83 | + sock.bind(("127.0.0.1", 0)) | ||
| 84 | + return sock.getsockname()[1] | ||
| 85 | + | ||
| 86 | + | ||
| 87 | +def verify_fault_injection(folder, phase, scenario, fault_step): | ||
| 88 | + path = folder / "evidence/injected-replica-1-rank-0.json" | ||
| 89 | + value = json.loads(path.read_text()) | ||
| 90 | + if value["point"] != "boundary_process_exit" or value["step"] != fault_step: | ||
| 91 | + raise AssertionError(f"Wrong fault point or generation: {phase}/{scenario}, {value}") | ||
| 92 | + injections = [value] | ||
| 93 | + # Preserve each generation before the next phase overwrites per-rank files. | ||
| 94 | + (folder / "evidence" / f"injections-{phase}.json").write_text(json.dumps(injections)) | ||
| 95 | + return injections | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def run_phase( | ||
| 99 | + folder, | ||
| 100 | + *, | ||
| 101 | + phase, | ||
| 102 | + scenario, | ||
| 103 | + devices, | ||
| 104 | + fault_step=3, | ||
| 105 | + source=None, | ||
| 106 | + steps=6, | ||
| 107 | + interval=100, | ||
| 108 | + seq_len=256, | ||
| 109 | + recipe="reference", | ||
| 110 | + resume_path=None, | ||
| 111 | + initial_root=None, | ||
| 112 | +): | ||
| 113 | + recipe = os.environ.get("LAST_WORDS_RECIPE", recipe) | ||
| 114 | + if os.environ.get("LAST_WORDS_COMPILE_BACKEND"): | ||
| 115 | + recipe = os.environ.get("LAST_WORDS_COMPILE_RECIPE", recipe) | ||
| 116 | + seq_len = int(os.environ.get("LAST_WORDS_COMPILE_SEQ_LEN", seq_len)) | ||
| 117 | + if recipe not in ("reference", "npu"): | ||
| 118 | + raise ValueError("Unknown last-words operator recipe") | ||
| 119 | + required_free_bytes = 96 * 1024**3 | ||
| 120 | + run_id = f"st-{phase}-{uuid.uuid4().hex}" | ||
| 121 | + folder.mkdir(parents=True, exist_ok=True) | ||
| 122 | + port = free_port() | ||
| 123 | + lighthouse_log = (folder / f"lighthouse-{phase}.log").open("w") | ||
| 124 | + is_fault = phase == "fault" | ||
| 125 | + enabled = is_fault or phase in ("current_on", "resume") | ||
| 126 | + if os.environ.get("LAST_WORDS_COORDINATION_BACKEND", "service") != "service": | ||
| 127 | + raise ValueError("Only the service coordination backend is supported") | ||
| 128 | + lighthouse_command = ["torchft_lighthouse", "--bind", f"127.0.0.1:{port}", "--min_replicas", "2"] | ||
| 129 | + lighthouse = start_child(lighthouse_command, stdout=lighthouse_log, stderr=subprocess.STDOUT) | ||
| 130 | + children, logs = [], [] | ||
| 131 | + service = None | ||
| 132 | + service_thread = None | ||
| 133 | + session_dir = folder / f"service-{phase}" | ||
| 134 | + train_script = Path(__file__).with_name("last_words_train_probe.py").resolve() | ||
| 135 | + started = time.monotonic() | ||
| 136 | + try: | ||
| 137 | + if shutil.disk_usage(folder).free < required_free_bytes: | ||
| 138 | + raise OSError("Insufficient checkpoint reserve for the NPU case") | ||
| 139 | + if enabled: | ||
| 140 | + service = _SERVICE["ServiceServer"](("127.0.0.1", 0)) | ||
| 141 | + _SERVICE["prepare_session"]( | ||
| 142 | + service, | ||
| 143 | + session_dir, | ||
| 144 | + address=f"http://127.0.0.1:{service.server_port}", | ||
| 145 | + run_id=run_id, | ||
| 146 | + num_replicas=2, | ||
| 147 | + world_size=2, | ||
| 148 | + heartbeat_seconds=30, | ||
| 149 | + startup_seconds=900, | ||
| 150 | + timeout_seconds=180, | ||
| 151 | + ) | ||
| 152 | + service_thread = threading.Thread(target=service.serve_forever, daemon=True) | ||
| 153 | + service_thread.start() | ||
| 154 | + time.sleep(1) | ||
| 155 | + if lighthouse is not None and lighthouse.poll() is not None: | ||
| 156 | + raise RuntimeError("TorchFT Lighthouse failed to start") | ||
| 157 | + for replica in range(2): | ||
| 158 | + device_start, device_end = replica * 2, replica * 2 + 2 | ||
| 159 | + env = dict( | ||
| 160 | + os.environ, | ||
| 161 | + TORCHFT_LIGHTHOUSE=f"http://127.0.0.1:{port}", | ||
| 162 | + ASCEND_RT_VISIBLE_DEVICES=",".join(devices[device_start:device_end]), | ||
| 163 | + TORCHFT_REPLICA_ID=str(replica), | ||
| 164 | + TORCHFT_MIN_REPLICA_SIZE="2", | ||
| 165 | + LAST_WORDS_TEST_PHASE=phase, | ||
| 166 | + LAST_WORDS_TEST_STEPS=str(steps), | ||
| 167 | + LAST_WORDS_TEST_INTERVAL=str(interval), | ||
| 168 | + LAST_WORDS_TEST_SEQ_LEN=str(seq_len), | ||
| 169 | + LAST_WORDS_TEST_RUN_ID=run_id, | ||
| 170 | + LAST_WORDS_TEST_REPLICA=str(replica), | ||
| 171 | + LAST_WORDS_TEST_SCENARIO=scenario, | ||
| 172 | + LAST_WORDS_TEST_FAULT_STEP=str(fault_step), | ||
| 173 | + LAST_WORDS_TEST_EVIDENCE=str(folder / "evidence"), | ||
| 174 | + OMP_NUM_THREADS="2", | ||
| 175 | + CPU_AFFINITY_CONF="0", | ||
| 176 | + ) | ||
| 177 | + # The replicas are independent torchrun jobs on the same host. | ||
| 178 | + # Reserve a 16-device HCCL port block for each job. | ||
| 179 | + base_port = int(env.get("HCCL_IF_BASE_PORT", "61000")) + 16 * replica | ||
| 180 | + if not 1024 <= base_port <= 65535 - 15: | ||
| 181 | + raise ValueError("HCCL_IF_BASE_PORT must allow two consecutive 16-port blocks") | ||
| 182 | + env["HCCL_IF_BASE_PORT"] = str(base_port) | ||
| 183 | + if initial_root is not None: | ||
| 184 | + env["LAST_WORDS_TEST_INITIAL_ROOT"] = str(initial_root) | ||
| 185 | + if resume_path is not None: | ||
| 186 | + env["LAST_WORDS_TEST_RESUME_PATH"] = str(resume_path) | ||
| 187 | + if os.environ.get("LAST_WORDS_COMPILE_BACKEND"): | ||
| 188 | + for key in ("TORCHINDUCTOR_CACHE_DIR", "TORCHINDUCTOR_NPU_EXT_CACHE_DIR"): | ||
| 189 | + env[key] = str(folder / "compile-cache" / run_id / key.lower()) | ||
| 190 | + if enabled: | ||
| 191 | + env["LAST_WORDS_SESSION_FILE"] = str(session_dir / f"replica-{replica}.json") | ||
| 192 | + current_root = Path(__file__).resolve().parents[2] | ||
| 193 | + dependencies = [ | ||
| 194 | + str(Path(path).resolve()) | ||
| 195 | + for path in env.get("PYTHONPATH", "").split(os.pathsep) | ||
| 196 | + if path and Path(path).resolve() != current_root | ||
| 197 | + ] | ||
| 198 | + env["PYTHONPATH"] = os.pathsep.join([str(source or current_root), *dependencies]) | ||
| 199 | + log = (folder / f"{phase}-replica-{replica}.log").open("w") | ||
| 200 | + logs.append(log) | ||
| 201 | + compile_backend = os.environ.get("LAST_WORDS_COMPILE_BACKEND") | ||
| 202 | + worker = [str(train_script)] | ||
| 203 | + if compile_backend: | ||
| 204 | + worker = [ | ||
| 205 | + "--no-python", | ||
| 206 | + "bash", | ||
| 207 | + str(train_script.with_name("run_last_words.sh")), | ||
| 208 | + "--compile-worker", | ||
| 209 | + sys.executable, | ||
| 210 | + str(train_script), | ||
| 211 | + ] | ||
| 212 | + command = [ | ||
| 213 | + sys.executable, | ||
| 214 | + "-m", | ||
| 215 | + "torch.distributed.run", | ||
| 216 | + "--nproc-per-node=2", | ||
| 217 | + "--rdzv-backend=c10d", | ||
| 218 | + "--rdzv-endpoint=localhost:0", | ||
| 219 | + "--max-restarts=0", | ||
| 220 | + *worker, | ||
| 221 | + "--module=last_words_small_config", | ||
| 222 | + "--config=deepseek_v4_small_torchft", | ||
| 223 | + f"--output-dir={folder}", | ||
| 224 | + ] | ||
| 225 | + if recipe == "npu": | ||
| 226 | + env["LAST_WORDS_TEST_OVERRIDES"] = json.dumps(NPU_OVERRIDES[1:]) | ||
| 227 | + children.append(start_child(command, cwd=source, env=env, stdout=log, stderr=subprocess.STDOUT)) | ||
| 228 | + deadline = time.monotonic() + max(3000 if os.environ.get("LAST_WORDS_COMPILE_BACKEND") else 660, steps * 30) | ||
| 229 | + candidate_root = folder / "checkpoint/last_words" / run_id | ||
| 230 | + while any(child.poll() is None for child in children): | ||
| 231 | + if time.monotonic() > deadline: | ||
| 232 | + raise TimeoutError(f"Last-words {phase}/{scenario} phase timed out") | ||
| 233 | + if not is_fault and any(child.poll() not in (None, 0) for child in children): | ||
| 234 | + raise RuntimeError(f"A replica failed during {phase}/{scenario}") | ||
| 235 | + time.sleep(0.5) | ||
| 236 | + if not is_fault: | ||
| 237 | + if any(child.returncode != 0 for child in children): | ||
| 238 | + raise RuntimeError(f"{phase} training did not finish") | ||
| 239 | + if enabled: | ||
| 240 | + result = json.loads((session_dir / "result.json").read_text()) | ||
| 241 | + if not result["success"] or result["round"] != 0 or result["replica_id"] is not None: | ||
| 242 | + raise AssertionError("Normal training requires explicit completion from every rank") | ||
| 243 | + return None | ||
| 244 | + verify_fault_injection(folder, phase, scenario, fault_step) | ||
| 245 | + result = json.loads((session_dir / "result.json").read_text()) | ||
| 246 | + grant = json.loads((session_dir / "grant.json").read_text()) | ||
| 247 | + if result["success"] is not True or any( | ||
| 248 | + record["run_id"] != run_id or record["replica_id"] != 0 or record["round"] != 1 | ||
| 249 | + for record in (grant, result) | ||
| 250 | + ): | ||
| 251 | + raise AssertionError("Fault in replica 1 requires replica 0 to succeed as the only round-1 writer") | ||
| 252 | + candidates = list(candidate_root.glob("replica-*/manifest.json")) | ||
| 253 | + if len(candidates) != 1: | ||
| 254 | + raise AssertionError(f"Single-writer fault must publish exactly one complete candidate: {len(candidates)}") | ||
| 255 | + selected = candidates[0] | ||
| 256 | + # torchrun succeeds only when every worker exits with code zero. | ||
| 257 | + if children[0].returncode != 0: | ||
| 258 | + raise AssertionError("The healthy writer did not exit cleanly") | ||
| 259 | + writer_log = (folder / "fault-replica-0.log").read_text() | ||
| 260 | + for rank in (0, 1): | ||
| 261 | + if f"Writer rank {rank} completed last-words save at {selected.parent}" not in writer_log: | ||
| 262 | + raise AssertionError(f"Writer rank {rank} did not complete the final save barrier") | ||
| 263 | + saved = json.loads(selected.read_text()) | ||
| 264 | + receipt = json.loads((selected.parent / "service-result.json").read_text()) | ||
| 265 | + if ( | ||
| 266 | + selected.parent.name != "replica-0" | ||
| 267 | + or saved["replica_id"] != 0 | ||
| 268 | + or saved["run_id"] != run_id | ||
| 269 | + or any( | ||
| 270 | + receipt[key] != result[key] | ||
| 271 | + for key in ("run_id", "round", "replica_id", "coordinator_instance", "success") | ||
| 272 | + ) | ||
| 273 | + or grant["coordinator_instance"] != result["coordinator_instance"] | ||
| 274 | + ): | ||
| 275 | + raise AssertionError("Emergency checkpoint writer or service identity differs from the grant and result") | ||
| 276 | + if saved["state"]["step"] != fault_step - 1: | ||
| 277 | + raise AssertionError("Checkpoint must preserve the last completed update before injection") | ||
| 278 | + return selected | ||
| 279 | + finally: | ||
| 280 | + if service_thread is not None and service_thread.is_alive(): | ||
| 281 | + service.shutdown() | ||
| 282 | + service_thread.join(timeout=3) | ||
| 283 | + if service is not None: | ||
| 284 | + service.server_close() | ||
| 285 | + stop_children([child for child in [*children, lighthouse] if child.poll() is None]) | ||
| 286 | + lighthouse_log.close() | ||
| 287 | + for log in logs: | ||
| 288 | + log.close() | ||
| 289 | + (folder / f"timing-{phase}.json").write_text(json.dumps({"seconds": time.monotonic() - started})) | ||
| 290 | + | ||
| 291 | + | ||
| 292 | +def verified_baseline(folder): | ||
| 293 | + baseline = os.environ.get("LAST_WORDS_BASELINE_REPO") | ||
| 294 | + if not baseline or not (Path(baseline) / "torchtitan_npu").is_dir(): | ||
| 295 | + raise ValueError( | ||
| 296 | + "Numerical case requires LAST_WORDS_BASELINE_REPO containing the original full source snapshot" | ||
| 297 | + ) | ||
| 298 | + baseline_root = Path(baseline).resolve() | ||
| 299 | + if (baseline_root / ".git").exists(): | ||
| 300 | + baseline_commit = subprocess.check_output(["git", "-C", baseline, "rev-parse", "HEAD"], text=True).strip() | ||
| 301 | + if baseline_commit != BASELINE_COMMIT: | ||
| 302 | + raise ValueError(f"Expected numerical baseline {BASELINE_COMMIT}, found {baseline_commit}") | ||
| 303 | + if subprocess.check_output(["git", "-C", baseline, "status", "--porcelain", "--untracked-files=no"], text=True): | ||
| 304 | + raise ValueError("Numerical baseline requires a clean tracked source checkout") | ||
| 305 | + hashes = { | ||
| 306 | + path.relative_to(baseline_root).as_posix(): hashlib.sha256( | ||
| 307 | + path.read_bytes().replace(b"\r\n", b"\n") | ||
| 308 | + ).hexdigest() | ||
| 309 | + for package in ("torchtitan_npu", "torchtitan_npu_recipes") | ||
| 310 | + for path in (baseline_root / package).rglob("*.py") | ||
| 311 | + } | ||
| 312 | + if hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest() != BASELINE_SOURCE_SHA256: | ||
| 313 | + raise ValueError(f"Numerical baseline Python sources differ from {BASELINE_COMMIT}") | ||
| 314 | + evidence = {"repository": str(baseline_root), "commit": BASELINE_COMMIT, "python_sha256": hashes} | ||
| 315 | + (folder / "baseline-source.json").write_text(json.dumps(evidence, sort_keys=True)) | ||
| 316 | + return baseline_root | ||
| 317 | + | ||
| 318 | + | ||
| 319 | +def numerical_inputs(evidence, steps): | ||
| 320 | + # Global batch 8 across four ranks with local batch 1 gives two microbatches per step. | ||
| 321 | + expected = { | ||
| 322 | + f"input-step-{step}-microbatch-{microbatch}-replica-{replica}-rank-{rank}.json" | ||
| 323 | + for step in range(1, steps + 1) | ||
| 324 | + for microbatch in range(2) | ||
| 325 | + for replica in range(2) | ||
| 326 | + for rank in range(2) | ||
| 327 | + } | ||
| 328 | + found = {path.name for path in evidence.glob("input-step-*.json")} | ||
| 329 | + if found != expected: | ||
| 330 | + raise AssertionError( | ||
| 331 | + f"Input evidence in {evidence}: missing {sorted(expected - found)}, extra {sorted(found - expected)}" | ||
| 332 | + ) | ||
| 333 | + inputs = {} | ||
| 334 | + for name in sorted(expected): | ||
| 335 | + digest = json.loads((evidence / name).read_text())["batch"] | ||
| 336 | + if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest): | ||
| 337 | + raise AssertionError(f"Invalid batch SHA-256: {evidence / name}") | ||
| 338 | + inputs[name] = digest | ||
| 339 | + return inputs | ||
| 340 | + | ||
| 341 | + | ||
| 342 | +def numerical_case(folder, devices): | ||
| 343 | + baseline_root = verified_baseline(folder) | ||
| 344 | + init = folder / "initial" | ||
| 345 | + run_phase(init, phase="init", scenario="numerical", devices=devices, initial_root=init / "shared-state") | ||
| 346 | + values = [] | ||
| 347 | + baseline_inputs = None | ||
| 348 | + steps = 6 | ||
| 349 | + for phase in ("baseline_off", "current_off", "current_on"): | ||
| 350 | + target = folder / phase | ||
| 351 | + target.mkdir() | ||
| 352 | + run_phase( | ||
| 353 | + target, | ||
| 354 | + phase=phase, | ||
| 355 | + scenario="numerical", | ||
| 356 | + devices=devices, | ||
| 357 | + source=baseline_root if phase == "baseline_off" else None, | ||
| 358 | + steps=steps, | ||
| 359 | + initial_root=init / "shared-state", | ||
| 360 | + ) | ||
| 361 | + inputs = numerical_inputs(target / "evidence", steps) | ||
| 362 | + if baseline_inputs is None: | ||
| 363 | + baseline_inputs = inputs | ||
| 364 | + else: | ||
| 365 | + for name, digest in inputs.items(): | ||
| 366 | + if digest != baseline_inputs[name]: | ||
| 367 | + raise AssertionError(f"Training input differs from baseline_off: {phase}/{name}") | ||
| 368 | + initial = list((target / "evidence").glob(f"initial-loaded-{phase}-*.json")) | ||
| 369 | + if len(initial) != 4: | ||
| 370 | + raise AssertionError(f"Missing complete initial-state load evidence: {phase}") | ||
| 371 | + for replica in range(2): | ||
| 372 | + for rank in range(2): | ||
| 373 | + saved_model = json.loads((init / "evidence" / f"initial-saved-replica-0-rank-{rank}.json").read_text()) | ||
| 374 | + saved_cursor = json.loads( | ||
| 375 | + (init / "evidence" / f"initial-saved-replica-{replica}-rank-{rank}.json").read_text() | ||
| 376 | + ) | ||
| 377 | + expected = {**saved_model, "cursor": saved_cursor["cursor"], "rng": saved_cursor["rng"]} | ||
| 378 | + actual = json.loads( | ||
| 379 | + (target / "evidence" / f"initial-loaded-{phase}-replica-{replica}-rank-{rank}.json").read_text() | ||
| 380 | + ) | ||
| 381 | + if actual != expected: | ||
| 382 | + raise AssertionError( | ||
| 383 | + "Complete initial model/optimizer/scheduler/progress, own cursor or RNG differs: " | ||
| 384 | + f"{phase}, replica={replica}, rank={rank}" | ||
| 385 | + ) | ||
| 386 | + metrics = {} | ||
| 387 | + sources = list((target / "evidence").glob(f"source-{phase}-*.json")) | ||
| 388 | + expected_root = baseline_root if phase == "baseline_off" else Path(__file__).resolve().parents[2] | ||
| 389 | + feature = expected_root / "torchtitan_npu/extensions/torchtitan/experiments/torchft" | ||
| 390 | + expected_sources = {"trainer": feature / "trainer.py"} | ||
| 391 | + if phase != "baseline_off": | ||
| 392 | + expected_sources["checkpoint"] = feature / "last_words/checkpoint.py" | ||
| 393 | + if len(sources) != 4: | ||
| 394 | + raise AssertionError(f"Missing production source evidence: {phase}") | ||
| 395 | + for path in sources: | ||
| 396 | + sources_loaded = {name: Path(source).resolve() for name, source in json.loads(path.read_text()).items()} | ||
| 397 | + if phase == "baseline_off": | ||
| 398 | + checkpoint = sources_loaded.pop("checkpoint") | ||
| 399 | + if checkpoint.parts[-4:] != ("torchtitan", "experiments", "torchft", "checkpoint.py"): | ||
| 400 | + raise AssertionError(f"Unexpected baseline checkpointer: {checkpoint}") | ||
| 401 | + if sources_loaded != expected_sources: | ||
| 402 | + raise AssertionError(f"Wrong production source loaded in {phase}: {path.read_text()}") | ||
| 403 | + for path in (target / "evidence").glob(f"metrics-{phase}-*.json"): | ||
| 404 | + value = json.loads(path.read_text()) | ||
| 405 | + if not all(math.isfinite(item) for item in value.values()): | ||
| 406 | + raise AssertionError("Non-finite full-precision training metric") | ||
| 407 | + metrics[path.name.replace(phase, "phase")] = {key: item.hex() for key, item in value.items()} | ||
| 408 | + if len(metrics) != steps * 4: | ||
| 409 | + raise AssertionError(f"Missing full-precision per-rank metrics: {phase} has {len(metrics)} entries") | ||
| 410 | + values.append(metrics) | ||
| 411 | + if values[0] != values[1] or values[0] != values[2]: | ||
| 412 | + raise AssertionError("Original off, current off and current on loss/gradient norm are not bitwise equal") | ||
| 413 | + print("Verified full-precision loss/gradient norm equality from one initial checkpoint in all three phases") | ||
| 414 | + | ||
| 415 | + | ||
| 416 | +def verify_resume(folder, manifest_path, fault_folder, steps=6): | ||
| 417 | + manifest = json.loads(manifest_path.read_text()) | ||
| 418 | + saved_step = manifest["state"]["step"] | ||
| 419 | + writer = manifest["replica_id"] | ||
| 420 | + for replica in range(2): | ||
| 421 | + cursor_step = manifest["cursors"][str(replica)]["state"]["step"] | ||
| 422 | + for rank in range(2): | ||
| 423 | + suffix = f"replica-{replica}-rank-{rank}.json" | ||
| 424 | + loaded = json.loads((folder / "evidence" / f"loaded-resume-{suffix}").read_text()) | ||
| 425 | + model = json.loads( | ||
| 426 | + ( | ||
| 427 | + fault_folder / "evidence" / f"completed-step-{saved_step}-replica-{writer}-rank-{rank}.json" | ||
| 428 | + ).read_text() | ||
| 429 | + ) | ||
| 430 | + cursor = json.loads((fault_folder / "evidence" / f"completed-step-{cursor_step}-{suffix}").read_text()) | ||
| 431 | + if loaded["model"] != model["model"] or loaded["cursor"] != cursor["cursor"]: | ||
| 432 | + raise AssertionError( | ||
| 433 | + f"Resume did not restore complete model/optimizer/progress or own cursor: {suffix}" | ||
| 434 | + ) | ||
| 435 | + if loaded["rng"] != cursor["rng"] or loaded["live_rng"] != cursor["rng"]: | ||
| 436 | + raise AssertionError(f"Resume did not restore own RNG: {suffix}") | ||
| 437 | + if loaded["progress"] != manifest["state"] or loaded["next_step"] != saved_step + 1: | ||
| 438 | + raise AssertionError(f"Resume started at the wrong completed update: {suffix}") | ||
| 439 | + for step in range(saved_step + 1, steps + 1): | ||
| 440 | + value = json.loads((folder / "evidence" / f"metrics-resume-step-{step}-{suffix}").read_text()) | ||
| 441 | + if not all(math.isfinite(item) for item in value.values()): | ||
| 442 | + raise AssertionError(f"Non-finite resumed metric: step={step}, {suffix}") | ||
| 443 | + completed = json.loads((folder / "evidence" / f"completed-step-{steps}-{suffix}").read_text()) | ||
| 444 | + expected_updates = manifest["state"]["last_words_num_updates"] + steps - saved_step | ||
| 445 | + if ( | ||
| 446 | + completed["progress"]["step"] != steps | ||
| 447 | + or completed["progress"]["last_words_num_updates"] != expected_updates | ||
| 448 | + ): | ||
| 449 | + raise AssertionError(f"Resume did not commit every requested update: {suffix}") | ||
| 450 | + (folder / "resume-verified.json").write_text( | ||
| 451 | + json.dumps(dict(passed=True, checkpoint=str(manifest_path), saved_step=saved_step, final_step=steps, ranks=4)) | ||
| 452 | + ) | ||
| 453 | + | ||
| 454 | + | ||
| 455 | +def main(): | ||
| 456 | + def interrupted(signum, frame): | ||
| 457 | + raise SystemExit(128 + signum) | ||
| 458 | + | ||
| 459 | + signal.signal(signal.SIGTERM, interrupted) | ||
| 460 | + parser = argparse.ArgumentParser() | ||
| 461 | + parser.add_argument("--output-dir", required=True) | ||
| 462 | + parser.add_argument("--scenario", choices=SCENARIOS, default="emergency_save") | ||
| 463 | + args = parser.parse_args() | ||
| 464 | + folder = Path(args.output_dir).resolve() | ||
| 465 | + folder.mkdir(parents=True, exist_ok=False) | ||
| 466 | + devices = os.environ.get("ASCEND_RT_VISIBLE_DEVICES", "0,1,2,3").split(",") | ||
| 467 | + if len(devices) != 4: | ||
| 468 | + raise ValueError("The last-words integration case requires exactly four assigned NPUs") | ||
| 469 | + if args.scenario == "numerical": | ||
| 470 | + numerical_case(folder, devices) | ||
| 471 | + return | ||
| 472 | + manifest = run_phase(folder, phase="fault", scenario=args.scenario, devices=devices) | ||
| 473 | + resumed = folder / "resume" | ||
| 474 | + run_phase(resumed, phase="resume", scenario=args.scenario, devices=devices, resume_path=manifest.parent) | ||
| 475 | + verify_resume(resumed, manifest, folder) | ||
| 476 | + print( | ||
| 477 | + f"Verified {args.scenario}: one 2x2 NPU candidate at {manifest}, externally loaded and trained through step 6" | ||
| 478 | + ) | ||
| 479 | + | ||
| 480 | + | ||
| 481 | +if __name__ == "__main__": | ||
| 482 | + main() | ||
| @@ -0,0 +1,77 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in the LICENSE file. | ||
| 3 | + | ||
| 4 | +"""Four-NPU TorchFT recipe used by all arms, including the pre-feature baseline.""" | ||
| 5 | + | ||
| 6 | +import json | ||
| 7 | +import os | ||
| 8 | + | ||
| 9 | +from torchtitan.config.override import parse_cli_imports | ||
| 10 | +from torchtitan.config.parallelism import ParallelismConfig | ||
| 11 | + | ||
| 12 | +from torchtitan_npu.config import CompileConfig, ModelCompileConfig | ||
| 13 | +from torchtitan_npu_recipes.tests.models.deepseek_v4 import deepseek_v4_debugmodel | ||
| 14 | +from torchtitan_npu_recipes.torchft.deepseek_v4 import _torchft_flash_config | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def deepseek_v4_small_torchft(): | ||
| 18 | + seq_len = int(os.environ["LAST_WORDS_TEST_SEQ_LEN"]) | ||
| 19 | + base = deepseek_v4_debugmodel( | ||
| 20 | + num_mtp_layers=1, | ||
| 21 | + seq_len=seq_len, | ||
| 22 | + parallelism=ParallelismConfig( | ||
| 23 | + data_parallel_shard_degree=2, | ||
| 24 | + expert_parallel_degree=2, | ||
| 25 | + fsdp_reshard_after_forward="always", | ||
| 26 | + ), | ||
| 27 | + ) | ||
| 28 | + config = _torchft_flash_config(base, expert_parallel_degree=2, data_parallel_shard_degree=2, global_batch_size=8) | ||
| 29 | + config.training.num_tokens_per_microbatch_per_dp_rank = seq_len | ||
| 30 | + config.training.steps = int(os.environ["LAST_WORDS_TEST_STEPS"]) | ||
| 31 | + config.checkpointer.interval = int(os.environ["LAST_WORDS_TEST_INTERVAL"]) | ||
| 32 | + config.checkpointer.last_save_model_only = False | ||
| 33 | + config.checkpointer.keep_latest_k = 2 | ||
| 34 | + config.metrics.log_freq = 1 | ||
| 35 | + config.debug.deterministic = os.environ["LAST_WORDS_TEST_SCENARIO"] == "numerical" | ||
| 36 | + config.debug.seed = 42 if config.debug.deterministic else 1234 | ||
| 37 | + if overrides := os.environ.get("LAST_WORDS_TEST_OVERRIDES"): | ||
| 38 | + config.override.imports = parse_cli_imports(json.loads(overrides)) | ||
| 39 | + ft = config.fault_tolerance | ||
| 40 | + ft.process_group_timeout_ms = 60000 | ||
| 41 | + if backend := os.environ.get("LAST_WORDS_COMPILE_BACKEND"): | ||
| 42 | + components = os.environ.get("LAST_WORDS_COMPILE_COMPONENTS", "model") | ||
| 43 | + if components not in ("model", "model,loss"): | ||
| 44 | + raise ValueError("Compile validation supports model or model,loss") | ||
| 45 | + config.compile = CompileConfig( | ||
| 46 | + components=["loss"] if components == "model,loss" else [], model=ModelCompileConfig(backend=backend) | ||
| 47 | + ) | ||
| 48 | + ft.process_group_timeout_ms = 300000 | ||
| 49 | + ft.quorum_warmup_timeout_ms = 600000 | ||
| 50 | + ft.quorum_timeout_seconds = 300 | ||
| 51 | + config.comm.init_timeout_seconds = 900 | ||
| 52 | + config.comm.train_timeout_seconds = 600 | ||
| 53 | + if os.environ["LAST_WORDS_TEST_PHASE"] in ("current_on", "fault", "resume"): | ||
| 54 | + ft.enable_elastic = False | ||
| 55 | + ft.last_words.enable = True | ||
| 56 | + ft.last_words.run_id = os.environ["LAST_WORDS_TEST_RUN_ID"] | ||
| 57 | + ft.last_words.heartbeat_timeout_seconds = 30 | ||
| 58 | + ft.last_words.timeout_seconds = 180 | ||
| 59 | + if resume_path := os.environ.get("LAST_WORDS_TEST_RESUME_PATH"): | ||
| 60 | + ft.last_words.resume_path = resume_path | ||
| 61 | + return config | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def describe_model(config): | ||
| 65 | + model = config.model | ||
| 66 | + return { | ||
| 67 | + "dim": model.dim, | ||
| 68 | + "vocab_size": model.vocab_size, | ||
| 69 | + "n_layers": len(model.layers), | ||
| 70 | + "mtp_layers": len(model.mtp_layers), | ||
| 71 | + "compress_ratios": list(model.compress_ratios), | ||
| 72 | + "expert_parallel_degree": config.parallelism.expert_parallel_degree, | ||
| 73 | + "data_parallel_shard_degree": config.parallelism.data_parallel_shard_degree, | ||
| 74 | + "tokens_per_step": config.training.num_tokens_per_train_step, | ||
| 75 | + "tokens_per_microbatch": config.training.num_tokens_per_microbatch_per_dp_rank, | ||
| 76 | + "seq_len": config.training.max_context_length, | ||
| 77 | + } | ||
| @@ -0,0 +1,271 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +"""Inject software faults in actual TorchFT training and record full state.""" | ||
| 5 | + | ||
| 6 | +import faulthandler | ||
| 7 | +import hashlib | ||
| 8 | +import importlib.metadata | ||
| 9 | +import json | ||
| 10 | +import os | ||
| 11 | +import runpy | ||
| 12 | +import sys | ||
| 13 | +import time | ||
| 14 | +from pathlib import Path | ||
| 15 | + | ||
| 16 | +import torch | ||
| 17 | +import torch.distributed as dist | ||
| 18 | +import torch.distributed.checkpoint as dcp | ||
| 19 | +import torch_npu # noqa: F401 # Register the accelerator before TorchTitan chooses its device module. | ||
| 20 | +from torch.distributed.tensor import DTensor | ||
| 21 | +from torchtitan.components.checkpointer import LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE | ||
| 22 | +from torchtitan.components.optim import OptimizersContainer | ||
| 23 | + | ||
| 24 | +# The baseline arm imports production code from an older checkout. Load this | ||
| 25 | +# harness's state implementation explicitly without changing those imports. | ||
| 26 | +_rng = runpy.run_path( | ||
| 27 | + str( | ||
| 28 | + Path(__file__).resolve().parents[2] | ||
| 29 | + / "torchtitan_npu/extensions/torchtitan/experiments/torchft/last_words/rng.py" | ||
| 30 | + ) | ||
| 31 | +) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def full_states(trainer): | ||
| 35 | + engine = trainer.engine | ||
| 36 | + checkpointer = engine.checkpointer | ||
| 37 | + states = {key: checkpointer.states[key] for key in (MODEL, LR_SCHEDULER, TRAIN_STATE)} | ||
| 38 | + # Read live optimizer scalars as well as sharded tensors in every arm. | ||
| 39 | + states[OPTIMIZER] = OptimizersContainer.state_dict(engine.optim.optimizers) | ||
| 40 | + if "ema" in checkpointer.states: | ||
| 41 | + states["ema"] = checkpointer.states["ema"] | ||
| 42 | + return checkpointer._flattened_model_states_sd(states) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def numerical_initial_state(trainer, *, save): | ||
| 46 | + engine = trainer.engine | ||
| 47 | + checkpointer = engine.checkpointer | ||
| 48 | + replica = engine.ft_manager.replica_id | ||
| 49 | + rank = dist.get_rank() | ||
| 50 | + root = Path(os.environ["LAST_WORDS_TEST_INITIAL_ROOT"]) | ||
| 51 | + states = full_states(trainer) | ||
| 52 | + # Match the on/off schemas without requiring a pre-feature trainer to export | ||
| 53 | + # the new counter. Use actual engine and TorchFT progress for all other fields. | ||
| 54 | + progress = {**states[TRAIN_STATE].state_dict(), "last_words_num_updates": 0} | ||
| 55 | + if progress["step"] != 0: | ||
| 56 | + raise AssertionError("The shared numerical initial state must precede training") | ||
| 57 | + states[TRAIN_STATE] = progress | ||
| 58 | + manager = engine.ft_manager.manager | ||
| 59 | + states["torchft"] = manager.state_dict() | ||
| 60 | + if save and replica == 0: | ||
| 61 | + dcp.save(states, checkpoint_id=root / "model", process_group=checkpointer.pg) | ||
| 62 | + if not save: | ||
| 63 | + dcp.load(states, checkpoint_id=root / "model", process_group=checkpointer.pg) | ||
| 64 | + checkpointer.states[MODEL].load_state_dict(states) | ||
| 65 | + engine.optim.optimizers.load_state_dict(states[OPTIMIZER]) | ||
| 66 | + engine.load_state_dict(states[TRAIN_STATE]) | ||
| 67 | + manager.load_state_dict(states["torchft"]) | ||
| 68 | + | ||
| 69 | + rng = _rng["RNGCheckpointState"](engine.device, rank) | ||
| 70 | + rng.capture() | ||
| 71 | + cursors = {"dataloader": trainer.dataloader, _rng["RNG_STATE"]: rng} | ||
| 72 | + cursor_path = root / f"replica-{replica}" | ||
| 73 | + if save: | ||
| 74 | + dcp.save(cursors, checkpoint_id=cursor_path, process_group=checkpointer.pg) | ||
| 75 | + else: | ||
| 76 | + dcp.load(cursors, checkpoint_id=cursor_path, process_group=checkpointer.pg) | ||
| 77 | + rng.restore() | ||
| 78 | + rng.capture() | ||
| 79 | + return rng | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +def digest(value): | ||
| 83 | + hasher = hashlib.sha256() | ||
| 84 | + | ||
| 85 | + def visit(item): | ||
| 86 | + if hasattr(item, "state_dict"): | ||
| 87 | + visit(item.state_dict()) | ||
| 88 | + elif isinstance(item, DTensor): | ||
| 89 | + visit(item.to_local()) | ||
| 90 | + elif isinstance(item, torch.Tensor): | ||
| 91 | + tensor = item.detach().cpu().contiguous() | ||
| 92 | + hasher.update(str((tensor.shape, tensor.dtype)).encode()) | ||
| 93 | + hasher.update(tensor.reshape(-1).view(torch.uint8).numpy().tobytes()) | ||
| 94 | + elif isinstance(item, dict): | ||
| 95 | + for key in sorted(item, key=str): | ||
| 96 | + hasher.update(str(key).encode()) | ||
| 97 | + visit(item[key]) | ||
| 98 | + elif isinstance(item, (list, tuple)): | ||
| 99 | + for child in item: | ||
| 100 | + visit(child) | ||
| 101 | + elif isinstance(item, bytes): | ||
| 102 | + hasher.update(item) | ||
| 103 | + else: | ||
| 104 | + hasher.update(str(item).encode()) | ||
| 105 | + | ||
| 106 | + visit(value) | ||
| 107 | + return hasher.hexdigest() | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +def record(trainer, name, value): | ||
| 111 | + replica = trainer.engine.ft_manager.replica_id | ||
| 112 | + rank = torch.distributed.get_rank() | ||
| 113 | + folder = Path(os.environ["LAST_WORDS_TEST_EVIDENCE"]) | ||
| 114 | + folder.mkdir(parents=True, exist_ok=True) | ||
| 115 | + path = folder / f"{name}-replica-{replica}-rank-{rank}.json" | ||
| 116 | + temporary = path.with_suffix(".tmp") | ||
| 117 | + temporary.write_text(json.dumps(value, sort_keys=True, allow_nan=False)) | ||
| 118 | + temporary.replace(path) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def initial_state_digest(trainer, rng): | ||
| 122 | + states = full_states(trainer) | ||
| 123 | + progress = dict(states[TRAIN_STATE].state_dict()) | ||
| 124 | + # The enabled trainer adds this counter to an otherwise identical step-zero state. | ||
| 125 | + progress.pop("last_words_num_updates", None) | ||
| 126 | + states[TRAIN_STATE] = progress | ||
| 127 | + states.pop("torchft", None) | ||
| 128 | + return { | ||
| 129 | + "model": digest(states), | ||
| 130 | + "cursor": digest(trainer.dataloader.state_dict()), | ||
| 131 | + "rng": digest(rng), | ||
| 132 | + "torchft": trainer.engine.ft_manager.manager.state_dict(), | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + | ||
| 136 | +def install_metrics_hook(trainer, phase): | ||
| 137 | + metrics_log = trainer.metrics_processor.log | ||
| 138 | + | ||
| 139 | + def metrics(step, avg_loss, max_loss, grad_norm, **kwargs): | ||
| 140 | + record(trainer, f"metrics-{phase}-step-{step}", {"loss": float(avg_loss), "grad_norm": float(grad_norm)}) | ||
| 141 | + return metrics_log(step, avg_loss, max_loss, grad_norm, **kwargs) | ||
| 142 | + | ||
| 143 | + trainer.metrics_processor.log = metrics | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +def injected_step(trainer, iterator): | ||
| 147 | + phase = os.environ["LAST_WORDS_TEST_PHASE"] | ||
| 148 | + scenario = os.environ["LAST_WORDS_TEST_SCENARIO"] | ||
| 149 | + fault_step = int(os.environ.get("LAST_WORDS_TEST_FAULT_STEP", "3")) | ||
| 150 | + engine = trainer.engine | ||
| 151 | + checkpointer = engine.checkpointer | ||
| 152 | + step = engine.num_completed_steps + 1 | ||
| 153 | + if not hasattr(trainer, "_last_words_test_installed"): | ||
| 154 | + import torchft._torchft as torchft_native | ||
| 155 | + from last_words_small_config import describe_model | ||
| 156 | + | ||
| 157 | + trainer._last_words_test_installed = True | ||
| 158 | + version = importlib.metadata.version("torchft") | ||
| 159 | + if version != "0.2.0" or hasattr(torchft_native, "LastWordsClient"): | ||
| 160 | + raise AssertionError("Service acceptance must use unmodified upstream TorchFT 0.2.0") | ||
| 161 | + record( | ||
| 162 | + trainer, | ||
| 163 | + f"source-{phase}", | ||
| 164 | + { | ||
| 165 | + "trainer": sys.modules[type(trainer).__module__].__file__, | ||
| 166 | + "checkpoint": sys.modules[type(checkpointer).__module__].__file__, | ||
| 167 | + }, | ||
| 168 | + ) | ||
| 169 | + config = trainer.config | ||
| 170 | + compile_model = getattr(config.compile, "model", None) | ||
| 171 | + record( | ||
| 172 | + trainer, | ||
| 173 | + f"execution-controls-{phase}", | ||
| 174 | + { | ||
| 175 | + "deterministic_algorithms": torch.are_deterministic_algorithms_enabled(), | ||
| 176 | + "deterministic_config": config.debug.deterministic, | ||
| 177 | + "seed_config": config.debug.seed, | ||
| 178 | + "compile_backend": compile_model.backend if compile_model else None, | ||
| 179 | + "checkpoint_interval": config.checkpointer.interval, | ||
| 180 | + "checkpoint_keep_latest_k": config.checkpointer.keep_latest_k, | ||
| 181 | + "model_dimensions": describe_model(config), | ||
| 182 | + "torchft_version": version, | ||
| 183 | + }, | ||
| 184 | + ) | ||
| 185 | + if phase == "resume": | ||
| 186 | + live_rng = _rng["RNGCheckpointState"](engine.device, dist.get_rank()) | ||
| 187 | + live_rng.capture() | ||
| 188 | + record( | ||
| 189 | + trainer, | ||
| 190 | + "loaded-resume", | ||
| 191 | + { | ||
| 192 | + "model": digest(checkpointer._full_states()), | ||
| 193 | + "cursor": digest(trainer.dataloader.state_dict()), | ||
| 194 | + "rng": digest(trainer._last_words_rng_state), | ||
| 195 | + "live_rng": digest(live_rng), | ||
| 196 | + "progress": engine.state_dict(), | ||
| 197 | + "next_step": step, | ||
| 198 | + }, | ||
| 199 | + ) | ||
| 200 | + if scenario == "numerical": | ||
| 201 | + saving = phase == "init" | ||
| 202 | + rng = numerical_initial_state(trainer, save=saving) | ||
| 203 | + name = "initial-saved" if saving else f"initial-loaded-{phase}" | ||
| 204 | + record(trainer, name, initial_state_digest(trainer, rng)) | ||
| 205 | + if saving: | ||
| 206 | + trainer.close() | ||
| 207 | + dist.destroy_process_group() | ||
| 208 | + raise SystemExit(0) | ||
| 209 | + install_metrics_hook(trainer, phase) | ||
| 210 | + | ||
| 211 | + if phase == "fault" and step == fault_step: | ||
| 212 | + target = engine.ft_manager.replica_id == 1 | ||
| 213 | + rank = torch.distributed.get_rank() | ||
| 214 | + if scenario == "emergency_save": | ||
| 215 | + checkpointer.maybe_wait_for_saving() | ||
| 216 | + evidence = Path(os.environ["LAST_WORDS_TEST_EVIDENCE"]) | ||
| 217 | + record(trainer, "boundary", {"step": step - 1}) | ||
| 218 | + if target and rank == 0: | ||
| 219 | + deadline = time.monotonic() + 120 | ||
| 220 | + while len(list(evidence.glob("boundary-*.json"))) != 4: | ||
| 221 | + if time.monotonic() > deadline: | ||
| 222 | + raise TimeoutError("Ranks did not reach injection boundary") | ||
| 223 | + time.sleep(0.05) | ||
| 224 | + record(trainer, "injected", {"point": "boundary_process_exit", "step": step}) | ||
| 225 | + os._exit(77) | ||
| 226 | + while not trainer.last_words.requested: | ||
| 227 | + time.sleep(0.05) | ||
| 228 | + | ||
| 229 | + def observed_data(source): | ||
| 230 | + for microbatch, batch in enumerate(source): | ||
| 231 | + # Hash the tensors actually passed into the production trainer, | ||
| 232 | + # including both MTP loss counts and routing normalization counts. | ||
| 233 | + value = digest((batch.as_input_dict(), batch.loss_token_counts, batch.routing_token_counts)) | ||
| 234 | + record(trainer, f"input-step-{step}-microbatch-{microbatch}", {"batch": value}) | ||
| 235 | + yield batch | ||
| 236 | + | ||
| 237 | + result = original(trainer, observed_data(iterator) if scenario == "numerical" else iterator) | ||
| 238 | + if phase in ("fault", "resume") and engine.num_completed_steps == step: | ||
| 239 | + record( | ||
| 240 | + trainer, | ||
| 241 | + f"completed-step-{step}", | ||
| 242 | + { | ||
| 243 | + "model": digest(checkpointer._full_states()), | ||
| 244 | + "cursor": digest(trainer.dataloader.state_dict()), | ||
| 245 | + "rng": digest(trainer._last_words_rng_state), | ||
| 246 | + "progress": engine.state_dict(), | ||
| 247 | + }, | ||
| 248 | + ) | ||
| 249 | + return result | ||
| 250 | + | ||
| 251 | + | ||
| 252 | +def run_training(): | ||
| 253 | + global original | ||
| 254 | + from torchtitan_npu.extensions.torchtitan.experiments.torchft.trainer import FaultTolerantTrainerEx | ||
| 255 | + from torchtitan_npu.train import main | ||
| 256 | + | ||
| 257 | + original = FaultTolerantTrainerEx.train_step | ||
| 258 | + FaultTolerantTrainerEx.train_step = injected_step | ||
| 259 | + diagnostics = os.environ.get("LAST_WORDS_TEST_FAULTHANDLER") == "1" | ||
| 260 | + if diagnostics: | ||
| 261 | + faulthandler.dump_traceback_later(90, repeat=True) | ||
| 262 | + try: | ||
| 263 | + main() | ||
| 264 | + finally: | ||
| 265 | + FaultTolerantTrainerEx.train_step = original | ||
| 266 | + if diagnostics: | ||
| 267 | + faulthandler.cancel_dump_traceback_later() | ||
| 268 | + | ||
| 269 | + | ||
| 270 | +if __name__ == "__main__": | ||
| 271 | + run_training() | ||
| @@ -0,0 +1,18 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 3 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 4 | +set -euo pipefail | ||
| 5 | +if [[ ${1:-} == --compile-worker ]]; then | ||
| 6 | + shift | ||
| 7 | + # ascendc reads these paths on import. torchrun supplies LOCAL_RANK to each worker. | ||
| 8 | + for key in TORCHINDUCTOR_CACHE_DIR TORCHINDUCTOR_NPU_EXT_CACHE_DIR; do | ||
| 9 | + if [[ ${!key:-} != /* ]]; then | ||
| 10 | + echo "Small recovery requires an absolute cache root for $key" >&2 | ||
| 11 | + exit 1 | ||
| 12 | + fi | ||
| 13 | + export "${key}=${!key}/replica-${LAST_WORDS_TEST_REPLICA}-rank-${LOCAL_RANK}" | ||
| 14 | + done | ||
| 15 | + exec "$@" | ||
| 16 | +fi | ||
| 17 | +cd "$(dirname "${BASH_SOURCE[0]}")/../.." | ||
| 18 | +exec "${PYTHON_BIN:-python3}" -m tests.integration_tests.last_words "$@" | ||
| @@ -79,8 +79,15 @@ def build_engram_hf_test_list(): | |||
| 79 | return build() | 79 | return build() |
| 80 | 80 | ||
| 81 | 81 | ||
| 82 | -# torchtitan-npu override: register the DeepSeek-V4 and V4.1 NPU suites. | 82 | +def build_last_words_test_list(): |
| 83 | + from tests.integration_tests.last_words import build_last_words_test_list as build | ||
| 84 | + | ||
| 85 | + return build() | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +# torchtitan-npu override: register the NPU suites. | ||
| 83 | _TEST_SUITES_FUNCTION = { | 89 | _TEST_SUITES_FUNCTION = { |
| 90 | + "torchft_last_words": build_last_words_test_list, | ||
| 84 | "models": build_models_test_list, | 91 | "models": build_models_test_list, |
| 85 | "deepseek_cp": build_deepseek_cp_test_list, | 92 | "deepseek_cp": build_deepseek_cp_test_list, |
| 86 | "deepseek_v4": build_deepseek_v4_test_list, | 93 | "deepseek_v4": build_deepseek_v4_test_list, |
| @@ -642,6 +649,14 @@ def _filter_tests( | |||
| 642 | if args.ngpu < test_flavor.ngpu: | 649 | if args.ngpu < test_flavor.ngpu: |
| 643 | skipped_ngpu.append(test_flavor) | 650 | skipped_ngpu.append(test_flavor) |
| 644 | continue | 651 | continue |
| 652 | + env = {**os.environ, **(test_flavor.env_vars or {})} | ||
| 653 | + missing = [name for name in test_flavor.required_env if not env.get(name)] | ||
| 654 | + if missing: | ||
| 655 | + message = f"{test_flavor.test_name} requires {', '.join(missing)}" | ||
| 656 | + if args.test_name != "all": | ||
| 657 | + raise ValueError(message) | ||
| 658 | + log_print(f"Skipping {message}") | ||
| 659 | + continue | ||
| 645 | runnable.append(test_flavor) | 660 | runnable.append(test_flavor) |
| 646 | return runnable, skipped_ngpu | 661 | return runnable, skipped_ngpu |
| 647 | 662 | ||
| @@ -6,5 +6,10 @@ | |||
| 6 | """Collect TorchFT tests only when their optional distribution is installed.""" | 6 | """Collect TorchFT tests only when their optional distribution is installed.""" |
| 7 | 7 | ||
| 8 | from importlib.util import find_spec | 8 | from importlib.util import find_spec |
| 9 | +from pathlib import Path | ||
| 9 | 10 | ||
| 10 | -collect_ignore_glob = ["test_*.py"] if find_spec("torchft") is None else [] | 11 | +collect_ignore = [] |
| 12 | +if find_spec("torchft") is None: | ||
| 13 | + # The standalone service runs without the optional training runtime. | ||
| 14 | + test_files = Path(__file__).parent.glob("test_*.py") | ||
| 15 | + collect_ignore = [path.name for path in test_files if path.stem != "test_last_words_service"] | ||
| @@ -0,0 +1,35 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +import runpy | ||
| 5 | +import threading | ||
| 6 | +from contextlib import contextmanager | ||
| 7 | +from pathlib import Path | ||
| 8 | + | ||
| 9 | +# Start the standalone service without importing the optional training runtime. | ||
| 10 | +FEATURE = Path(__file__).resolve().parents[6] / "torchtitan_npu/extensions/torchtitan/experiments/torchft/last_words" | ||
| 11 | +SERVICE = runpy.run_path(str(FEATURE / "service.py")) | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +@contextmanager | ||
| 15 | +def service_session(root, run_id, *, num_replicas=2, world_size=2): | ||
| 16 | + directory = root / f"session-{run_id}" | ||
| 17 | + with SERVICE["ServiceServer"](("127.0.0.1", 0)) as server: | ||
| 18 | + SERVICE["prepare_session"]( | ||
| 19 | + server, | ||
| 20 | + directory, | ||
| 21 | + address=f"http://127.0.0.1:{server.server_port}", | ||
| 22 | + run_id=run_id, | ||
| 23 | + num_replicas=num_replicas, | ||
| 24 | + world_size=world_size, | ||
| 25 | + heartbeat_seconds=30, | ||
| 26 | + startup_seconds=60, | ||
| 27 | + timeout_seconds=100, | ||
| 28 | + ) | ||
| 29 | + thread = threading.Thread(target=server.serve_forever) | ||
| 30 | + thread.start() | ||
| 31 | + try: | ||
| 32 | + yield directory | ||
| 33 | + finally: | ||
| 34 | + server.shutdown() | ||
| 35 | + thread.join() | ||
| @@ -106,13 +106,12 @@ def test_completed_rejected_step_clears_transient_auxiliary_state(monkeypatch, c | |||
| 106 | max_consecutive_recoveries=3, | 106 | max_consecutive_recoveries=3, |
| 107 | reset_auxiliary_state=auxiliary_reset, | 107 | reset_auxiliary_state=auxiliary_reset, |
| 108 | ) | 108 | ) |
| 109 | - trainer = SimpleNamespace( | 109 | + trainer = FaultTolerantTrainerEx.__new__(FaultTolerantTrainerEx) |
| 110 | - engine=engine, | 110 | + trainer.engine = engine |
| 111 | - recovery=recovery, | 111 | + trainer.recovery = recovery |
| 112 | - metrics_processor=Mock(should_log=Mock(return_value=True)), | 112 | + trainer.last_words = None |
| 113 | - gradient_accumulation_steps=1, | 113 | + trainer.metrics_processor = Mock(should_log=Mock(return_value=True)) |
| 114 | - num_pp_microbatches=1, | 114 | + trainer.gradient_accumulation_steps = trainer.num_pp_microbatches = 1 |
| 115 | - ) | ||
| 116 | 115 | ||
| 117 | def optimizer_attempt(*args, **kwargs): | 116 | def optimizer_attempt(*args, **kwargs): |
| 118 | engine.optim.lr_schedulers.step() | 117 | engine.optim.lr_schedulers.step() |
| @@ -120,7 +119,7 @@ def test_completed_rejected_step_clears_transient_auxiliary_state(monkeypatch, c | |||
| 120 | 119 | ||
| 121 | engine.optim.step.side_effect = optimizer_attempt | 120 | engine.optim.step.side_effect = optimizer_attempt |
| 122 | recovery.run_step( | 121 | recovery.run_step( |
| 123 | - lambda iterator: FaultTolerantTrainerEx._train_step(trainer, iterator), | 122 | + trainer._train_step, |
| 124 | iter([SimpleNamespace(loss_token_counts=torch.tensor(1), routing_token_counts=torch.tensor(1))]), | 123 | iter([SimpleNamespace(loss_token_counts=torch.tensor(1), routing_token_counts=torch.tensor(1))]), |
| 125 | ) | 124 | ) |
| 126 | assert engine.num_completed_steps == 15 | 125 | assert engine.num_completed_steps == 15 |
| @@ -139,7 +138,7 @@ def test_completed_rejected_step_clears_transient_auxiliary_state(monkeypatch, c | |||
| 139 | trainer.metrics_processor.log.side_effect = error | 138 | trainer.metrics_processor.log.side_effect = error |
| 140 | with pytest.raises(RuntimeError, match="finalized step requires restarting") as raised: | 139 | with pytest.raises(RuntimeError, match="finalized step requires restarting") as raised: |
| 141 | recovery.run_step( | 140 | recovery.run_step( |
| 142 | - lambda iterator: FaultTolerantTrainerEx._train_step(trainer, iterator), | 141 | + trainer._train_step, |
| 143 | iter([SimpleNamespace(loss_token_counts=torch.tensor(1), routing_token_counts=torch.tensor(1))]), | 142 | iter([SimpleNamespace(loss_token_counts=torch.tensor(1), routing_token_counts=torch.tensor(1))]), |
| 144 | ) | 143 | ) |
| 145 | assert raised.value.__cause__ is error | 144 | assert raised.value.__cause__ is error |
| @@ -0,0 +1,154 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +from contextlib import closing | ||
| 5 | +from pathlib import Path | ||
| 6 | +from types import SimpleNamespace | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | +import torch.distributed.checkpoint as dcp | ||
| 11 | +from torchtitan.components.checkpointer import DATALOADER, LR_SCHEDULER, TRAIN_STATE | ||
| 12 | +from torchtitan.experiments.torchft.trainer import FaultTolerantTrainer | ||
| 13 | + | ||
| 14 | +from tests.unit_tests.extensions.torchtitan.experiments.torchft.service_helpers import service_session | ||
| 15 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.last_words.checkpoint import LastWordsCheckpointManager | ||
| 16 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.last_words.rng import RNG_STATE, RNGCheckpointState | ||
| 17 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.last_words.worker import ( | ||
| 18 | + LastWordsConfig, | ||
| 19 | + LastWordsWorkerController, | ||
| 20 | + atomic_json, | ||
| 21 | + read_json, | ||
| 22 | +) | ||
| 23 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.trainer import FaultTolerantTrainerEx | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def test_normal_training_completes_after_checkpoint_drain(monkeypatch): | ||
| 27 | + events = [] | ||
| 28 | + monkeypatch.setattr(FaultTolerantTrainer, "train", lambda self: events.append("train")) | ||
| 29 | + trainer = FaultTolerantTrainerEx.__new__(FaultTolerantTrainerEx) | ||
| 30 | + trainer.engine = SimpleNamespace(checkpointer=SimpleNamespace(finish_pending_save=lambda: events.append("drain"))) | ||
| 31 | + trainer.last_words = SimpleNamespace(finish_training=lambda: events.append("finished")) | ||
| 32 | + | ||
| 33 | + trainer.train() | ||
| 34 | + | ||
| 35 | + assert events == ["train", "drain", "finished"] | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +class DictState: | ||
| 39 | + def __init__(self, value): | ||
| 40 | + self.value = dict(value) | ||
| 41 | + | ||
| 42 | + def state_dict(self): | ||
| 43 | + return self.value | ||
| 44 | + | ||
| 45 | + def load_state_dict(self, value): | ||
| 46 | + self.value = dict(value) | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +class CheckpointAdamW(torch.optim.AdamW): | ||
| 50 | + def _refresh_cached_state_dict(self): | ||
| 51 | + # Plain AdamW exposes live state; the TorchFT container refreshes a cache here. | ||
| 52 | + pass | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +@pytest.fixture | ||
| 56 | +def saved_checkpoint(tmp_path, monkeypatch): | ||
| 57 | + model = torch.nn.Module() | ||
| 58 | + model.register_parameter("weight", torch.nn.Parameter(torch.tensor([1.0, -4.0]))) | ||
| 59 | + model._register_state_dict_hook(lambda _, state, *_args: {key: value.clone() for key, value in state.items()}) | ||
| 60 | + optimizer = CheckpointAdamW([model.weight], lr=0.02, foreach=False) | ||
| 61 | + model.weight.grad = torch.tensor([2.0, -3.0]) | ||
| 62 | + optimizer.step() | ||
| 63 | + state = {"step": 5, "ntokens_seen": 160, "last_words_num_updates": 4} | ||
| 64 | + cursor = DictState({"position": torch.tensor(20)}) | ||
| 65 | + | ||
| 66 | + manager = LastWordsCheckpointManager( | ||
| 67 | + LastWordsCheckpointManager.Config(folder=str(tmp_path), interval=1, keep_latest_k=0), | ||
| 68 | + model_parts=[model], | ||
| 69 | + optimizers=optimizer, | ||
| 70 | + lr_schedulers=DictState({"last_epoch": 4}), | ||
| 71 | + ema=None, | ||
| 72 | + extra_states={TRAIN_STATE: DictState(state)}, | ||
| 73 | + sd_adapter=None, | ||
| 74 | + ) | ||
| 75 | + manager.last_words_signature, manager.last_words_state = "a" * 64, state | ||
| 76 | + rng = RNGCheckpointState(torch.device("cpu"), 0) | ||
| 77 | + rng.capture() | ||
| 78 | + manager.rng_state = rng | ||
| 79 | + manager.ft_states = {DATALOADER: cursor, RNG_STATE: rng} | ||
| 80 | + with service_session(tmp_path, "launch-1", num_replicas=1, world_size=1) as directory: | ||
| 81 | + monkeypatch.setenv("LAST_WORDS_SESSION_FILE", str(directory / "replica-0.json")) | ||
| 82 | + config = LastWordsConfig(enable=True, run_id="launch-1", heartbeat_timeout_seconds=30, timeout_seconds=100) | ||
| 83 | + with closing( | ||
| 84 | + LastWordsWorkerController(config, folder=str(tmp_path), replica_id=0, num_replicas=1, rank=0, world_size=1) | ||
| 85 | + ) as control: | ||
| 86 | + manager.last_words = control | ||
| 87 | + path = tmp_path / "ft-replicat-0" / config.run_id / "step-3" | ||
| 88 | + dcp.save(manager.ft_states, checkpoint_id=path) | ||
| 89 | + atomic_json( | ||
| 90 | + path / "last_words_cursor.json", manager._cursor_record(dict(state, step=3, last_words_num_updates=2)) | ||
| 91 | + ) | ||
| 92 | + control.request_terminal_stop("save at the completed boundary") | ||
| 93 | + target = manager.save_last_words(state) | ||
| 94 | + assert read_json(target / "service-result.json")["success"] is True | ||
| 95 | + try: | ||
| 96 | + yield manager, target, model, optimizer, cursor, state | ||
| 97 | + finally: | ||
| 98 | + rng.restore() | ||
| 99 | + manager.close() | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +@pytest.mark.parametrize("legacy", [False, True], ids=["v2-automatic", "v1-explicit"]) | ||
| 103 | +def test_emergency_checkpoint_restores_complete_training_state(saved_checkpoint, legacy): | ||
| 104 | + manager, target, model, optimizer, cursor, state = saved_checkpoint | ||
| 105 | + expected_weight = model.weight.detach().clone() | ||
| 106 | + expected_rng = torch.get_rng_state().clone() | ||
| 107 | + if legacy: | ||
| 108 | + atomic_json(target / "manifest.json", dict(read_json(target / "manifest.json"), format_version=1)) | ||
| 109 | + (target / "service-result.json").unlink() | ||
| 110 | + manager.last_words.config.resume_path = str(target) | ||
| 111 | + manager.last_words.config.run_id = "restart" | ||
| 112 | + with torch.no_grad(): | ||
| 113 | + model.weight.fill_(25) | ||
| 114 | + optimizer.state[model.weight]["exp_avg"].fill_(100) | ||
| 115 | + manager.states[LR_SCHEDULER].value["last_epoch"] = 0 | ||
| 116 | + manager.states[TRAIN_STATE].value["step"] = 0 | ||
| 117 | + cursor.value["position"].fill_(99) | ||
| 118 | + torch.rand(1) | ||
| 119 | + | ||
| 120 | + assert manager.load() | ||
| 121 | + | ||
| 122 | + assert torch.equal(model.weight, expected_weight) | ||
| 123 | + torch.testing.assert_close(optimizer.state[model.weight]["exp_avg"], torch.tensor([0.2, -0.3])) | ||
| 124 | + assert optimizer.state[model.weight]["step"].item() == 1 | ||
| 125 | + assert manager.states[LR_SCHEDULER].value == {"last_epoch": 4} | ||
| 126 | + assert manager.states[TRAIN_STATE].value == state | ||
| 127 | + assert cursor.value["position"].item() == 20 | ||
| 128 | + assert torch.equal(torch.get_rng_state(), expected_rng) | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +def test_external_emergency_resume_can_save_and_reload_periodic_checkpoint(saved_checkpoint, monkeypatch): | ||
| 132 | + manager, target, model, _, cursor, state = saved_checkpoint | ||
| 133 | + manager.folder = str(Path(manager.folder) / "next-job") | ||
| 134 | + manager.last_words.config.run_id = "restart" | ||
| 135 | + manager.last_words.config.resume_path = str(target) | ||
| 136 | + manager.last_words_stop_requested = lambda: False | ||
| 137 | + monkeypatch.setattr(torch.distributed, "get_rank", lambda: 0) | ||
| 138 | + | ||
| 139 | + assert manager.load() | ||
| 140 | + assert manager.save(state["step"]) | ||
| 141 | + | ||
| 142 | + binding = read_json(Path(manager.folder) / "step-5/last_words_binding.json") | ||
| 143 | + assert binding["state"] == state | ||
| 144 | + assert (Path(manager.folder) / binding["anchors"]["0"] / ".metadata").is_file() | ||
| 145 | + manager.last_words.config.resume_path = "" | ||
| 146 | + manager.last_words.config.run_id = "second-restart" | ||
| 147 | + with torch.no_grad(): | ||
| 148 | + model.weight.fill_(50) | ||
| 149 | + cursor.value["position"].fill_(1000) | ||
| 150 | + | ||
| 151 | + assert manager.load() | ||
| 152 | + torch.testing.assert_close(model.weight, torch.tensor([0.9798, -3.9792])) | ||
| 153 | + assert cursor.value["position"].item() == 20 | ||
| 154 | + assert manager.states[TRAIN_STATE].value == state | ||
| @@ -0,0 +1,62 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +import json | ||
| 5 | +import runpy | ||
| 6 | +from contextlib import ExitStack | ||
| 7 | + | ||
| 8 | +from tests.unit_tests.extensions.torchtitan.experiments.torchft.service_helpers import FEATURE, service_session | ||
| 9 | + | ||
| 10 | +WorkerSessionClient = runpy.run_path(str(FEATURE / "client.py"))["WorkerSessionClient"] | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def test_resume_requires_the_same_checkpoint_from_both_replica_leaders(tmp_path, monkeypatch): | ||
| 14 | + with service_session(tmp_path, "resume", world_size=1) as directory, ExitStack() as clients: | ||
| 15 | + leaders = [] | ||
| 16 | + for replica in range(2): | ||
| 17 | + monkeypatch.setenv("LAST_WORDS_SESSION_FILE", str(directory / f"replica-{replica}.json")) | ||
| 18 | + leader = WorkerSessionClient("resume", replica, 0) | ||
| 19 | + clients.callback(leader.client.close) | ||
| 20 | + leaders.append(leader) | ||
| 21 | + choice = "periodic step=4 candidate" | ||
| 22 | + status = dict(phase="initializing", world_size=1, heartbeat_timeout_seconds=30, resume_choice=choice) | ||
| 23 | + assert "confirmed_resume" not in leaders[0].report(status, requested=False) | ||
| 24 | + for leader in reversed(leaders): | ||
| 25 | + assert leader.report(status, requested=False)["confirmed_resume"] == choice | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +def test_service_elects_most_advanced_replica_and_confirms_save(tmp_path, monkeypatch): | ||
| 29 | + with service_session(tmp_path, "save") as directory, ExitStack() as clients: | ||
| 30 | + workers = [] | ||
| 31 | + for replica, step in enumerate((2, 3)): | ||
| 32 | + monkeypatch.setenv("LAST_WORDS_SESSION_FILE", str(directory / f"replica-{replica}.json")) | ||
| 33 | + state = {"step": step, "last_words_num_updates": step} | ||
| 34 | + status = dict(phase="frozen", state=state, world_size=2, heartbeat_timeout_seconds=30) | ||
| 35 | + ranks = [] | ||
| 36 | + for rank in range(2): | ||
| 37 | + worker = WorkerSessionClient("save", replica, rank) | ||
| 38 | + clients.callback(worker.client.close) | ||
| 39 | + worker.set_ready(state, "model") | ||
| 40 | + worker.report(status, requested=True) | ||
| 41 | + ranks.append(worker) | ||
| 42 | + workers.append(ranks) | ||
| 43 | + | ||
| 44 | + expected_state = {"step": 3, "last_words_num_updates": 3} | ||
| 45 | + grant = {"round": 1, "replica_id": 1, "state": expected_state, "signature": "model"} | ||
| 46 | + assert all(worker.poll()["grant"] == grant for ranks in workers for worker in ranks) | ||
| 47 | + | ||
| 48 | + published = dict( | ||
| 49 | + phase="frozen", state=expected_state, world_size=2, heartbeat_timeout_seconds=30, published_round=1 | ||
| 50 | + ) | ||
| 51 | + writer = workers[1] | ||
| 52 | + for worker in writer: | ||
| 53 | + assert worker.report(published, requested=True)["result"] is None | ||
| 54 | + result = writer[0].report(dict(published, validated_round=1), requested=True) | ||
| 55 | + assert result["phase"] == "SUCCEEDED" | ||
| 56 | + expected = {"round": 1, "replica_id": 1, "success": True, "error": ""} | ||
| 57 | + assert result["result"] == expected | ||
| 58 | + assert workers[0][1].poll()["result"] == expected | ||
| 59 | + audit = json.loads((directory / "result.json").read_text()) | ||
| 60 | + assert audit == dict( | ||
| 61 | + expected, version=result["version"], run_id="save", coordinator_instance=result["instance"] | ||
| 62 | + ) | ||
| @@ -57,7 +57,9 @@ def test_reset_failed_iteration_clears_cached_fsdp_gradients(monkeypatch): | |||
| 57 | unsharded.grad = torch.ones(1) | 57 | unsharded.grad = torch.ones(1) |
| 58 | self.fsdp_param = object.__new__(FSDPParam) | 58 | self.fsdp_param = object.__new__(FSDPParam) |
| 59 | self.fsdp_param._unsharded_param = unsharded | 59 | self.fsdp_param._unsharded_param = unsharded |
| 60 | - self.state = SimpleNamespace(_fsdp_param_groups=[SimpleNamespace(fsdp_params=[self.fsdp_param])]) | 60 | + self.state = SimpleNamespace( |
| 61 | + _is_root=True, _fsdp_param_groups=[SimpleNamespace(fsdp_params=[self.fsdp_param])] | ||
| 62 | + ) | ||
| 61 | self.reset_count = 0 | 63 | self.reset_count = 0 |
| 62 | 64 | ||
| 63 | def _get_fsdp_state(self): | 65 | def _get_fsdp_state(self): |
| @@ -7,8 +7,11 @@ from unittest.mock import Mock | |||
| 7 | 7 | ||
| 8 | import pytest | 8 | import pytest |
| 9 | import torch | 9 | import torch |
| 10 | -from torchtitan.components.optim import AdamW | 10 | +import torch.distributed.checkpoint as dcp |
| 11 | +from torchtitan.components.checkpointer import LR_SCHEDULER, OPTIMIZER | ||
| 12 | +from torchtitan.components.optim import AdamW, LRSchedulersContainer | ||
| 11 | 13 | ||
| 14 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.last_words.checkpoint import LastWordsCheckpointManager | ||
| 12 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.optimizer import ( | 15 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.optimizer import ( |
| 13 | TorchFTOptimEx, | 16 | TorchFTOptimEx, |
| 14 | TorchFTOptimizersContainerEx, | 17 | TorchFTOptimizersContainerEx, |
| @@ -16,14 +19,16 @@ from torchtitan_npu.extensions.torchtitan.experiments.torchft.optimizer import ( | |||
| 16 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx | 19 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx |
| 17 | 20 | ||
| 18 | 21 | ||
| 19 | -def make_optimizer(accepted): | 22 | +def make_optimizer(accepted, *, last_words=False): |
| 20 | model = torch.nn.Linear(1, 1, bias=False) | 23 | model = torch.nn.Linear(1, 1, bias=False) |
| 21 | with torch.no_grad(): | 24 | with torch.no_grad(): |
| 22 | model.weight.fill_(1.0) | 25 | model.weight.fill_(1.0) |
| 23 | manager = Mock() | 26 | manager = Mock() |
| 24 | manager._pg = ProcessGroupHCCLEx(recovery_timeout=timedelta(seconds=1)) | 27 | manager._pg = ProcessGroupHCCLEx(recovery_timeout=timedelta(seconds=1)) |
| 25 | manager.should_commit.return_value = accepted | 28 | manager.should_commit.return_value = accepted |
| 26 | - ft = SimpleNamespace(manager=manager, process_group=manager._pg, use_async_quorum=False) | 29 | + ft = SimpleNamespace( |
| 30 | + manager=manager, process_group=manager._pg, use_async_quorum=False, last_words_enabled=last_words | ||
| 31 | + ) | ||
| 27 | config = TorchFTOptimizersContainerEx.Config( | 32 | config = TorchFTOptimizersContainerEx.Config( |
| 28 | optimizers=[ | 33 | optimizers=[ |
| 29 | AdamW.Config( | 34 | AdamW.Config( |
| @@ -79,6 +84,58 @@ def test_accepted_step_updates_parameter_once_and_advances_scheduler_once(monkey | |||
| 79 | torch.testing.assert_close(model.weight, torch.tensor([[0.9]])) | 84 | torch.testing.assert_close(model.weight, torch.tensor([[0.9]])) |
| 80 | 85 | ||
| 81 | 86 | ||
| 87 | +def test_last_words_authorizes_update_before_model_hooks(monkeypatch): | ||
| 88 | + model, optimizer, manager = make_optimizer(True, last_words=True) | ||
| 89 | + monkeypatch.setattr("torch_npu.npu.current_stream", lambda: Mock(synchronize=Mock())) | ||
| 90 | + events = [] | ||
| 91 | + manager.should_commit.side_effect = lambda: events.append("vote") or True | ||
| 92 | + optimizer.register_step_pre_hook(lambda *_: events.append("model-hook")) | ||
| 93 | + optimizer.on_last_words_update = lambda: events.append("updating") | ||
| 94 | + optimizer.zero_grad() | ||
| 95 | + model(torch.ones(1, 1)).sum().backward() | ||
| 96 | + optimizer.step() | ||
| 97 | + | ||
| 98 | + assert events == ["vote", "updating", "model-hook"] | ||
| 99 | + torch.testing.assert_close(model.weight, torch.tensor([[0.9]])) | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +@pytest.mark.parametrize("legacy", [False, True], ids=["current", "legacy-cache"]) | ||
| 103 | +def test_periodic_checkpoint_restores_decayed_lr_before_next_update(tmp_path, legacy): | ||
| 104 | + def checkpointer(): | ||
| 105 | + model, optimizer, _ = make_optimizer(True) | ||
| 106 | + schedule = LRSchedulersContainer(optimizer, lambda epoch: 0.5**epoch) | ||
| 107 | + optimizer.init_cache_state_dict() | ||
| 108 | + return LastWordsCheckpointManager( | ||
| 109 | + LastWordsCheckpointManager.Config(folder=str(tmp_path), interval=1, keep_latest_k=0), | ||
| 110 | + model_parts=[model], | ||
| 111 | + optimizers=optimizer, | ||
| 112 | + lr_schedulers=schedule, | ||
| 113 | + ema=None, | ||
| 114 | + extra_states={}, | ||
| 115 | + sd_adapter=None, | ||
| 116 | + ) | ||
| 117 | + | ||
| 118 | + writer = checkpointer() | ||
| 119 | + writer.states[OPTIMIZER].optimizers[0].step() | ||
| 120 | + writer.states[LR_SCHEDULER].step() | ||
| 121 | + checkpoint = tmp_path / "step-1" | ||
| 122 | + if legacy: | ||
| 123 | + dcp.save(writer._flattened_model_states_sd(), checkpoint_id=checkpoint) | ||
| 124 | + else: | ||
| 125 | + assert writer.save(1) | ||
| 126 | + writer.close() | ||
| 127 | + | ||
| 128 | + raw = {OPTIMIZER: {"param_groups.weight.lr": 0.0}} | ||
| 129 | + dcp.load(raw, checkpoint_id=checkpoint) | ||
| 130 | + assert raw[OPTIMIZER]["param_groups.weight.lr"] == (0.1 if legacy else 0.05) | ||
| 131 | + | ||
| 132 | + reader = checkpointer() | ||
| 133 | + assert reader.load() | ||
| 134 | + assert reader.states[OPTIMIZER].optimizers[0].param_groups[0]["lr"] == 0.05 | ||
| 135 | + assert reader.states[LR_SCHEDULER].state_dict() == {"last_epoch": 1} | ||
| 136 | + reader.close() | ||
| 137 | + | ||
| 138 | + | ||
| 82 | def test_rejected_step_skips_optimizer_and_preserves_upstream_scheduler_advancement(): | 139 | def test_rejected_step_skips_optimizer_and_preserves_upstream_scheduler_advancement(): |
| 83 | model, optimizer, manager = make_optimizer(False) | 140 | model, optimizer, manager = make_optimizer(False) |
| 84 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer.optimizers[0], step_size=1, gamma=0.5) | 141 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer.optimizers[0], step_size=1, gamma=0.5) |
| @@ -318,15 +318,15 @@ def test_ft_train_step_consumes_collated_valid_tokens(monkeypatch): | |||
| 318 | engine.forward_backward = forward_backward | 318 | engine.forward_backward = forward_backward |
| 319 | engine.optim_step = Mock(return_value=torch.tensor(1.0)) | 319 | engine.optim_step = Mock(return_value=torch.tensor(1.0)) |
| 320 | 320 | ||
| 321 | - trainer = SimpleNamespace( | 321 | + trainer = module.FaultTolerantTrainerEx.__new__(module.FaultTolerantTrainerEx) |
| 322 | - engine=engine, | 322 | + trainer.engine = engine |
| 323 | - recovery=Mock(), | 323 | + trainer.recovery = Mock() |
| 324 | - metrics_processor=Mock(should_log=Mock(return_value=False)), | 324 | + trainer.last_words = None |
| 325 | - gradient_accumulation_steps=2, | 325 | + trainer.metrics_processor = Mock(should_log=Mock(return_value=False)) |
| 326 | - num_pp_microbatches=1, | 326 | + trainer.gradient_accumulation_steps = 2 |
| 327 | - ) | 327 | + trainer.num_pp_microbatches = 1 |
| 328 | 328 | ||
| 329 | - module.FaultTolerantTrainerEx._train_step(trainer, iter(microbatches)) | 329 | + trainer._train_step(iter(microbatches)) |
| 330 | 330 | ||
| 331 | assert len(observed) == 1 | 331 | assert len(observed) == 1 |
| 332 | groups, loss_tokens, routing_tokens = observed[0] | 332 | groups, loss_tokens, routing_tokens = observed[0] |
| @@ -346,7 +346,7 @@ def test_ft_train_step_consumes_collated_valid_tokens(monkeypatch): | |||
| 346 | monkeypatch.setattr(module.dist_utils, "dist_max", lambda value, *_: value.item()) | 346 | monkeypatch.setattr(module.dist_utils, "dist_max", lambda value, *_: value.item()) |
| 347 | monkeypatch.setattr(module, "collect_aux_loss_metrics", lambda _: {"aux_loss": 0.25}) | 347 | monkeypatch.setattr(module, "collect_aux_loss_metrics", lambda _: {"aux_loss": 0.25}) |
| 348 | engine.optim_step.side_effect = lambda: trainer.metrics_processor.log.assert_not_called() or torch.tensor(1.0) | 348 | engine.optim_step.side_effect = lambda: trainer.metrics_processor.log.assert_not_called() or torch.tensor(1.0) |
| 349 | - module.FaultTolerantTrainerEx._train_step(trainer, iter(microbatches)) | 349 | + trainer._train_step(iter(microbatches)) |
| 350 | assert observed[1][1:] == ([10, 6], [14, 10]) | 350 | assert observed[1][1:] == ([10, 6], [14, 10]) |
| 351 | trainer.metrics_processor.reset.assert_called_once() | 351 | trainer.metrics_processor.reset.assert_called_once() |
| 352 | log_args = trainer.metrics_processor.log.call_args | 352 | log_args = trainer.metrics_processor.log.call_args |
| @@ -5,5 +5,6 @@ | |||
| 5 | - 每个上游目标只允许一个激活模块直接 monkey-patch,避免覆盖顺序不确定。迁移阶段的 ownership 检查脚本保存在代码仓外的本地工具目录;新增 patch 仍必须人工确认 owner、目标路径和激活顺序。 | 5 | - 每个上游目标只允许一个激活模块直接 monkey-patch,避免覆盖顺序不确定。迁移阶段的 ownership 检查脚本保存在代码仓外的本地工具目录;新增 patch 仍必须人工确认 owner、目标路径和激活顺序。 |
| 6 | - 激活模块通过公开注册接口接纳其他扩展;需要扩展同一目标时,不得新增第二个直接 patch 模块。 | 6 | - 激活模块通过公开注册接口接纳其他扩展;需要扩展同一目标时,不得新增第二个直接 patch 模块。 |
| 7 | - TorchFT engine 绑定由 `experiments/torchft/__init__.py` 按需独占激活;目标与顺序见[架构说明](../../../docs/architecture.md#torchft-engine)。 | 7 | - TorchFT engine 绑定由 `experiments/torchft/__init__.py` 按需独占激活;目标与顺序见[架构说明](../../../docs/architecture.md#torchft-engine)。 |
| 8 | +- TorchFT 遗言 service 是显式启动的标准库入口。worker 在线程中协调保存,节点进程的启动与重启由外部负责。 | ||
| 8 | - 组件接线模块只注册 hook,不定义 `apply()`,也不直接 monkey-patch。组件禁用时只跳过对应接线模块,核心激活模块仍可加载。 | 9 | - 组件接线模块只注册 hook,不定义 `apply()`,也不直接 monkey-patch。组件禁用时只跳过对应接线模块,核心激活模块仍可加载。 |
| 9 | - 核心模块不得在顶层导入组件;在真正注册或需要时再惰性加载已声明组件。 | 10 | - 核心模块不得在顶层导入组件;在真正注册或需要时再惰性加载已声明组件。 |
| @@ -0,0 +1,34 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +"""TorchFT checkpoint handling for scalar optimizer state and scheduler restoration.""" | ||
| 5 | + | ||
| 6 | +import torch | ||
| 7 | +from torchtitan.components.checkpointer import LR_SCHEDULER, OPTIMIZER | ||
| 8 | +from torchtitan.components.optim import LRSchedulersContainer | ||
| 9 | +from torchtitan.experiments.torchft.checkpoint import TorchFTCheckpointManager | ||
| 10 | +from torchtitan.experiments.torchft.optimizer import TorchFTOptimizersContainer | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +class TorchFTCheckpointManagerEx(TorchFTCheckpointManager): | ||
| 14 | + def _prepare_save_state(self, state_dict): | ||
| 15 | + optimizer = state_dict.get(OPTIMIZER) | ||
| 16 | + if isinstance(optimizer, TorchFTOptimizersContainer): | ||
| 17 | + optimizer._refresh_cached_state_dict() # pyrefly: ignore [missing-attribute] | ||
| 18 | + | ||
| 19 | + def dcp_save(self, state_dict, *args, **kwargs): | ||
| 20 | + self._prepare_save_state(state_dict) | ||
| 21 | + return super().dcp_save(state_dict, *args, **kwargs) | ||
| 22 | + | ||
| 23 | + def _load_checkpoint(self, states, checkpoint_id, *, from_hf, from_quantized): | ||
| 24 | + super()._load_checkpoint(states, checkpoint_id, from_hf=from_hf, from_quantized=from_quantized) | ||
| 25 | + schedulers = states.get(LR_SCHEDULER) | ||
| 26 | + if isinstance(states.get(OPTIMIZER), TorchFTOptimizersContainer) and type(schedulers) is LRSchedulersContainer: | ||
| 27 | + # Legacy periodic checkpoints can contain an older optimizer lr. The | ||
| 28 | + # built-in LambdaLR has already reconstructed each group's rate at last_epoch. | ||
| 29 | + for scheduler in schedulers: | ||
| 30 | + for group, lr in zip(scheduler.optimizer.param_groups, scheduler.get_last_lr(), strict=True): | ||
| 31 | + if isinstance(group["lr"], torch.Tensor): | ||
| 32 | + group["lr"].fill_(lr) | ||
| 33 | + else: | ||
| 34 | + group["lr"] = lr | ||
| @@ -7,7 +7,7 @@ | |||
| 7 | """Synchronous TorchFT manager for the NPU FSDP/EP training path.""" | 7 | """Synchronous TorchFT manager for the NPU FSDP/EP training path.""" |
| 8 | 8 | ||
| 9 | from collections.abc import Callable | 9 | from collections.abc import Callable |
| 10 | -from dataclasses import dataclass | 10 | +from dataclasses import dataclass, field |
| 11 | from datetime import timedelta | 11 | from datetime import timedelta |
| 12 | 12 | ||
| 13 | import torch | 13 | import torch |
| @@ -16,6 +16,7 @@ import torchft | |||
| 16 | from torch.distributed._composable.fsdp.fully_shard import FSDPModule | 16 | from torch.distributed._composable.fsdp.fully_shard import FSDPModule |
| 17 | from torchtitan.experiments.torchft.manager import TorchFTManager | 17 | from torchtitan.experiments.torchft.manager import TorchFTManager |
| 18 | 18 | ||
| 19 | +from torchtitan_npu.extensions.torchtitan.experiments.torchft.last_words.worker import LastWordsConfig | ||
| 19 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import ManagerEx | 20 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.manager import ManagerEx |
| 20 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx | 21 | from torchtitan_npu.extensions.torchtitan.experiments.torchft.process_group import ProcessGroupHCCLEx |
| 21 | 22 | ||
| @@ -57,6 +58,8 @@ def _install_all_reduce_hooks( | |||
| 57 | 58 | ||
| 58 | 59 | ||
| 59 | class FTManagerEx(TorchFTManager): | 60 | class FTManagerEx(TorchFTManager): |
| 61 | + manager: ManagerEx # pyrefly: ignore [bad-override-mutable-attribute] | ||
| 62 | + | ||
| 60 | @dataclass(kw_only=True, slots=True) | 63 | @dataclass(kw_only=True, slots=True) |
| 61 | class Config(TorchFTManager.Config): | 64 | class Config(TorchFTManager.Config): |
| 62 | enable: bool = True | 65 | enable: bool = True |
| @@ -67,9 +70,15 @@ class FTManagerEx(TorchFTManager): | |||
| 67 | device_recovery_timeout_seconds: int = 60 | 70 | device_recovery_timeout_seconds: int = 60 |
| 68 | max_consecutive_hccl_recoveries: int = 3 | 71 | max_consecutive_hccl_recoveries: int = 3 |
| 69 | quorum_warmup_timeout_ms: int = 90000 | 72 | quorum_warmup_timeout_ms: int = 90000 |
| 73 | + enable_elastic: bool = True | ||
| 74 | + """Allow runtime replica shrink, healing and externally initiated rejoin.""" | ||
| 75 | + last_words: LastWordsConfig = field(default_factory=LastWordsConfig) | ||
| 70 | 76 | ||
| 71 | @staticmethod | 77 | @staticmethod |
| 72 | def validate_config(config: Config) -> None: | 78 | def validate_config(config: Config) -> None: |
| 79 | + config.last_words.validate() | ||
| 80 | + if not config.enable_elastic and config.min_replica_size != config.group_size: | ||
| 81 | + raise ValueError("Fixed membership requires min_replica_size == group_size") | ||
| 73 | if not config.enable or config.process_group != "hccl": | 82 | if not config.enable or config.process_group != "hccl": |
| 74 | raise ValueError("NPU TorchFT requires enabled HCCL fault tolerance") | 83 | raise ValueError("NPU TorchFT requires enabled HCCL fault tolerance") |
| 75 | if config.semi_sync_method is not None: | 84 | if config.semi_sync_method is not None: |
| @@ -87,6 +96,7 @@ class FTManagerEx(TorchFTManager): | |||
| 87 | self.validate_config(config) | 96 | self.validate_config(config) |
| 88 | self.group_size = config.group_size | 97 | self.group_size = config.group_size |
| 89 | self.replica_id = config.replica_id | 98 | self.replica_id = config.replica_id |
| 99 | + self.last_words_enabled = config.last_words.enable | ||
| 90 | # Required by TorchTitan's optimizer container interface. Quorum | 100 | # Required by TorchTitan's optimizer container interface. Quorum |
| 91 | # scheduling itself is fixed to synchronous mode below. | 101 | # scheduling itself is fixed to synchronous mode below. |
| 92 | self.use_async_quorum = False | 102 | self.use_async_quorum = False |
| @@ -112,6 +122,7 @@ class FTManagerEx(TorchFTManager): | |||
| 112 | timeout=timedelta(milliseconds=config.timeout_ms), | 122 | timeout=timedelta(milliseconds=config.timeout_ms), |
| 113 | quorum_timeout=timedelta(seconds=config.quorum_timeout_seconds), | 123 | quorum_timeout=timedelta(seconds=config.quorum_timeout_seconds), |
| 114 | ) | 124 | ) |
| 125 | + self._manager.elastic_enabled = config.enable_elastic | ||
| 115 | self.replicate_pg = torchft.process_group.ManagedProcessGroup(self._manager) | 126 | self.replicate_pg = torchft.process_group.ManagedProcessGroup(self._manager) |
| 116 | self.replicate_pg.register("dp_replicate") | 127 | self.replicate_pg.register("dp_replicate") |
| 117 | 128 | ||
| @@ -0,0 +1,4 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +"""Coordinated emergency checkpoint saving for NPU TorchFT.""" | ||
Atorchtitan_npu/extensions/torchtitan/experiments/torchft/last_words/checkpoint.py+889-0File content is under review, please try again later
| @@ -0,0 +1,240 @@ | |||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 2 | +# All rights reserved. | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 4 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 5 | + | ||
| 6 | +"""Check DCP metadata against the application's required recovery state.""" | ||
| 7 | + | ||
| 8 | +import hashlib | ||
| 9 | +import json | ||
| 10 | +from dataclasses import fields, is_dataclass | ||
| 11 | +from functools import partial | ||
| 12 | +from math import prod | ||
| 13 | +from pathlib import Path | ||
| 14 | +from typing import Any | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def tokenizer_asset_digest(folder: str) -> str: | ||
| 18 | + """Hash the assets selected by TorchTitan's HuggingFaceTokenizer, independent of their location.""" | ||
| 19 | + root = Path(folder) | ||
| 20 | + names = ["tokenizer.json"] | ||
| 21 | + if not (root / "tokenizer.json").is_file(): | ||
| 22 | + names = ["vocab.json" if (root / "vocab.json").is_file() else "vocab.txt"] | ||
| 23 | + if (root / "merges.txt").is_file(): | ||
| 24 | + names.append("merges.txt") | ||
| 25 | + if (root / "tokenizer_config.json").is_file(): | ||
| 26 | + names.append("tokenizer_config.json") | ||
| 27 | + if (root / "chat_template.jinja").is_file(): | ||
| 28 | + names.append("chat_template.jinja") | ||
| 29 | + digests = {} | ||
| 30 | + for name in names: | ||
| 31 | + with (root / name).open("rb") as asset: | ||
| 32 | + digests[name] = hashlib.file_digest(asset, "sha256").hexdigest() | ||
| 33 | + return hashlib.sha256(json.dumps(digests, sort_keys=True).encode()).hexdigest() | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def checkpoint_config_signatures(config: Any) -> tuple[str, ...]: | ||
| 37 | + """Bind persisted training state to the v0.4 recipe and data geometry.""" | ||
| 38 | + | ||
| 39 | + def normalize(value: Any) -> Any: | ||
| 40 | + if is_dataclass(value) and not isinstance(value, type): | ||
| 41 | + return { | ||
| 42 | + "owner": f"{type(value).__module__}.{type(value).__qualname__}", | ||
| 43 | + "fields": {field.name: normalize(getattr(value, field.name)) for field in fields(value)}, | ||
| 44 | + } | ||
| 45 | + if isinstance(value, dict): | ||
| 46 | + return {str(key): normalize(item) for key, item in value.items()} | ||
| 47 | + if isinstance(value, (list, tuple)): | ||
| 48 | + return [normalize(item) for item in value] | ||
| 49 | + if isinstance(value, (set, frozenset)): | ||
| 50 | + return sorted((normalize(item) for item in value), key=lambda item: json.dumps(item, sort_keys=True)) | ||
| 51 | + if isinstance(value, (str, int, float, bool)) or value is None: | ||
| 52 | + return value | ||
| 53 | + if isinstance(value, partial): | ||
| 54 | + return { | ||
| 55 | + "function": normalize(value.func), | ||
| 56 | + "args": normalize(value.args), | ||
| 57 | + "keywords": normalize(value.keywords), | ||
| 58 | + } | ||
| 59 | + if callable(value): | ||
| 60 | + return f"{value.__module__}.{value.__qualname__}" | ||
| 61 | + return str(value) | ||
| 62 | + | ||
| 63 | + contract = { | ||
| 64 | + "version": 3, | ||
| 65 | + "model": normalize(config.model), | ||
| 66 | + "parallelism": normalize(config.parallelism), | ||
| 67 | + "dataloader": normalize(config.dataloader), | ||
| 68 | + "tokenizer": normalize(config.tokenizer), | ||
| 69 | + "optim": normalize(config.optim), | ||
| 70 | + "training": normalize(config.training), | ||
| 71 | + "loss": normalize(config.loss), | ||
| 72 | + "group_size": config.fault_tolerance.group_size, | ||
| 73 | + "override": normalize(config.override), | ||
| 74 | + "compile": normalize(config.compile), | ||
| 75 | + } | ||
| 76 | + return (hashlib.sha256(json.dumps(contract, sort_keys=True).encode()).hexdigest(),) | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +def state_schema(states, *, kind): | ||
| 80 | + """Describe live DCP state without saving or loading tensor values.""" | ||
| 81 | + from torch.distributed.checkpoint import DefaultSavePlanner | ||
| 82 | + from torch.distributed.checkpoint.stateful import Stateful | ||
| 83 | + | ||
| 84 | + values = {key: value.state_dict() if isinstance(value, Stateful) else value for key, value in states.items()} | ||
| 85 | + planner = DefaultSavePlanner() | ||
| 86 | + planner.set_up_planner(values, is_coordinator=True) | ||
| 87 | + fields = {} | ||
| 88 | + for item in planner.create_local_plan().items: | ||
| 89 | + field = {"kind": "object"} | ||
| 90 | + if item.tensor_data is not None: | ||
| 91 | + field = { | ||
| 92 | + "kind": "tensor", | ||
| 93 | + "shape": list(item.tensor_data.size), | ||
| 94 | + "dtype": str(item.tensor_data.properties.dtype), | ||
| 95 | + } | ||
| 96 | + previous = fields.setdefault(item.index.fqn, field) | ||
| 97 | + if previous != field: | ||
| 98 | + raise ValueError("Inconsistent local tensor recovery schema") | ||
| 99 | + groups: dict[str, list[str]] = {} | ||
| 100 | + reserved = {"optimizer", "lr_scheduler", "train_state", "ema", "torchft"} | ||
| 101 | + if kind == "cursor": | ||
| 102 | + reserved = {"dataloader", "last_words_rng"} | ||
| 103 | + elif kind != "model": | ||
| 104 | + raise ValueError("Unknown recovery state schema kind") | ||
| 105 | + for name in fields: | ||
| 106 | + prefix = name.split(".", 1)[0] | ||
| 107 | + group = prefix if prefix in reserved else "model" | ||
| 108 | + groups.setdefault(group, []).append(name) | ||
| 109 | + return {"version": 1, "kind": kind, "fields": fields, "groups": groups} | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +def replica_cursor_schema(local, replica, *, batch_degree, num_shards): | ||
| 113 | + """Expand the live rank's DCP contract to every shard of a logical replica.""" | ||
| 114 | + fields = {} | ||
| 115 | + groups = {} | ||
| 116 | + for group, names in local["groups"].items(): | ||
| 117 | + expanded = [] | ||
| 118 | + for name in names: | ||
| 119 | + prefix, _, rest = name.partition(".") | ||
| 120 | + slot, dot, suffix = rest.partition(".") | ||
| 121 | + # ParallelAwareDataloader uses global batch ranks; RNG uses local shard ranks. | ||
| 122 | + if group == "dataloader" and slot.startswith("dp_rank_") and slot[8:].isdecimal(): | ||
| 123 | + slots = [f"dp_rank_{replica * batch_degree + i}" for i in range(batch_degree)] | ||
| 124 | + elif group == "last_words_rng" and slot.startswith("rank_") and slot[5:].isdecimal(): | ||
| 125 | + slots = [f"rank_{i}" for i in range(num_shards)] | ||
| 126 | + else: | ||
| 127 | + expanded.append(name) | ||
| 128 | + fields[name] = local["fields"][name] | ||
| 129 | + continue | ||
| 130 | + for target in slots: | ||
| 131 | + key = f"{prefix}.{target}{dot}{suffix}" | ||
| 132 | + if key not in fields: | ||
| 133 | + expanded.append(key) | ||
| 134 | + fields[key] = local["fields"][name] | ||
| 135 | + groups[group] = expanded | ||
| 136 | + return {**local, "fields": fields, "groups": groups} | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +def _validate_description(schema, *, kind): | ||
| 140 | + if not isinstance(schema, dict) or schema.get("version") != 1 or schema.get("kind") != kind: | ||
| 141 | + raise ValueError("Checkpoint has no compatible required-state schema") | ||
| 142 | + fields, groups = schema.get("fields"), schema.get("groups") | ||
| 143 | + if not isinstance(fields, dict) or not isinstance(groups, dict): | ||
| 144 | + raise ValueError("Invalid required-state schema layout") | ||
| 145 | + required = {"model", "optimizer", "lr_scheduler", "train_state"} | ||
| 146 | + if kind == "cursor": | ||
| 147 | + required = {"dataloader", "last_words_rng"} | ||
| 148 | + if not required <= groups.keys(): | ||
| 149 | + raise ValueError(f"Checkpoint schema lacks required state: {sorted(required - groups.keys())}") | ||
| 150 | + covered = [] | ||
| 151 | + for group, names in groups.items(): | ||
| 152 | + if not isinstance(group, str) or not isinstance(names, list) or not names: | ||
| 153 | + raise ValueError("Checkpoint schema has an empty state group") | ||
| 154 | + for name in names: | ||
| 155 | + if not isinstance(name, str) or name not in fields: | ||
| 156 | + raise ValueError("Checkpoint state group references a missing field") | ||
| 157 | + if group != "model" and name != group and not name.startswith(group + "."): | ||
| 158 | + raise ValueError("Checkpoint state group and field name disagree") | ||
| 159 | + covered.extend(names) | ||
| 160 | + if len(covered) != len(set(covered)) or set(covered) != fields.keys(): | ||
| 161 | + raise ValueError("Checkpoint state groups do not partition required fields") | ||
| 162 | + for name, field in fields.items(): | ||
| 163 | + if not isinstance(field, dict) or field.get("kind") not in {"tensor", "object"}: | ||
| 164 | + raise ValueError(f"Invalid recovery field schema: {name}") | ||
| 165 | + if field["kind"] == "tensor" and ( | ||
| 166 | + not isinstance(field.get("shape"), list) | ||
| 167 | + or any(type(size) is not int or size < 0 for size in field["shape"]) | ||
| 168 | + or not isinstance(field.get("dtype"), str) | ||
| 169 | + ): | ||
| 170 | + raise ValueError(f"Invalid tensor recovery schema: {name}") | ||
| 171 | + if kind == "model" and not any(fields[name]["kind"] == "tensor" for name in groups["model"]): | ||
| 172 | + raise ValueError("Checkpoint model schema has no tensor state") | ||
| 173 | + return fields | ||
| 174 | + | ||
| 175 | + | ||
| 176 | +def validate_state_schema(path, schema, *, kind, expected=None): | ||
| 177 | + """Check published fields, then the independently derived live schema.""" | ||
| 178 | + import torch.distributed.checkpoint as dcp | ||
| 179 | + from torch.distributed.checkpoint.metadata import BytesStorageMetadata, TensorStorageMetadata | ||
| 180 | + | ||
| 181 | + required = dict(_validate_description(schema, kind=kind)) | ||
| 182 | + if expected is not None: | ||
| 183 | + # The candidate's own declaration cannot relax the live application's | ||
| 184 | + # model, optimizer, EMA, counters or current logical-replica cursor. | ||
| 185 | + for name, field in _validate_description(expected, kind=kind).items(): | ||
| 186 | + if name in required and required[name] != field: | ||
| 187 | + raise ValueError(f"Published and live recovery schemas differ: {name}") | ||
| 188 | + required[name] = field | ||
| 189 | + metadata = dcp.FileSystemReader(path).read_metadata().state_dict_metadata | ||
| 190 | + for name, field in required.items(): | ||
| 191 | + stored = metadata.get(name) | ||
| 192 | + if field["kind"] == "tensor": | ||
| 193 | + if ( | ||
| 194 | + not isinstance(stored, TensorStorageMetadata) | ||
| 195 | + or list(stored.size) != field["shape"] | ||
| 196 | + or str(stored.properties.dtype) != field["dtype"] | ||
| 197 | + ): | ||
| 198 | + raise ValueError(f"Checkpoint has no matching required tensor: {name}") | ||
| 199 | + elif not isinstance(stored, BytesStorageMetadata): | ||
| 200 | + raise ValueError(f"Checkpoint has no required serialized state: {name}") | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +def validate_metadata_coverage(metadata): | ||
| 204 | + """Reject metadata with missing storage or incomplete/overlapping chunks.""" | ||
| 205 | + from torch.distributed.checkpoint.metadata import BytesStorageMetadata, TensorStorageMetadata | ||
| 206 | + | ||
| 207 | + storage = {(item.fqn, tuple(item.offset) if item.offset is not None else None) for item in metadata.storage_data} | ||
| 208 | + for name, entry in metadata.state_dict_metadata.items(): | ||
| 209 | + if isinstance(entry, BytesStorageMetadata): | ||
| 210 | + if (name, None) not in storage: | ||
| 211 | + raise ValueError(f"Checkpoint has no storage for state: {name}") | ||
| 212 | + continue | ||
| 213 | + if not isinstance(entry, TensorStorageMetadata): | ||
| 214 | + raise ValueError(f"Unsupported checkpoint metadata: {name}") | ||
| 215 | + volume, chunks = 0, [] | ||
| 216 | + for chunk in entry.chunks: | ||
| 217 | + offsets, sizes = tuple(chunk.offsets), tuple(chunk.sizes) | ||
| 218 | + if ( | ||
| 219 | + len(offsets) != len(entry.size) | ||
| 220 | + or len(sizes) != len(entry.size) | ||
| 221 | + or any( | ||
| 222 | + offset < 0 or size < 0 or offset + size > full | ||
| 223 | + for offset, size, full in zip(offsets, sizes, entry.size, strict=True) | ||
| 224 | + ) | ||
| 225 | + ): | ||
| 226 | + raise ValueError(f"Checkpoint has invalid tensor chunks: {name}") | ||
| 227 | + current = prod(sizes) | ||
| 228 | + if current: | ||
| 229 | + if (name, offsets) not in storage: | ||
| 230 | + raise ValueError(f"Checkpoint tensor chunk has no storage: {name}") | ||
| 231 | + for old_offsets, old_sizes in chunks: | ||
| 232 | + if all( | ||
| 233 | + a < b + y and b < a + x | ||
| 234 | + for a, x, b, y in zip(offsets, sizes, old_offsets, old_sizes, strict=True) | ||
| 235 | + ): | ||
| 236 | + raise ValueError(f"Checkpoint tensor chunks overlap: {name}") | ||
| 237 | + chunks.append((offsets, sizes)) | ||
| 238 | + volume += current | ||
| 239 | + if volume != prod(entry.size): | ||
| 240 | + raise ValueError(f"Checkpoint tensor chunks are incomplete: {name}") | ||
Atorchtitan_npu/extensions/torchtitan/experiments/torchft/last_words/checkpoint_validation.py+420-0File content is under review, please try again later
| @@ -0,0 +1,162 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +"""HTTP transport and session clients for the torchtitan-npu save service. | ||
| 5 | + | ||
| 6 | +This module must remain standard-library-only: control imports cannot initialize | ||
| 7 | +torch/NPU. It uses direct HTTP(S) RPC and does not own training processes. | ||
| 8 | +""" | ||
| 9 | + | ||
| 10 | +import http.client | ||
| 11 | +import ipaddress | ||
| 12 | +import json | ||
| 13 | +import os | ||
| 14 | +import ssl | ||
| 15 | +import threading | ||
| 16 | +import time | ||
| 17 | +from pathlib import Path | ||
| 18 | +from urllib.parse import urlsplit | ||
| 19 | + | ||
| 20 | +RPC_PROTOCOL_VERSION = 6 | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def validate_service_address(address, *, allow_port_zero=False): | ||
| 24 | + """Parse a root service URL without opening sockets or loading credentials.""" | ||
| 25 | + parsed = urlsplit(address) | ||
| 26 | + if ( | ||
| 27 | + parsed.scheme not in {"http", "https"} | ||
| 28 | + or not parsed.hostname | ||
| 29 | + or parsed.username is not None | ||
| 30 | + or parsed.password is not None | ||
| 31 | + or parsed.query | ||
| 32 | + or parsed.fragment | ||
| 33 | + or parsed.path not in ("", "/") | ||
| 34 | + or parsed.port is None | ||
| 35 | + or (parsed.port == 0 and not allow_port_zero) | ||
| 36 | + or any(character.isspace() for character in address) | ||
| 37 | + ): | ||
| 38 | + raise ValueError("Provide an HTTP(S) service root URL with an explicit port and no credentials") | ||
| 39 | + try: | ||
| 40 | + loopback = ipaddress.ip_address(parsed.hostname).is_loopback | ||
| 41 | + except ValueError: | ||
| 42 | + loopback = parsed.hostname == "localhost" | ||
| 43 | + if parsed.scheme == "http" and not loopback: | ||
| 44 | + raise ValueError("Non-loopback coordination requires HTTPS with mutual TLS") | ||
| 45 | + return parsed | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class ServiceClient: | ||
| 49 | + """Bounded persistent HTTP transport; imports no tensor or native extension.""" | ||
| 50 | + | ||
| 51 | + def __init__(self, address): | ||
| 52 | + parsed = validate_service_address(address) | ||
| 53 | + self.connection: http.client.HTTPConnection | ||
| 54 | + if parsed.scheme == "https": | ||
| 55 | + files = [os.environ.get(f"LAST_WORDS_SERVICE_{name}_FILE", "") for name in ("CA", "CERT", "KEY")] | ||
| 56 | + if not all(files): | ||
| 57 | + raise ValueError("HTTPS coordination requires LAST_WORDS_SERVICE_CA_FILE, CERT_FILE and KEY_FILE") | ||
| 58 | + context = ssl.create_default_context(cafile=files[0]) | ||
| 59 | + context.load_cert_chain(certfile=files[1], keyfile=files[2]) | ||
| 60 | + self.connection = http.client.HTTPSConnection(parsed.hostname, parsed.port, timeout=2, context=context) | ||
| 61 | + else: | ||
| 62 | + self.connection = http.client.HTTPConnection(parsed.hostname, parsed.port, timeout=2) | ||
| 63 | + self.lock = threading.Lock() | ||
| 64 | + | ||
| 65 | + def call(self, document, deadline) -> str: | ||
| 66 | + with self.lock: | ||
| 67 | + delay = 0.1 | ||
| 68 | + while (remaining := deadline - time.monotonic()) > 0: | ||
| 69 | + self.connection.timeout = min(2.0, remaining) | ||
| 70 | + if self.connection.sock is not None: | ||
| 71 | + self.connection.sock.settimeout(self.connection.timeout) | ||
| 72 | + try: | ||
| 73 | + self.connection.request( | ||
| 74 | + "POST", "/coordinate", body=document.encode(), headers={"Content-Type": "application/json"} | ||
| 75 | + ) | ||
| 76 | + response = self.connection.getresponse() | ||
| 77 | + raw = response.read(8 * 1024 * 1024 + 1) | ||
| 78 | + if len(raw) > 8 * 1024 * 1024: | ||
| 79 | + raise RuntimeError("Coordinator response exceeds limit") | ||
| 80 | + result = raw.decode() | ||
| 81 | + if response.status == 503: | ||
| 82 | + raise ConnectionError("Coordinator temporarily unavailable") | ||
| 83 | + if response.status != 200: | ||
| 84 | + raise RuntimeError(json.loads(result).get("error", "Coordinator request failed")) | ||
| 85 | + return result | ||
| 86 | + except (OSError, http.client.HTTPException): | ||
| 87 | + # The server may already have committed this report. Retry | ||
| 88 | + # exactly the same sequence and payload, including on 503. | ||
| 89 | + self.connection.close() | ||
| 90 | + time.sleep(min(delay, max(0, deadline - time.monotonic()))) | ||
| 91 | + delay = min(1.0, 2 * delay) | ||
| 92 | + except BaseException: | ||
| 93 | + self.connection.close() | ||
| 94 | + raise | ||
| 95 | + raise TimeoutError("Coordinator transport deadline expired") | ||
| 96 | + | ||
| 97 | + def close(self): | ||
| 98 | + with self.lock: | ||
| 99 | + self.connection.close() | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +class WorkerSessionClient: | ||
| 103 | + def __init__(self, run_id, replica, rank): | ||
| 104 | + self.session = json.loads(Path(os.environ["LAST_WORDS_SESSION_FILE"]).read_text()) | ||
| 105 | + session = self.session | ||
| 106 | + if ( | ||
| 107 | + session.get("version") != RPC_PROTOCOL_VERSION | ||
| 108 | + or session.get("run_id") != run_id | ||
| 109 | + or session.get("replica") != replica | ||
| 110 | + ): | ||
| 111 | + raise ValueError("Session file does not match this run/replica/protocol") | ||
| 112 | + if not 0 <= rank < session["world_size"]: | ||
| 113 | + raise ValueError("Rank outside registered replica") | ||
| 114 | + self.client = ServiceClient(session["address"]) | ||
| 115 | + self.identity = dict( | ||
| 116 | + version=RPC_PROTOCOL_VERSION, | ||
| 117 | + run_id=run_id, | ||
| 118 | + instance=session["instance"], | ||
| 119 | + token=session["token"], | ||
| 120 | + replica=replica, | ||
| 121 | + rank=rank, | ||
| 122 | + ) | ||
| 123 | + self.lock = threading.Lock() | ||
| 124 | + self.seq = 0 | ||
| 125 | + self.snapshot = None | ||
| 126 | + self.ready = None | ||
| 127 | + | ||
| 128 | + def report(self, status, requested, *, deadline=None): | ||
| 129 | + if deadline is None: | ||
| 130 | + deadline = time.monotonic() + self.session["heartbeat_seconds"] | ||
| 131 | + with self.lock: | ||
| 132 | + self.seq += 1 | ||
| 133 | + status = dict(status, requested=requested, ready=self.ready) | ||
| 134 | + document = dict(self.identity, seq=self.seq, op="shard_report", data=status) | ||
| 135 | + snapshot = json.loads(self.client.call(json.dumps(document), deadline)) | ||
| 136 | + if any(snapshot.get(key) != self.identity[key] for key in ("version", "run_id", "instance")): | ||
| 137 | + raise RuntimeError("Coordinator response belongs to another save session") | ||
| 138 | + self.snapshot = snapshot | ||
| 139 | + return snapshot | ||
| 140 | + | ||
| 141 | + def get_cached_snapshot(self): | ||
| 142 | + # Replies replace the entire snapshot. A reader may still need the | ||
| 143 | + # preceding freeze snapshot while the next heartbeat is being retried. | ||
| 144 | + return self.snapshot | ||
| 145 | + | ||
| 146 | + def poll(self): | ||
| 147 | + deadline = time.monotonic() + self.session["heartbeat_seconds"] | ||
| 148 | + with self.lock: | ||
| 149 | + self.seq += 1 | ||
| 150 | + document = json.dumps(dict(self.identity, seq=self.seq, op="poll", data=None)) | ||
| 151 | + snapshot = json.loads(self.client.call(document, deadline)) | ||
| 152 | + if any(snapshot.get(key) != self.identity[key] for key in ("version", "run_id", "instance")): | ||
| 153 | + raise RuntimeError("Coordinator poll belongs to another save session") | ||
| 154 | + self.snapshot = snapshot | ||
| 155 | + return snapshot | ||
| 156 | + | ||
| 157 | + def set_ready(self, state, signature): | ||
| 158 | + with self.lock: | ||
| 159 | + ready = dict(state=state, signature=signature) | ||
| 160 | + if self.ready is not None and self.ready != ready: | ||
| 161 | + raise RuntimeError("Cannot change frozen ready state") | ||
| 162 | + self.ready = ready | ||
| @@ -0,0 +1,101 @@ | |||
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
| 2 | +# All rights reserved. | ||
| 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 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 8 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 9 | + | ||
| 10 | +"""Rank-local random streams committed with each logical replica's data cursor.""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +import copy | ||
| 15 | +import random | ||
| 16 | + | ||
| 17 | +import numpy as np | ||
| 18 | +import torch | ||
| 19 | + | ||
| 20 | +RNG_STATE = "last_words_rng" | ||
| 21 | +RNG_SCHEMA = 1 | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class RNGCheckpointState: | ||
| 25 | + """Export a frozen training-thread snapshot, never a background RNG read. | ||
| 26 | + | ||
| 27 | + DCP keys are disjoint across replica-local ranks. Saving one replicated key | ||
| 28 | + for different rank-local generators would silently keep only one stream. | ||
| 29 | + Only the current device is read; no other device context is initialized. | ||
| 30 | + """ | ||
| 31 | + | ||
| 32 | + device: torch.device | ||
| 33 | + | ||
| 34 | + def __init__(self, device: torch.device, rank: int): | ||
| 35 | + # torch.device is an instance value here, not a class descriptor. | ||
| 36 | + self.device = torch.device(device) # pyrefly: ignore [read-only] | ||
| 37 | + self.key = f"rank_{rank}" | ||
| 38 | + self._snapshot = None | ||
| 39 | + | ||
| 40 | + def capture(self): | ||
| 41 | + algorithm, keys, position, has_gaussian, gaussian = np.random.get_state(legacy=True) | ||
| 42 | + assert isinstance(keys, np.ndarray) | ||
| 43 | + state = dict( | ||
| 44 | + schema=RNG_SCHEMA, | ||
| 45 | + device_type=self.device.type, | ||
| 46 | + python=random.getstate(), | ||
| 47 | + cpu=torch.get_rng_state().clone(), | ||
| 48 | + numpy=dict( | ||
| 49 | + algorithm=algorithm, | ||
| 50 | + keys=torch.from_numpy(keys.astype(np.int64)), | ||
| 51 | + position=position, | ||
| 52 | + has_gaussian=has_gaussian, | ||
| 53 | + gaussian=gaussian, | ||
| 54 | + ), | ||
| 55 | + ) | ||
| 56 | + if self.device.type != "cpu": | ||
| 57 | + device_module = getattr(torch, self.device.type) | ||
| 58 | + state["accelerator"] = device_module.get_rng_state(self.device).cpu().clone() | ||
| 59 | + self._snapshot = state | ||
| 60 | + | ||
| 61 | + def state_dict(self): | ||
| 62 | + if self._snapshot is None: | ||
| 63 | + raise RuntimeError("RNG state must be captured at a complete training boundary") | ||
| 64 | + return {self.key: copy.deepcopy(self._snapshot)} | ||
| 65 | + | ||
| 66 | + def load_state_dict(self, state): | ||
| 67 | + value = state[self.key] | ||
| 68 | + if value["schema"] != RNG_SCHEMA or value["device_type"] != self.device.type: | ||
| 69 | + raise ValueError("Checkpoint RNG schema or device type differs") | ||
| 70 | + if self.device.type != "cpu": | ||
| 71 | + stream = value.get("accelerator") | ||
| 72 | + if ( | ||
| 73 | + not isinstance(stream, torch.Tensor) | ||
| 74 | + or stream.dtype != torch.uint8 | ||
| 75 | + or stream.ndim != 1 | ||
| 76 | + or stream.numel() == 0 | ||
| 77 | + ): | ||
| 78 | + raise ValueError("Checkpoint accelerator RNG stream is missing or invalid") | ||
| 79 | + self._snapshot = copy.deepcopy(value) | ||
| 80 | + | ||
| 81 | + def restore(self): | ||
| 82 | + state = self.state_dict()[self.key] | ||
| 83 | + random.setstate(state["python"]) | ||
| 84 | + torch.set_rng_state(state["cpu"]) | ||
| 85 | + numpy = state["numpy"] | ||
| 86 | + np.random.set_state( | ||
| 87 | + ( | ||
| 88 | + numpy["algorithm"], | ||
| 89 | + numpy["keys"].numpy().astype(np.uint32), | ||
| 90 | + numpy["position"], | ||
| 91 | + numpy["has_gaussian"], | ||
| 92 | + numpy["gaussian"], | ||
| 93 | + ) | ||
| 94 | + ) | ||
| 95 | + if self.device.type != "cpu": | ||
| 96 | + getattr(torch, self.device.type).set_rng_state(state["accelerator"], self.device) | ||
| 97 | + | ||
| 98 | + def fork(self): | ||
| 99 | + other = RNGCheckpointState(self.device, int(self.key.removeprefix("rank_"))) | ||
| 100 | + other.load_state_dict(self.state_dict()) | ||
| 101 | + return other | ||
| @@ -0,0 +1,633 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved. | ||
| 2 | +# This source code is licensed under the BSD-style license found in LICENSE. | ||
| 3 | + | ||
| 4 | +"""Emergency-save authority, independent of process launch, TorchFT and torch. | ||
| 5 | + | ||
| 6 | +All shard aggregation and writer decisions are serialized by one lock. Server | ||
| 7 | +incarnations are deliberately ephemeral: losing this process fails the attempt. | ||
| 8 | +Writer ranks acknowledge publication before rank zero validates the checkpoint. | ||
| 9 | +This service never launches, terminates or restarts training. A failed writer is never replaced. | ||
| 10 | +""" | ||
| 11 | + | ||
| 12 | +import argparse | ||
| 13 | +import copy | ||
| 14 | +import hmac | ||
| 15 | +import ipaddress | ||
| 16 | +import json | ||
| 17 | +import logging | ||
| 18 | +import math | ||
| 19 | +import os | ||
| 20 | +import secrets | ||
| 21 | +import socket | ||
| 22 | +import ssl | ||
| 23 | +import threading | ||
| 24 | +import time | ||
| 25 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| 26 | +from pathlib import Path | ||
| 27 | +from typing import Any, cast | ||
| 28 | + | ||
| 29 | +if __package__: | ||
| 30 | + from .client import RPC_PROTOCOL_VERSION, validate_service_address | ||
| 31 | +else: | ||
| 32 | + import runpy | ||
| 33 | + | ||
| 34 | + _client = runpy.run_path(str(Path(__file__).with_name("client.py"))) | ||
| 35 | + validate_service_address = _client["validate_service_address"] | ||
| 36 | + RPC_PROTOCOL_VERSION = _client["RPC_PROTOCOL_VERSION"] | ||
| 37 | + | ||
| 38 | +MAX_REQUEST_BYTES = 1024 * 1024 | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def require(condition, message): | ||
| 42 | + if not condition: | ||
| 43 | + raise ValueError(message) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def is_uint64(value): | ||
| 47 | + return type(value) is int and 0 <= value < 2**64 | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def sync_directory(directory): | ||
| 51 | + fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY) | ||
| 52 | + try: | ||
| 53 | + os.fsync(fd) | ||
| 54 | + finally: | ||
| 55 | + os.close(fd) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +class Session: | ||
| 59 | + def __init__(self, config, now): | ||
| 60 | + self.config = config | ||
| 61 | + require(is_uint64(config["world_size"]) and 1 <= config["world_size"] <= 64, "invalid shard count") | ||
| 62 | + tokens = config["replica_tokens"] | ||
| 63 | + require(isinstance(tokens, list) and 1 <= len(tokens) <= 64, "invalid replica count") | ||
| 64 | + require( | ||
| 65 | + all(isinstance(token, str) and len(token) >= 32 for token in tokens), | ||
| 66 | + "invalid replica token", | ||
| 67 | + ) | ||
| 68 | + require(len(set(tokens)) == len(tokens), "duplicate replica token") | ||
| 69 | + for key in ("heartbeat_seconds", "startup_seconds", "timeout_seconds"): | ||
| 70 | + value = config[key] | ||
| 71 | + require(type(value) in (float, int) and math.isfinite(value) and value > 0, "invalid time budget") | ||
| 72 | + self.started = now | ||
| 73 | + self.fault_at = None | ||
| 74 | + self.reason = "" | ||
| 75 | + self.phase = "RUNNING" | ||
| 76 | + self.reports: dict[tuple[int, int], dict[str, Any]] = {} | ||
| 77 | + self.excluded = set() | ||
| 78 | + self.finished_replicas = set() | ||
| 79 | + self.exhausted_inputs: dict[int, int] = {} | ||
| 80 | + self.latest_ready_step = 0 | ||
| 81 | + self.resume_choices: dict[int, str] = {} | ||
| 82 | + self.grant = None | ||
| 83 | + self.round = 0 | ||
| 84 | + self.result = None | ||
| 85 | + self.revision = 1 | ||
| 86 | + | ||
| 87 | + def request_terminal_save(self, now, reason): | ||
| 88 | + if self.fault_at is None and self.result is None: | ||
| 89 | + self.fault_at, self.reason, self.phase = now, reason, "PREPARING" | ||
| 90 | + self.revision += 1 | ||
| 91 | + | ||
| 92 | + def finish(self, error=""): | ||
| 93 | + if self.result is None: | ||
| 94 | + self.phase = "FAILED" if error else "SUCCEEDED" | ||
| 95 | + self.result = dict( | ||
| 96 | + success=not error, | ||
| 97 | + error=error, | ||
| 98 | + round=self.round, | ||
| 99 | + replica_id=self.grant["replica_id"] if self.grant else None, | ||
| 100 | + ) | ||