Closed
test: 增加 TorchFT NPU 定向 UT 与门禁 #679
test: 增加 TorchFT NPU 定向 UT 与门禁 #679
Closed
zhangyifan999Add on Sep 1Closed at Oct 12
zhangyifan999
zhangyifan999Collaborators
Sep 1

描述

本 PR 是原 PR 644 的第 5 层,为前四层功能增加定向单元测试并接入仓库标准 UT 门禁,同时提供 4 卡单机 TorchFT ST。该层不修改生产代码。

目标分支为 master。合入依赖:#675、#676、#677 和 #678。

调用流程

  1. 标准门禁通过 .ci/setup_torchtitan.sh 读取 requirements.txt 中固定的 Torchtitan commit 并准备源码。
  2. .ci/unit_test.sh 安装开发依赖和与固定 TorchFT commit 对应的 nightly wheel。
  3. pytest 收集 tests/unit_tests/torchft 下三个测试文件。
  4. test_process_group.py 验证 #675 factory 与 #676 HCCL PG 的注册边界。
  5. test_rejoin.py 直接驱动 #676 Work tracker、device recovery、state staging 和 replay 状态机。
  6. test_torchft.py 从 #678 DeepSeek recipe/CLI 进入 #677 Manager/Trainer/Optimizer/Checkpoint,覆盖完整集成链。
  7. .ci/smoke_test.sh 通过 --test_suite torchft 进入 integration runner;torchft.py 在 4 张 NPU 上编排 2 replicas x 2 ranks,分别验证正常训练和 rejoin。

IntegrationTestRunner 扩展点

仓库原有 run_single_test() 每个 case 只启动一次 scripts/run_train.sh,适合普通单训练任务。TorchFT ST 需要同时管理 Lighthouse、两个独立 torchrun、故障 replica 的退出与 replacement,因此为 OverrideDefinitions 增加可选的 runner 回调,并用 IntegrationTestRunner Protocol 约束其签名。

只有显式设置 runner 的 TorchFT case 才绕过默认单进程路径;现有模型 case 的命令拼装、golden loss 和 TensorBoard 检查保持不变。TorchFT 的具体编排由 _TorchFTScenarioRunner 实现,调用关系为:

run_tests.py -> build_torchft_test_list() -> run_single_test()
             -> run_torchft_case() -> _TorchFTScenarioRunner
             -> Lighthouse + replica 0 + replica 1
             -> optional kill/relaunch + log validation + cleanup
[standard UT job]
        |
        v
[.ci/setup_torchtitan.sh: requirements-pinned source]
        |
        v
[.ci/unit_test.sh: install dev deps + torchft-nightly]
        |
        +--------------------+--------------------+
        |                    |                    |
        v                    v                    v
[test_process_group.py] [test_rejoin.py]   [test_torchft.py]
        |                    |                    |
        v                    v                    v
