Merged
fix: support distributed seed checkpoints for numerical alignment #1014
fix: support distributed seed checkpoints for numerical alignment #1014
Merged
1Fire4Add on Oct 13
Total: 5 files changed+358-14
@@ -12,6 +12,7 @@ scripts/numerical_alignment/
12├── README.md12├── README.md
13├── compare_module_example.py # RMSNorm 前向输出和梯度对比13├── compare_module_example.py # RMSNorm 前向输出和梯度对比
14├── loss_compare.py # 两个 Git 版本的 loss、grad_norm 对比14├── loss_compare.py # 两个 Git 版本的 loss、grad_norm 对比
15+├── create_seed_checkpoint.py # 按 baseline 并行布局保存 step-0
15├── requirements.txt # 推理基线的额外依赖16├── requirements.txt # 推理基线的额外依赖
16├── configs/17├── configs/
17│ └── dsv4_4l.json # DSV4 四层、四专家推理配置18│ └── dsv4_4l.json # DSV4 四层、四专家推理配置
@@ -188,6 +189,22 @@ python scripts/numerical_alignment/loss_compare.py HEAD~1 HEAD \
188两侧卡数不同时使用 `--baseline-ngpus` / `--test-ngpus`,并通过各自 options 设置对应并行拓扑。189两侧卡数不同时使用 `--baseline-ngpus` / `--test-ngpus`,并通过各自 options 设置对应并行拓扑。
189比较并行策略时,还需保证全局 batch、输入数据和训练配置一致。190比较并行策略时,还需保证全局 batch、输入数据和训练配置一致。
190 191 
192+#### Seed checkpoint 与运行环境
193+ 
194+默认通过同一份 seed checkpoint 初始化两侧模型,创建方式由 `--seed-mode` 指定:
195+ 
196+- `unsharded`:默认模式,使用单进程 CPU 初始化完整权重。
197+- `distributed`:使用 baseline 的卡数、runner、配置和 `--baseline-options` 构建并行模型,需要预留与 baseline 相同的卡数和显存资源。Engram 等原生 checkpoint 依赖并行布局的模型可使用该模式。
198+ 
199+`--baseline-env` / `--test-env` 分别注入 `KEY=VALUE[,...]` 环境变量,可重复指定;seed 使用 baseline 环境,进程数由 `--seed-mode` 决定。
200+`distributed` 不能与 `--baseline-env TRAIN_FILE=...` 同用,以免 seed 与训练使用不同的模型构建入口。
201+ 
202+分布式模式通过 `TRAIN_FILE=create_seed_checkpoint` 选择辅助入口,runner 必须读取并传递 `TRAIN_FILE`,不能写死训练入口。
203+辅助入口只保存 model-only 的 step-0,不执行 forward、backward 或优化器更新;仍会构建 baseline 配置的优化器。
204+seed 命令额外设置 `--training.steps=1`,限制 runner 忽略 `TRAIN_FILE` 时的误训练步数。
205+两侧加载同一份 seed 权重;跨并行布局加载是否受支持取决于模型的 checkpoint 实现。
206+当前不支持恢复完整训练状态的续训比较。
207+ 
191#### 输出与清理208#### 输出与清理
192 209 
193默认在当前目录的 `outputs/compare_results/` 下创建独立结果目录;`--output-dir` 可指定空目录或尚不存在的目录。210默认在当前目录的 `outputs/compare_results/` 下创建独立结果目录;`--output-dir` 可指定空目录或尚不存在的目录。
@@ -0,0 +1,57 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Save initialized model weights using the configured distributed layout.
7+ 
8+Launched through the baseline runner by loss_compare.py. Unlike TorchTitan's
9+single-rank CPU seed entry, this builds the normal parallelized model and saves
10+step 0 without calling train(), loading a checkpoint, or updating the optimizer.
11+This follows the seed branch of torchtitan v0.3.0's torchtitan/train.py main();
12+recheck that entry point and Trainer construction when upgrading torchtitan.
13+"""
14+ 
15+from typing import TYPE_CHECKING, cast
16+ 
17+import torch
18+from torchtitan.config import ConfigManager
19+from torchtitan.observability import structured_logger as sl
20+from torchtitan.tools.logging import init_logger, logger
21+ 
22+import torchtitan_npu # noqa: F401
23+ 
24+if TYPE_CHECKING:
25+ from torchtitan.trainer import Trainer
26+ 
27+ 
28+def main() -> None:
xuyujun
xuyujunxuyujunOct 21

这段基本照着 torchtitan v0.3.0 的 train.py:main() 写的。建议在文件说明里加一句“对应上游 torchtitan/train.py main() 的 seed 分支,升级 torchtitan 时同步核对”,以后改版本好找。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
29+ init_logger()
30+ config = cast("Trainer.Config", ConfigManager().parse_args())
31+ if config.checkpoint.create_seed_checkpoint:
xuyujun
xuyujunxuyujunOct 21

(对应第 29-36 行和第 44-52 行。)

现在的 UT 只测了 loss_compare.py 传参对不对,create_seed_checkpoint.py 本身一行都没跑到。建议加一个小 UT:替换掉 ConfigManager.parse_args 和 config.build,检查 4 个报错条件各自会拦住,正常路径会调用 save(curr_step=0, last_step=True) 和 close()。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
32+ raise ValueError("Distributed seed creation requires checkpoint.create_seed_checkpoint=False")
33+ if not config.checkpoint.enable or config.checkpoint.load_only:
34+ raise ValueError("Distributed seed creation requires checkpoint saving to be enabled")
35+ if not config.checkpoint.last_save_model_only or config.checkpoint.last_save_in_hf:
36+ raise ValueError("Distributed seed creation requires a model-only native checkpoint")
37+ if config.comm.mode == "local_tensor":
38+ raise ValueError("Distributed seed creation requires initialized distributed model weights")
39+ sl.init_structured_logger(
40+ source="training",
41+ output_dir=config.dump_folder,
42+ enable=config.debug.enable_structured_logging,
43+ )
44+ trainer: Trainer | None = None
45+ try:
46+ trainer = config.build()
xuyujun
xuyujunxuyujunOct 21

不阻塞。seed 阶段只存模型权重,优化器其实用不上。如果之后 4K 或更大的配置在 seed 阶段就爆显存,可以考虑这一步换成占用更小的优化器配置。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
47+ trainer.checkpointer.save(curr_step=0, last_step=True)
48+ logger.info("Created distributed seed checkpoint at step 0; no training updates performed")
49+ finally:
50+ if trainer is not None:
51+ trainer.close()
52+ if torch.distributed.is_initialized():
53+ torch.distributed.destroy_process_group()
54+ 
55+ 
56+if __name__ == "__main__":
57+ main()
@@ -24,6 +24,11 @@ TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close
24随机种子、TensorBoard 配置不能放入 `--baseline-options` / `--test-options`。24随机种子、TensorBoard 配置不能放入 `--baseline-options` / `--test-options`。
25`--no-seed-checkpoint` 可跳过共享 checkpoint。25`--no-seed-checkpoint` 可跳过共享 checkpoint。
26 26 
27+Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-mode distributed`。
28+该模式按 baseline 的 NPU 数、入口配置及额外选项构建模型,在训练前保存 step-0,
29+不执行 forward、backward 或 optimizer 更新。两侧仍加载同一份权重;checkpoint
30+是否支持两侧不同的并行布局由模型决定,不兼容时加载会失败。
31+ 
27用法示例:32用法示例:
28 33 
291. 比较两个 Git 分支或提交341. 比较两个 Git 分支或提交
@@ -74,6 +79,9 @@ TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close
74- --seq-len:seed 和两侧训练的序列长度,默认 4096;例如 `--seq-len 2048`。79- --seq-len:seed 和两侧训练的序列长度,默认 4096;例如 `--seq-len 2048`。
75- --ngpus:NPU 进程数,默认 1;两侧拓扑不同时用 --baseline-ngpus /80- --ngpus:NPU 进程数,默认 1;两侧拓扑不同时用 --baseline-ngpus /
76 --test-ngpus 分别指定。81 --test-ngpus 分别指定。
82+- --seed-mode:默认 unsharded 使用单卡 CPU 初始化;distributed 保留 baseline
xuyujun
xuyujunxuyujunOct 21

(这条说的是 scripts/numerical_alignment/README.md:26,README 不在这次改动里,所以挂在这里的参数说明上。)

README 还没改。第 26 行仍写着“seed 由 baseline 单卡生成”,加了 --seed-mode distributed 后这句就不对了。请在 README 里补上 --seed-mode 的说明,写清楚:分布式模式会用 baseline 的卡数、runner 和 --baseline-options 搭模型,需要和 baseline 一样的卡和显存;runner 必须认 TRAIN_FILE 环境变量。另外 panchao 那条评论也请回一下。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
83+ 的并行布局,需要与 baseline 相同的卡数和显存资源,runner 必须支持 TRAIN_FILE。
84+ distributed 不能与 --baseline-env TRAIN_FILE=... 同用。
77- --output-dir:结果输出目录,必须为空或尚未存在;默认在当前目录的85- --output-dir:结果输出目录,必须为空或尚未存在;默认在当前目录的
78 outputs/compare_results/ 下创建独立的结果子目录。86 outputs/compare_results/ 下创建独立的结果子目录。
79- --cleanup-after-test / --no-cleanup-after-test:默认清理 seed 目录和临时87- --cleanup-after-test / --no-cleanup-after-test:默认清理 seed 目录和临时
@@ -285,25 +293,34 @@ def build_seed_command(
285 *,293 *,
286 deterministic: bool = True,294 deterministic: bool = True,
287 seq_len: int = DEFAULT_SEQ_LEN,295 seq_len: int = DEFAULT_SEQ_LEN,
296+ distributed: bool = False,
297+ options: str = "",
288) -> list[str]:298) -> list[str]:
289- # Seed creation skips parallelize_fn but still builds an optimizer. Use299+ # CPU seed creation skips parallelize_fn but still builds an optimizer;
290- # AdamW here because DistMuon requires DTensor parameters. Only model300+ # DistMuon requires DTensor parameters. Distributed creation preserves
291- # weights are saved; training keeps the runner's optimizer selection.301+ # the baseline optimizer and layout. Both modes save only model weights.
302+ initialization = (
303+ [*shlex.split(options), "--checkpoint.no-create-seed-checkpoint", "--training.steps=1"]
304+ if distributed
305+ else [
306+ "--checkpoint.create_seed_checkpoint",
307+ "--optimizer.name=AdamW",
308+ "--parallelism.data-parallel-replicate-degree=1",
309+ "--parallelism.data-parallel-shard-degree=1",
310+ "--parallelism.tensor-parallel-degree=1",
311+ "--parallelism.pipeline-parallel-degree=1",
312+ "--parallelism.context-parallel-degree=1",
313+ "--parallelism.expert-parallel-degree=1",
314+ ]
315+ )
292 return [316 return [
293 str(runner),317 str(runner),
294 f"--dump_folder={dump_folder}",318 f"--dump_folder={dump_folder}",
295- "--checkpoint.create_seed_checkpoint",319+ *initialization,
296 "--checkpoint.enable",320 "--checkpoint.enable",
297 "--checkpoint.no-load-only",321 "--checkpoint.no-load-only",
298 f"--checkpoint.folder={dump_folder / 'checkpoint'}",322 f"--checkpoint.folder={dump_folder / 'checkpoint'}",
299 "--checkpoint.last-save-model-only",323 "--checkpoint.last-save-model-only",
300- "--optimizer.name=AdamW",
301- "--parallelism.data-parallel-replicate-degree=1",
302- "--parallelism.data-parallel-shard-degree=1",
303- "--parallelism.tensor-parallel-degree=1",
304- "--parallelism.pipeline-parallel-degree=1",
305- "--parallelism.context-parallel-degree=1",
306- "--parallelism.expert-parallel-degree=1",
307 *_fixed_training_options(deterministic=deterministic, seq_len=seq_len),324 *_fixed_training_options(deterministic=deterministic, seq_len=seq_len),
308 ]325 ]
309 326 
@@ -616,6 +633,7 @@ def write_report(
616 mode: str,633 mode: str,
617 thresholds: MetricThresholds,634 thresholds: MetricThresholds,
618 comparisons: Sequence[MetricComparison],635 comparisons: Sequence[MetricComparison],
636+ seed_mode: str = "unsharded",
619) -> None:637) -> None:
620 report: dict[str, Any] = {638 report: dict[str, Any] = {
621 "baseline": {"ref": baseline_ref, "commit": baseline_commit, "runner": str(baseline_runner)},639 "baseline": {"ref": baseline_ref, "commit": baseline_commit, "runner": str(baseline_runner)},
@@ -623,6 +641,7 @@ def write_report(
623 "runner_scope": runner_scope,641 "runner_scope": runner_scope,
624 "expected_step_range": {"first": 1, "last": expected_steps},642 "expected_step_range": {"first": 1, "last": expected_steps},
625 "mode": mode,643 "mode": mode,
644+ "seed_mode": seed_mode,
626 "thresholds": asdict(thresholds),645 "thresholds": asdict(thresholds),
627 "passed": all(result.passed for result in comparisons),646 "passed": all(result.passed for result in comparisons),
628 "metrics": [asdict(result) for result in comparisons],647 "metrics": [asdict(result) for result in comparisons],
@@ -728,7 +747,14 @@ def parse_args() -> argparse.Namespace:
728 default=[],747 default=[],
729 help="extra KEY=VALUE[,...] environment for the test run (repeatable)",748 help="extra KEY=VALUE[,...] environment for the test run (repeatable)",
730 )749 )
731- parser.add_argument(750+ seed_group = parser.add_mutually_exclusive_group()
751+ seed_group.add_argument(
panchao-gitcode

新加了 --seed-mode,但 README 的 --baseline-env/--test-env 说明还写着“seed 由 baseline 单卡生成”,和 distributed 模式冲突。请同步 README,并写清 distributed 需要 baseline 的卡数和资源。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
752+ "--seed-mode",
753+ choices=("unsharded", "distributed"),
754+ default="unsharded",
755+ help="shared checkpoint initialization: single-rank CPU or baseline's distributed layout",
756+ )
757+ seed_group.add_argument(
732 "--no-seed-checkpoint",758 "--no-seed-checkpoint",
733 action="store_true",759 action="store_true",
734 help="initialize both runs from deterministic seeds instead of one checkpoint",760 help="initialize both runs from deterministic seeds instead of one checkpoint",
@@ -739,6 +765,8 @@ def parse_args() -> argparse.Namespace:
739 help="do not enable deterministic algorithms (required by unsupported fused ops)",765 help="do not enable deterministic algorithms (required by unsupported fused ops)",
740 )766 )
741 args = parser.parse_args()767 args = parser.parse_args()
768+ if args.seed_mode == "distributed" and "TRAIN_FILE" in _merged_env(args.baseline_env):
769+ parser.error("--seed-mode distributed cannot be combined with --baseline-env TRAIN_FILE=...")
742 if args.steps <= 0:770 if args.steps <= 0:
743 parser.error("--steps must be positive")771 parser.error("--steps must be positive")
744 if args.seq_len <= 0:772 if args.seq_len <= 0:
@@ -824,20 +852,35 @@ def main() -> None:
824 if not args.no_seed_checkpoint:852 if not args.no_seed_checkpoint:
825 log_step("Creating shared seed checkpoint")853 log_step("Creating shared seed checkpoint")
826 seed_dump = output_dir / "seed"854 seed_dump = output_dir / "seed"
855+ distributed_seed = args.seed_mode == "distributed"
856+ seed_env = training_env(base_n if distributed_seed else 1, _merged_env(args.baseline_env))
xuyujun
xuyujunxuyujunOct 21

(对应第 853-857 行。)

这里会把用户在 --baseline-env 里设的 TRAIN_FILE 直接覆盖掉。baseline 用自定义入口时,seed 阶段搭的模型就和训练时不一致了,也不会报错。建议在分布式模式下检测到 --baseline-env 带了 TRAIN_FILE 时直接报错,提示这两者不能一起用;或者至少打一条警告。再补一个 UT 覆盖这种情况。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
857+ if distributed_seed:
858+ # Use this CLI's helper even when the baseline ref predates it.
859+ # Expose only the helper, not sibling modules such as utils.
860+ seed_entrypoint = seed_dump / "entrypoint"
861+ seed_entrypoint.mkdir(parents=True)
862+ shutil.copy2(Path(__file__).with_name("create_seed_checkpoint.py"), seed_entrypoint)
863+ seed_env["TRAIN_FILE"] = "create_seed_checkpoint"
xuyujun
xuyujunxuyujunOct 21

(报错检查在第 874-876 行,那几行这次没改,所以挂在这里。)

分布式模式依赖 runner 认 TRAIN_FILE。如果 runner 写死了入口,seed 阶段会真的去训练,跑完才报“seed checkpoint was not created”。建议 seed 阶段额外加 --training.steps=1 之类的兜底,或者让辅助入口先打一行固定标记、跑完检查日志里有没有这行;至少在报错信息里提示“检查 runner 是否支持 TRAIN_FILE”。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
864+ seed_env["PYTHONPATH"] = os.pathsep.join(
xuyujun
xuyujunxuyujunOct 21

现在没问题,提一句:这里把整个目录加进了 PYTHONPATH,utils 也跟着变成了顶层模块,名字太通用。可以考虑只把辅助入口单独放一个目录,或者换个不容易撞的模块名。

likedislike
1Fire4
1Fire4
Oct 22 Comments:
likedislike
865+ filter(None, (str(seed_entrypoint), seed_env.get("PYTHONPATH", "")))
866+ )
827 run_with_realtime_output(867 run_with_realtime_output(
828 build_seed_command(868 build_seed_command(
829 baseline_runner,869 baseline_runner,
830 seed_dump,870 seed_dump,
831 deterministic=not args.no_deterministic,871 deterministic=not args.no_deterministic,
832 seq_len=args.seq_len,872 seq_len=args.seq_len,
873+ distributed=distributed_seed,
874+ options=args.baseline_options,
833 ),875 ),
834 cwd=baseline_worktree,876 cwd=baseline_worktree,
835- env=training_env(1, _merged_env(args.baseline_env)),877+ env=seed_env,
836 log_file=seed_dump / "training.log",878 log_file=seed_dump / "training.log",
837 )879 )
838 seed_checkpoint = seed_dump / "checkpoint" / "step-0"880 seed_checkpoint = seed_dump / "checkpoint" / "step-0"
839 if not seed_checkpoint.is_dir():881 if not seed_checkpoint.is_dir():
840- raise RuntimeError(f"seed checkpoint was not created: {seed_checkpoint}")882+ hint = "; check that the runner supports TRAIN_FILE=create_seed_checkpoint" if distributed_seed else ""
883+ raise RuntimeError(f"seed checkpoint was not created: {seed_checkpoint}{hint}")
841 log_success(f"Seed checkpoint is ready: {seed_checkpoint}")884 log_success(f"Seed checkpoint is ready: {seed_checkpoint}")
842 else:885 else:
843 log_info("Shared seed checkpoint disabled; using deterministic seeds")886 log_info("Shared seed checkpoint disabled; using deterministic seeds")
@@ -921,6 +964,7 @@ def main() -> None:
921 mode=args.mode,964 mode=args.mode,
922 thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS),965 thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS),
923 comparisons=comparisons,966 comparisons=comparisons,
967+ seed_mode="none" if args.no_seed_checkpoint else args.seed_mode,
924 )968 )
925 log_success(f"Report written: {output_dir / 'comparison.json'}")969 log_success(f"Report written: {output_dir / 'comparison.json'}")
926 if not all(result.passed for result in comparisons):970 if not all(result.passed for result in comparisons):
@@ -0,0 +1,114 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Exercise the seed entry lifecycle with Trainer construction isolated from NPU."""
7+ 
8+import importlib.util
9+import sys
10+from pathlib import Path
11+from types import ModuleType, SimpleNamespace
12+from unittest.mock import Mock
13+ 
14+import pytest
15+import torch
16+ 
17+pytestmark = pytest.mark.tooling
18+SCRIPT = Path(__file__).resolve().parents[3] / "scripts/numerical_alignment/create_seed_checkpoint.py"
19+ 
20+ 
21+@pytest.fixture
22+def seed_entry(monkeypatch, tmp_path):
23+ trainer = Mock(spec=["checkpointer", "close"])
24+ trainer.checkpointer = Mock(spec=["save"])
25+ config = SimpleNamespace(
26+ checkpoint=SimpleNamespace(
27+ create_seed_checkpoint=False,
28+ enable=True,
29+ load_only=False,
30+ last_save_model_only=True,
31+ last_save_in_hf=False,
32+ ),
33+ comm=SimpleNamespace(mode="default"),
34+ debug=SimpleNamespace(enable_structured_logging=False),
35+ dump_folder=str(tmp_path),
36+ build=Mock(return_value=trainer),
37+ )
38+ config_manager = Mock()
39+ config_manager.return_value.parse_args.return_value = config
40+ # Only imports and NPU-dependent construction are replaced; main() is real.
41+ modules = {
42+ name: ModuleType(name)
43+ for name in (
44+ "torchtitan",
45+ "torchtitan.config",
46+ "torchtitan.observability",
47+ "torchtitan.tools",
48+ "torchtitan.tools.logging",
49+ "torchtitan_npu",
50+ )
51+ }
52+ modules["torchtitan.config"].ConfigManager = config_manager
53+ modules["torchtitan.observability"].structured_logger = Mock()
54+ modules["torchtitan.tools.logging"].init_logger = Mock()
55+ modules["torchtitan.tools.logging"].logger = Mock()
56+ for name, module in modules.items():
57+ monkeypatch.setitem(sys.modules, name, module)
58+ monkeypatch.setattr(torch.distributed, "is_initialized", lambda: True)
59+ destroy = Mock()
60+ monkeypatch.setattr(torch.distributed, "destroy_process_group", destroy)
61+ spec = importlib.util.spec_from_file_location("distributed_seed_entry", SCRIPT)
62+ entry = importlib.util.module_from_spec(spec)
63+ spec.loader.exec_module(entry)
64+ return entry, config, trainer, destroy
65+ 
66+ 
67+@pytest.mark.parametrize(
68+ ("section", "field", "value", "message"),
69+ [
70+ ("checkpoint", "create_seed_checkpoint", True, "create_seed_checkpoint=False"),
71+ ("checkpoint", "enable", False, "checkpoint saving to be enabled"),
72+ ("checkpoint", "load_only", True, "checkpoint saving to be enabled"),
73+ ("checkpoint", "last_save_model_only", False, "model-only native checkpoint"),
74+ ("checkpoint", "last_save_in_hf", True, "model-only native checkpoint"),
75+ ("comm", "mode", "local_tensor", "initialized distributed model weights"),
76+ ],
77+ ids=["cpu_seed", "saving_disabled", "load_only", "full_state", "hf_export", "local_tensor"],
78+)
79+def test_seed_entry_rejects_invalid_configuration_before_build(seed_entry, section, field, value, message):
80+ entry, config, trainer, _ = seed_entry
81+ setattr(getattr(config, section), field, value)
82+ 
83+ with pytest.raises(ValueError, match=message):
84+ entry.main()
85+ 
86+ config.build.assert_not_called()
87+ trainer.checkpointer.save.assert_not_called()
88+ 
89+ 
90+def test_seed_entry_saves_step_zero_and_releases_resources(seed_entry):
91+ entry, config, trainer, destroy = seed_entry
92+ 
93+ entry.main()
94+ 
95+ config.build.assert_called_once_with()
96+ trainer.checkpointer.save.assert_called_once_with(curr_step=0, last_step=True)
97+ trainer.close.assert_called_once_with()
98+ destroy.assert_called_once_with()
99+ 
100+ 
101+@pytest.mark.parametrize("failure", ["build", "save"])
102+def test_seed_entry_releases_resources_on_failure(seed_entry, failure):
103+ entry, config, trainer, destroy = seed_entry
104+ operation = config.build if failure == "build" else trainer.checkpointer.save
105+ operation.side_effect = RuntimeError("seed operation failed")
106+ 
107+ with pytest.raises(RuntimeError, match="seed operation failed"):
108+ entry.main()
109+ 
110+ if failure == "build":
111+ trainer.close.assert_not_called()
112+ else:
113+ trainer.close.assert_called_once_with()
114+ destroy.assert_called_once_with()
@@ -37,6 +37,7 @@ def runner_repo(tmp_path):
37 git("config", "core.hooksPath", "/dev/null")37 git("config", "core.hooksPath", "/dev/null")
38 (repo / "emit_metrics.py").write_text(38 (repo / "emit_metrics.py").write_text(
39 """import argparse39 """import argparse
40+import os
40from pathlib import Path41from pathlib import Path
41from tensorboard.compat.proto.event_pb2 import Event42from tensorboard.compat.proto.event_pb2 import Event
42from tensorboard.compat.proto.summary_pb2 import Summary43from tensorboard.compat.proto.summary_pb2 import Summary
@@ -46,7 +47,15 @@ p.add_argument('--dump_folder', type=Path)
46p.add_argument('--training.steps', type=int, dest='steps')47p.add_argument('--training.steps', type=int, dest='steps')
47p.add_argument('--value', type=float)48p.add_argument('--value', type=float)
48p.add_argument('--recorded-steps')49p.add_argument('--recorded-steps')
50+p.add_argument('--checkpoint.folder', type=Path, dest='checkpoint_folder')
49args, _ = p.parse_known_args()51args, _ = p.parse_known_args()
52+if os.environ.get('TRAIN_FILE') == 'create_seed_checkpoint':
53+ entrypoint = Path(os.environ['PYTHONPATH'].split(os.pathsep)[0])
54+ print('seed-imports=' + ','.join(sorted(path.name for path in entrypoint.iterdir())))
55+ (args.checkpoint_folder / 'step-0').mkdir(parents=True)
56+ print('seed-processes=' + os.environ['NGPU'])
57+ print('seed-value=' + str(args.value))
58+ raise SystemExit(0)
50steps = range(1, args.steps + 1) if args.recorded_steps is None else map(int, args.recorded_steps.split(','))59steps = range(1, args.steps + 1) if args.recorded_steps is None else map(int, args.recorded_steps.split(','))
51w = EventFileWriter(str(args.dump_folder / 'tensorboard' / 'rank_0'))60w = EventFileWriter(str(args.dump_folder / 'tensorboard' / 'rank_0'))
52try:61try:
@@ -92,6 +101,109 @@ def _compare(repo, refs, output, runner, *options):
92 )101 )
93 102 
94 103 
104+def test_loss_compare_distributed_seed_uses_baseline_layout_and_options(tmp_path, runner_repo):
105+ repo, refs = runner_repo
106+ output = tmp_path / "comparison"
107+ 
108+ result = subprocess.run(
109+ [
110+ sys.executable,
111+ str(CLI),
112+ refs[0],
113+ refs[0],
114+ "--runner=runner.sh",
115+ "--seed-mode=distributed",
116+ "--baseline-ngpus=2",
117+ "--test-ngpus=2",
118+ "--steps=2",
119+ "--baseline-options=--value=3",
120+ "--test-options=--value=3",
121+ "--output-dir",
122+ str(output),
123+ ],
124+ cwd=repo,
125+ text=True,
126+ capture_output=True,
127+ timeout=40,
128+ )
129+ 
130+ assert result.returncode == 0, result.stdout + result.stderr
131+ assert "seed-processes=2" in result.stdout
132+ assert "seed-value=3.0" in result.stdout
133+ assert "seed-imports=create_seed_checkpoint.py" in result.stdout
134+ report = json.loads((output / "comparison.json").read_text())
135+ assert report["seed_mode"] == "distributed"
136+ assert report["passed"]
137+ assert "runner-value=3.0" in (output / "baseline" / "training.log").read_text()
138+ assert "runner-value=3.0" in (output / "test" / "training.log").read_text()
139+ 
140+ 
141+def test_loss_compare_rejects_distributed_seed_with_custom_baseline_entrypoint(tmp_path):
142+ output = tmp_path / "comparison"
143+ 
144+ result = subprocess.run(
145+ [
146+ sys.executable,
147+ str(CLI),
148+ "HEAD",
149+ "HEAD",
150+ "--seed-mode=distributed",
151+ "--baseline-env=EXAMPLE=1,TRAIN_FILE=custom.train",
152+ "--baseline-env=EXAMPLE=2",
153+ "--output-dir",
154+ str(output),
155+ ],
156+ cwd=tmp_path,
157+ text=True,
158+ capture_output=True,
159+ timeout=10,
160+ )
161+ 
162+ assert result.returncode == 2, result.stdout + result.stderr
163+ assert "--seed-mode distributed cannot be combined with --baseline-env TRAIN_FILE" in result.stderr
164+ assert not output.exists()
165+ 
166+ 
167+def test_loss_compare_bounds_training_when_runner_ignores_seed_entrypoint(tmp_path, runner_repo):
168+ repo, refs = runner_repo
169+ observed_steps = tmp_path / "observed_steps"
170+ training = (
171+ "import argparse; from pathlib import Path; "
172+ "parser = argparse.ArgumentParser(); "
173+ "parser.add_argument('--training.steps', dest='steps', type=int); "
174+ "args, _ = parser.parse_known_args(); "
175+ f"Path({str(observed_steps)!r}).write_text(','.join(map(str, range(1, args.steps + 1))))"
176+ )
177+ runner = repo / "ignore_entrypoint.sh"
178+ runner.write_text(f'#!/bin/bash\nexec {shlex.quote(sys.executable)} -c {shlex.quote(training)} "$@"\n')
179+ runner.chmod(0o755)
180+ output = tmp_path / "comparison"
181+ 
182+ result = subprocess.run(
183+ [
184+ sys.executable,
185+ str(CLI),
186+ refs[0],
187+ refs[0],
188+ f"--runner={runner}",
189+ "--seed-mode=distributed",
190+ "--steps=5",
191+ "--output-dir",
192+ str(output),
193+ ],
194+ cwd=repo,
195+ text=True,
196+ capture_output=True,
197+ timeout=40,
198+ )
199+ 
200+ assert result.returncode != 0
201+ assert "check that the runner supports TRAIN_FILE=create_seed_checkpoint" in result.stderr
202+ assert observed_steps.read_text() == "1"
203+ assert not (output / "baseline").exists()
204+ assert not (output / "comparison.json").exists()
205+ 
206+ 
95@pytest.mark.parametrize("side", ["baseline", "test"])207@pytest.mark.parametrize("side", ["baseline", "test"])
96@pytest.mark.parametrize(208@pytest.mark.parametrize(
97 ("options", "hint"),209 ("options", "hint"),