[#675 registry +       [#676 Work/event/  [#678 recipe/delayed import]
 #676 HCCL PG]          rejoin/replay]             |
                                                  v
                                      [#677 trainer/optimizer/
                                       checkpoint integration]

[single-node NPU ST]
        |
        +-----------------------------+
        |                             |
        v                             v
[training: 2 x 2]          [rejoin: kill + relaunch replica 1]
        |                             |
        v                             v
[both replicas finish]     [HCCL stop/restart + replay + healing]

测试调用链与断言边界

  • ProcessGroup 测试只检查注册、timeout 和同步 quorum 配置,不模拟真实 HCCL 设备。
  • Rejoin 测试通过 mock stop/restart 和 NPU completion event 验证状态机、并发与 generation,不替代真实多卡实验。
  • Integration 测试验证组件初始化顺序、梯度 hook、MoE rollback、DCP owner、data-only DCP 和 RNG 恢复。
  • 单机 ST 使用真实 Lighthouse、两个独立 torchrun 和 HCCL ProcessGroup;故障恢复场景不通过 mock 或训练代码 hook 注入故障。
  • 真实组合 tree 另在固定 requirements 容器运行,结果为 37 passed in 39.80s。

文件与函数

.ci/unit_test.sh

  • 无 shell 函数变更;在标准 CPU UT job 中安装与 optional dependency 对应的 torchft-nightly==2026.7.17 wheel,避免 source build 依赖 Rust/maturin。

.ci/smoke_test.sh

  • 安装固定版本的 torchft-nightly,先通过 --test_suite torchft 运行 TorchFT ST,再执行既有 models suite。

tests/integration_tests/__init__.py

  • IntegrationTestRunner:约束需要自定义进程编排的 integration case 回调签名。
  • OverrideDefinitions.runner:可选回调;未设置时既有 case 的执行行为不变。

tests/integration_tests/run_tests.py

  • _TEST_SUITES_FUNCTION["torchft"]:注册 TorchFT suite。
  • run_single_test():case 设置 runner 时调用自定义回调并返回,否则继续使用原来的单次 scripts/run_train.sh 和 loss 检查路径。

tests/integration_tests/torchft.py

  • _Settings.from_environment():读取模型、数据、设备、端口、步数和超时设置。
  • _TorchFTScenarioRunner:管理 Lighthouse、两个 torchrun 进程树、日志、超时和清理。
  • _run_training():验证 2 replicas x 2 ranks 正常同步训练。
  • _run_rejoin():在 step 2 后终止 replica 1,再以同一 replica ID 拉起 replacement;要求 survivor 完成 stop/restart 和 step replay,replacement 完成 peer healing。
  • run_torchft_case():把通用 runner 回调转换为具体 TorchFT scenario。
  • build_torchft_test_list():注册 torchft_training 和 torchft_rejoin 两个 4 卡 case。

tests/unit_tests/torchft/test_process_group.py

  • _config():构造最小 NPU FT manager 配置。
  • test_registered_hccl_process_group_contract():验证 registry 能创建 HCCL wrapper、透传 timeout 并暴露稳定 backend name。
  • 内部 capture_timeout():截获 ProcessGroupWrapper 初始化 timeout。
  • test_npu_process_group_config_contract():覆盖 HCCL/同步 quorum 合法配置和 backend、半同步、replica 数非法配置。

tests/unit_tests/torchft/test_rejoin.py

  • _configured_rejoin_process_group():构造已启用 rejoin 的最小 HCCL PG。
  • _tracked_work_fixture():构造带 timer 的 tracked Work 测试夹具。
  • TestNpuRecoverySnapshot.test_peer_healing_state_becomes_the_local_committed_snapshot():验证 peer state 应用后成为本地 committed snapshot。
  • test_prepare_healing_snapshot_materializes_all_state_on_training_thread():验证 FSDP/NPU state 在训练线程 staging。
  • test_manager_state_dict_materializes_deferred_state_for_peer_healing():验证 recovery worker 读取的是 materialized CPU state。
  • _make_replay_trainer():构造最小 replay trainer。
  • test_replay_restores_batches_and_rng_without_refetching():验证重放不重新读 dataloader,并恢复 batch 与 RNG。
  • test_replay_waits_for_device_restart_before_next_attempt():验证下一次 attempt 前等待 restart、清理失败状态并恢复 committed state。
  • 该用例内部 run_attempt():第一次 attempt 注入 replay error,第二次验证 restart 后从缓存继续。
  • test_trainer_replay_caches_every_pipeline_microbatch():验证 PP/gradient accumulation 会缓存完整 step 的所有 microbatch。
  • test_work_watchdog_is_scoped_to_transaction_generation():验证旧 generation timer 不会 abort 新 quorum。
  • test_work_remains_active_until_completion_event_finishes():验证 Python Work 完成后仍等待 NPU event。
  • test_incomplete_work_remains_active():验证未完成 event 保持 active。
  • test_failed_work_remains_active():验证 query 失败按 active 处理,避免误判安全。
  • test_abort_restarts_device_only_for_active_work():验证无 active Work 只重建 PG,有 active Work 才 stop/restart device。
  • test_reconfigure_replays_completed_but_uncommitted_step():验证 communicator 重配时未提交 step 必须 replay。
  • test_concurrent_abort_runs_device_recovery_once():验证并发 abort 只执行一次整设备恢复。
  • 该用例内部 stop_device():用事件阻塞模拟慢速整设备停止,制造两个 abort 并发窗口。
  • test_container_wraps_the_nonrecursive_inner_adapter():验证 optimizer container 使用非递归 adapter。
  • test_initial_and_recovery_quorum_finish_before_zero_grad():验证 initial/recovery quorum 在下一次 forward 前完成。
  • test_aborted_quorum_cannot_commit_after_process_group_reconfigure():验证旧 quorum future 不能在新 generation 提交 optimizer step。

tests/unit_tests/torchft/test_torchft.py

  • _initialize_fault_tolerant_trainer():用 mock 上游构造函数测试 NPU trainer 初始化顺序。
  • test_deepseek_v4_config_late_binds_torchft_after_enable():验证普通 recipe 只在 enable 后派生 FT 配置且保留基线字段。
  • test_deepseek_v4_config_does_not_eagerly_import_torchft():验证 TorchFT 关闭时进程不导入 torchft。
  • test_deepseek_v4_config_exposes_torchft_cli_without_preimport():验证 CLI 可解析 TorchFT 参数且保持延迟导入。
  • test_deepseek_v4_torchft_recipe_defers_implementation_imports():在独立子进程加载显式 FT recipe,验证只预置 extension/checkpoint,配置解析期不导入 NPU TorchFT 实现。
  • test_npu_ft_trainer_initializes_configured_spmd_backend():验证 FT trainer 使用 NPU 配置的 distributed backend。
  • test_model_overrides_run_after_update_and_before_build():验证模型 override 顺序位于 config update 后、组件 build 前。
  • 内部 apply_override():记录 override 执行顺序。
  • 内部 initialize_upstream():模拟并记录上游 trainer 初始化。
  • 测试模型的 update_from_config():记录模型配置更新发生在 override/build 之前。
  • test_cuda_graph_validation_runs_without_model_overrides():验证无 override 时仍执行 graph 配置校验。
  • 该用例内部 initialize_upstream():模拟上游初始化并检查校验后的配置。
  • 该用例模型的 update_from_config():记录无 override 场景的 config update。
  • test_replicate_dp_hook_uses_stream_ordered_cross_replica_all_reduce():验证纯 DP replicate 路径安装跨 replica hook,并以目标 ProcessGroup 和 ReduceOp.AVG 调用一次 stream-ordered AllReduce;不再断言 bucket 前后的 .item()。
  • _run_abort_path()、test_abort_restarts_device_only_for_active_work()、test_abort_without_active_work_uses_process_group_abort():分别复用 abort 执行夹具并独立验证 active Work 的整设备恢复路径与无 active Work 的普通 PG abort 路径。
  • FakeReplicateModule.__init__():初始化测试用 hook 槽位。
  • FakeReplicateModule._get_fsdp_state():提供最小单 parameter-group FSDP state。
  • FakeReplicateModule.set_all_reduce_hook():记录被安装的跨 replica hook。
  • test_loss_process_group_averages_float_sum_only():验证 loss SUM 转 AVG,而非浮点或其他 op 不被改写。
  • test_rejected_quorum_syncs_moe_counts_then_rolls_back_bias():验证 MoE counts 先同步,quorum 拒绝后 bias 回滚。
  • 内部 initialize_base():模拟普通 OptimizersContainer 初始化。
  • 内部 update_expert_bias():记录并模拟 MoE bias 更新。
  • test_persistent_checkpoint_has_single_writer_and_restores_live_lr():验证完整 DCP 单 writer 及 load 后 LR 恢复。
  • test_peer_healing_without_persistent_checkpoint_does_not_require_states_attribute():验证关闭持久化 DCP 时 peer healing 仍注册完整训练状态。
  • test_dataloader_checkpoint_storage_does_not_enable_persistent_checkpoint():验证 data-only DCP 不会误开启完整 checkpoint。
  • 内部 initialize_storage():截获 data-only storage 配置。
  • test_torch_rng_state_restores_loaded_cpu_and_npu_streams():验证 checkpoint load 后恢复 CPU/NPU RNG。

类型

Checklist:

如何测试

pytest -q tests/unit_tests/torchft

4 卡单机 ST:

python -m tests.integration_tests.run_tests \
    test_reports/torchft \
    --test_suite torchft \
    --ngpu 4

# 单独运行 rejoin
python -m tests.integration_tests.run_tests \
    test_reports/torchft_rejoin \
    --test_suite torchft \
    --test_name torchft_rejoin \
    --ngpu 4

同时验证:

git diff --check master...torchft-pr644-05-tests-gate

拆分组合验证结果(固定 master requirements 环境):

47 passed in 53.89s
eager 4→3→4 active Work:完成 100 step,公共 step loss/grad norm 逐行一致
torch.compile 4→3→4 active Work:完成 160 step,replacement 重编译并完成 peer healing,公共 step loss/grad norm 逐行一致

4 卡真实 NPU ST(2026-09-02,NPU_DEVICES=2,3,4,5):

training: 2 replicas x 2 ranks,双方完成 step 1-3;每步 loss/grad_norm 一致;双方 Training completed
rejoin:   step 2 后终止 replica 1 进程树;survivor 完成 stop/reinit 1 个本地 NPU process group/restart 和 step replay;
          replacement 完成 peer healing;双方完成 12-step 训练并 Training completed
fatal:    survivor/replacement 均无 collective watchdog timeout 或未处理 traceback

组合分支与原 PR 644 aa41bfb 的 git diff --exit-code 返回 0。

其他信息

该 PR 作为 stacked PR 的验收层。前三个代码 PR 的 CI 可运行仓库原门禁;新增 TorchFT 定向用例在本层进入标准 UT job。

likedislike
The current Pull Request has been closed by xuyujun.
zhangyifan999zhangyifan999Collaborators
Sep 1 Created pull request, commit e4983a0e
atomgit-bot
atomgit-botCollaborators
Sep 1 Comments:

变更摘要

本 PR 是 stacked PR 644 的第 5 层(验收层),不修改任何生产代码,仅为前四层 TorchFT NPU 功能新增定向单元测试,并将其接入仓库标准 UT 门禁。测试覆盖 torchtitan_npu 中 TorchFT 相关的进程组创建与配置校验、rejoin 恢复/重放/看门狗机制、trainer 初始化顺序、checkpoint 与 RNG 恢复等行为,通过 FaultTolerantTrainerEx、ManagerEx、ProcessGroupHCCLEx、OptimizerWrapperEx、TorchFTCheckpointManagerEx 等扩展类的 mock 构造验证。

主要改动

  • CI 门禁接入 torchft-nightly wheel:.ci/unit_test.sh 在标准 CPU UT job 中新增 pip install "torchft-nightly==2026.7.17",该版本与 pyproject.toml 中 optional dependency 固定提交一致,使 CPU UT 无需 Rust/maturin 工具链即可 source build。
  • 新增进程组契约测试(tests/unit_tests/torchft/test_process_group.py):验证 _hccl_group_id() 的 group id 生成、manager_module.create_process_group("hccl", timeout) 返回 ProcessGroupHCCLEx 且 timeout 透传到 ProcessGroupWrapper.__init__、backend name 稳定为 "torchft-hccl";并以参数化用例覆盖 validate_npu_process_group_config 对非 hccl backend、非同步 quorum 的 semi_sync_method、非法 min_replica_size 抛 ValueError 的校验。
  • 新增 rejoin 恢复机制测试(tests/unit_tests/torchft/test_rejoin.py):覆盖 ManagerEx 的 peer healing snapshot 物化(prepare_healing_snapshot 在训练线程调用全部 state dict 并 staging、_manager_state_dict 读取 materialized CPU state);_ReplayableStepIterator 重放不重读 dataloader、恢复 batch 与 RNG、按 microbatch 数量(gradient accumulation × PP microbatch)缓存完整 step;ProcessGroupHCCLEx 的 rejoin workaround(watchdog timer 限定在旧 generation、abort 仅在有 active work 时 stop_device/restart_device 且并发 abort 只恢复一次、重配时未提交 step 必须 replay);OptimizerWrapperEx 在 zero_grad 前完成 initial/recovery quorum,且 _StepReplayError 阻止旧 quorum 在新 generation 提交。
  • 新增 trainer/checkpoint 定向测试(tests/unit_tests/torchft/test_torchft.py):验证 deepseek_v4 配置仅在 extension.torchft.enable 后派生 FT 配置并保留基线字段、TorchFT 关闭时子进程不导入 torchft 但 CLI 可解析 TorchFT 参数;模型 override 顺序位于 config update 之后、组件 build 之前且 _validate_cuda_graphs 始终执行;maybe_set_all_reduce_hook 在纯 DP ReplicateModule 路径安装并物化跨 replica AVG all-reduce hook;LossManagedProcessGroupEx 仅将浮点 loss 的 SUM 改写为 AVG(int token count 保持 SUM);quorum 被拒时先同步 MoE counts 再回滚 expert_bias_E;持久化 checkpoint 仅单 writer 保存且 load 后恢复 LR;data-only DCP 不开启持久化 checkpoint;_TorchRngState.load_state_dict 恢复 CPU 与 NPU 的 RNG stream。
likedislike
Incorrect?
atomgit-bot
atomgit-botCollaborators
Sep 1 Comments:

代码审查

✅ 未发现问题

likedislike
Incorrect?
CANN-robotCANN-robotCollaborators
Sep 1 Added label: cann-cla/yes
CANN-robot
CANN-robotCollaborators
Sep 1 Comments:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here.
You can get sig-info at here.
You can self-configure the PR merge rules for this repository. For more details, please refer to Here.
For more, you also can visit HICANN.


PR Approval Progress

⚠️ This PR does not yet meet the following requirements:lgtm (requires ≥ 2 person(s) per module)、approve (requires ≥ 1 person(s) per module)

Module Approval Details

module lgtm status approve status
repo-cann/torchtitan-npu ❌ (0/2)(You can also ask: xuyujun, zhaowei1936, 张德鹏, 徐道鸿, wanghui0) ❌ (0/1)(You can also ask: hwcaifubi, panchao-gitcode, lrwei0709, 张德鹏, wanghui0)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

zhangyifan999, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
182 messages are collapsed here。 See more
zhangyifan999zhangyifan999Collaborators
Sep 11 Pre merge succeeded (commit_id: 6e9fd957bf28e828c21dc23e8878e0d1ac3633b6)
CANN-robotCANN-robotCollaborators
Sep 11 Removed label: cann-cla/yes
CANN-robotCANN-robotCollaborators
Sep 11 Added label: cann-cla/yes
xuyujunxuyujunCollaborators
Oct 12 Close pull request
xuyujun
xuyujunCollaborators
Oct 12 Comments:

【关闭原因】TorchFT NPU 定向 UT 与门禁已由 #828/#906(已合入 master)取代,故关闭。

likedislike