Merged
feat: 适配 dev_0.4.0 Muon/NovaSwap 并同步 Engram checkpoint 修复 #1153
没有杰Add on Nov 2
feat: 适配 dev_0.4.0 Muon/NovaSwap 并同步 Engram checkpoint 修复 #1153
Merged
Total: 19 files changed+154-550
| @@ -154,12 +154,7 @@ python scripts/numerical_alignment/loss_compare.py HEAD HEAD \ | |||
| 154 | 154 | ||
| 155 | #### Seed checkpoint | 155 | #### Seed checkpoint |
| 156 | 156 | ||
| 157 | -默认通过同一份 seed checkpoint 初始化两侧模型,由 `--seed-mode` 指定创建方式: | 157 | +默认使用 baseline 入口,以单进程 CPU 初始化完整权重并保存 seed checkpoint,两侧训练加载同一份权重。seed 阶段单独使用 `NGPU=1`,不改变两次训练本身的卡数。跨并行布局加载是否支持取决于模型的 checkpoint 实现;当前不支持恢复完整训练状态的续训比较。 |
| 158 | - | ||
| 159 | -- `unsharded`(默认):单进程 CPU 初始化完整权重,单独使用 `NGPU=1`。 | ||
| 160 | -- `distributed`:按 baseline 的卡数、runner 和配置构建并行模型,需预留与 baseline 相同的卡数和显存;Engram 等依赖并行布局的 checkpoint 适用。该模式下 runner 必须读取并传递 `TRAIN_FILE`,不能写死训练入口,且不能与 `--baseline-env TRAIN_FILE=...` 同用。 | ||
| 161 | - | ||
| 162 | -两种模式都不改变两次训练本身的卡数。跨并行布局加载是否支持取决于模型的 checkpoint 实现;当前不支持恢复完整训练状态的续训比较。 | ||
| 163 | 若两侧无法共用 seed checkpoint,可用 `--no-seed-checkpoint` 改为固定种子初始化。 | 158 | 若两侧无法共用 seed checkpoint,可用 `--no-seed-checkpoint` 改为固定种子初始化。 |
| 164 | 159 | ||
| 165 | 两侧默认使用 token 预算接口。迁移比较可分别选择序列长度参数:`--baseline-training-api legacy` 使用 `--training.seq-len`,`--test-training-api tokens` 使用 `--training.max-context-length`;长度仍由 `--seq-len` 统一指定。旧侧 local/global batch 与新侧 microbatch/train-step token 预算通过各自 options 显式传入,工具不推断数据并行度或梯度累积。`--baseline-upstream` / `--test-upstream` 可分别指定 TorchTitan 源码目录,并加入对应进程的 `PYTHONPATH`;解释器及依赖仍由各侧环境提供。 | 160 | 两侧默认使用 token 预算接口。迁移比较可分别选择序列长度参数:`--baseline-training-api legacy` 使用 `--training.seq-len`,`--test-training-api tokens` 使用 `--training.max-context-length`;长度仍由 `--seq-len` 统一指定。旧侧 local/global batch 与新侧 microbatch/train-step token 预算通过各自 options 显式传入,工具不推断数据并行度或梯度累积。`--baseline-upstream` / `--test-upstream` 可分别指定 TorchTitan 源码目录,并加入对应进程的 `PYTHONPATH`;解释器及依赖仍由各侧环境提供。 |
| @@ -1,57 +0,0 @@ | |||
| 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: | ||
| 29 | - init_logger() | ||
| 30 | - config = cast("Trainer.Config", ConfigManager().parse_args()) | ||
| 31 | - if config.checkpoint.create_seed_checkpoint: | ||
| 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() | ||
| 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() | ||
| @@ -27,11 +27,6 @@ TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close | |||
| 27 | 旧版本可使用 `--baseline-training-api legacy`,将 baseline 的长度参数改为 `--training.seq-len`。 | 27 | 旧版本可使用 `--baseline-training-api legacy`,将 baseline 的长度参数改为 `--training.seq-len`。 |
| 28 | `--baseline-upstream` / `--test-upstream` 分别指定独立的 TorchTitan 源码目录。 | 28 | `--baseline-upstream` / `--test-upstream` 分别指定独立的 TorchTitan 源码目录。 |
| 29 | 29 | ||
| 30 | -Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-mode distributed`。 | ||
| 31 | -该模式按 baseline 的 NPU 数、入口配置及额外选项构建模型,在训练前保存 step-0, | ||
| 32 | -不执行 forward、backward 或 optimizer 更新。两侧仍加载同一份权重;checkpoint | ||
| 33 | -是否支持两侧不同的并行布局由模型决定,不兼容时加载会失败。 | ||
| 34 | - | ||
| 35 | 用法示例: | 30 | 用法示例: |
| 36 | 31 | ||
| 37 | 1. 比较自行准备的两个训练脚本 | 32 | 1. 比较自行准备的两个训练脚本 |
| @@ -111,10 +106,7 @@ Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-m | |||
| 111 | - --seq-len:seed 和两侧训练的序列长度,默认 4096;例如 `--seq-len 2048`。 | 106 | - --seq-len:seed 和两侧训练的序列长度,默认 4096;例如 `--seq-len 2048`。 |
| 112 | - --ngpus:可选的两侧 NPU 进程数覆盖值;默认沿用环境变量和各自 runner 的卡数设置。 | 107 | - --ngpus:可选的两侧 NPU 进程数覆盖值;默认沿用环境变量和各自 runner 的卡数设置。 |
| 113 | 两侧拓扑不同时用 --baseline-ngpus / --test-ngpus 分别覆盖;显式卡数参数优先于 | 108 | 两侧拓扑不同时用 --baseline-ngpus / --test-ngpus 分别覆盖;显式卡数参数优先于 |
| 114 | - NGPU 环境变量。默认 unsharded seed 使用单进程初始化。 | 109 | + NGPU 环境变量。seed 使用单进程 CPU 初始化。 |
| 115 | -- --seed-mode:默认 unsharded 使用单卡 CPU 初始化;distributed 保留 baseline | ||
| 116 | - 的并行布局,需要与 baseline 相同的卡数和显存资源,runner 必须支持 TRAIN_FILE。 | ||
| 117 | - distributed 不能与 --baseline-env TRAIN_FILE=... 同用。 | ||
| 118 | - --output-dir:结果输出目录,必须为空或尚未存在;默认在当前目录的 | 110 | - --output-dir:结果输出目录,必须为空或尚未存在;默认在当前目录的 |
| 119 | outputs/compare_results/ 下创建独立的结果子目录。 | 111 | outputs/compare_results/ 下创建独立的结果子目录。 |
| 120 | - --cleanup-after-test / --no-cleanup-after-test:默认清理 seed 目录和临时 | 112 | - --cleanup-after-test / --no-cleanup-after-test:默认清理 seed 目录和临时 |
| @@ -337,34 +329,25 @@ def build_seed_command( | |||
| 337 | deterministic: bool = True, | 329 | deterministic: bool = True, |
| 338 | seq_len: int = DEFAULT_SEQ_LEN, | 330 | seq_len: int = DEFAULT_SEQ_LEN, |
| 339 | training_api: str = "tokens", | 331 | training_api: str = "tokens", |
| 340 | - distributed: bool = False, | ||
| 341 | - options: str = "", | ||
| 342 | ) -> list[str]: | 332 | ) -> list[str]: |
| 343 | - # CPU seed creation skips parallelize_fn but still builds an optimizer; | 333 | + # Seed creation skips parallelize_fn but still builds an optimizer. Use |
| 344 | - # DistMuon requires DTensor parameters. Distributed creation preserves | 334 | + # AdamW here because DistMuon requires DTensor parameters. Only model |
| 345 | - # the baseline optimizer and layout. Both modes save only model weights. | 335 | + # weights are saved; training keeps the runner's optimizer selection. |
| 346 | - initialization = ( | ||
| 347 | - [*shlex.split(options), "--checkpoint.no-create-seed-checkpoint", "--training.steps=1"] | ||
| 348 | - if distributed | ||
| 349 | - else [ | ||
| 350 | - "--checkpoint.create_seed_checkpoint", | ||
| 351 | - "--optimizer.name=AdamW", | ||
| 352 | - "--parallelism.data-parallel-replicate-degree=1", | ||
| 353 | - "--parallelism.data-parallel-shard-degree=1", | ||
| 354 | - "--parallelism.tensor-parallel-degree=1", | ||
| 355 | - "--parallelism.pipeline-parallel-degree=1", | ||
| 356 | - "--parallelism.context-parallel-degree=1", | ||
| 357 | - "--parallelism.expert-parallel-degree=1", | ||
| 358 | - ] | ||
| 359 | - ) | ||
| 360 | return [ | 336 | return [ |
| 361 | str(runner), | 337 | str(runner), |
| 362 | f"--dump_folder={dump_folder}", | 338 | f"--dump_folder={dump_folder}", |
| 363 | - *initialization, | 339 | + "--checkpoint.create_seed_checkpoint", |
| 364 | "--checkpoint.enable", | 340 | "--checkpoint.enable", |
| 365 | "--checkpoint.no-load-only", | 341 | "--checkpoint.no-load-only", |
| 366 | f"--checkpoint.folder={dump_folder / 'checkpoint'}", | 342 | f"--checkpoint.folder={dump_folder / 'checkpoint'}", |
| 367 | "--checkpoint.last-save-model-only", | 343 | "--checkpoint.last-save-model-only", |
| 344 | + "--optimizer.name=AdamW", | ||
| 345 | + "--parallelism.data-parallel-replicate-degree=1", | ||
| 346 | + "--parallelism.data-parallel-shard-degree=1", | ||
| 347 | + "--parallelism.tensor-parallel-degree=1", | ||
| 348 | + "--parallelism.pipeline-parallel-degree=1", | ||
| 349 | + "--parallelism.context-parallel-degree=1", | ||
| 350 | + "--parallelism.expert-parallel-degree=1", | ||
| 368 | *_fixed_training_options(deterministic=deterministic, seq_len=seq_len, training_api=training_api), | 351 | *_fixed_training_options(deterministic=deterministic, seq_len=seq_len, training_api=training_api), |
| 369 | ] | 352 | ] |
| 370 | 353 | ||
| @@ -703,7 +686,6 @@ def write_report( | |||
| 703 | mode: str, | 686 | mode: str, |
| 704 | thresholds: MetricThresholds, | 687 | thresholds: MetricThresholds, |
| 705 | comparisons: Sequence[MetricComparison], | 688 | comparisons: Sequence[MetricComparison], |
| 706 | - seed_mode: str = "unsharded", | ||
| 707 | runtime_options: Mapping[str, Any] | None = None, | 689 | runtime_options: Mapping[str, Any] | None = None, |
| 708 | ) -> None: | 690 | ) -> None: |
| 709 | report: dict[str, Any] = { | 691 | report: dict[str, Any] = { |
| @@ -722,7 +704,6 @@ def write_report( | |||
| 722 | "runner_scope": runner_scope, | 704 | "runner_scope": runner_scope, |
| 723 | "expected_step_range": {"first": 1, "last": expected_steps}, | 705 | "expected_step_range": {"first": 1, "last": expected_steps}, |
| 724 | "mode": mode, | 706 | "mode": mode, |
| 725 | - "seed_mode": seed_mode, | ||
| 726 | "thresholds": asdict(thresholds), | 707 | "thresholds": asdict(thresholds), |
| 727 | "passed": all(result.passed for result in comparisons), | 708 | "passed": all(result.passed for result in comparisons), |
| 728 | "metrics": [asdict(result) for result in comparisons], | 709 | "metrics": [asdict(result) for result in comparisons], |
| @@ -851,14 +832,7 @@ def parse_args() -> argparse.Namespace: | |||
| 851 | default=[], | 832 | default=[], |
| 852 | help="extra KEY=VALUE[,...] environment for the test run (repeatable)", | 833 | help="extra KEY=VALUE[,...] environment for the test run (repeatable)", |
| 853 | ) | 834 | ) |
| 854 | - seed_group = parser.add_mutually_exclusive_group() | 835 | + parser.add_argument( |
| 855 | - seed_group.add_argument( | ||
| 856 | - "--seed-mode", | ||
| 857 | - choices=("unsharded", "distributed"), | ||
| 858 | - default="unsharded", | ||
| 859 | - help="shared checkpoint initialization: single-rank CPU or baseline's distributed layout", | ||
| 860 | - ) | ||
| 861 | - seed_group.add_argument( | ||
| 862 | "--no-seed-checkpoint", | 836 | "--no-seed-checkpoint", |
| 863 | action="store_true", | 837 | action="store_true", |
| 864 | help="initialize both runs from deterministic seeds instead of one checkpoint", | 838 | help="initialize both runs from deterministic seeds instead of one checkpoint", |
| @@ -871,8 +845,6 @@ def parse_args() -> argparse.Namespace: | |||
| 871 | args = parser.parse_args() | 845 | args = parser.parse_args() |
| 872 | if (args.baseline_ref is None) != (args.test_ref is None): | 846 | if (args.baseline_ref is None) != (args.test_ref is None): |
| 873 | parser.error("provide both baseline_ref and test_ref, or omit both to use the current working tree") | 847 | parser.error("provide both baseline_ref and test_ref, or omit both to use the current working tree") |
| 874 | - if args.seed_mode == "distributed" and "TRAIN_FILE" in _merged_env(args.baseline_env): | ||
| 875 | - parser.error("--seed-mode distributed cannot be combined with --baseline-env TRAIN_FILE=...") | ||
| 876 | if args.steps <= 0: | 848 | if args.steps <= 0: |
| 877 | parser.error("--steps must be positive") | 849 | parser.error("--steps must be positive") |
| 878 | if args.seq_len <= 0: | 850 | if args.seq_len <= 0: |
| @@ -994,20 +966,6 @@ def main() -> None: | |||
| 994 | if not args.no_seed_checkpoint: | 966 | if not args.no_seed_checkpoint: |
| 995 | log_step("Creating shared seed checkpoint") | 967 | log_step("Creating shared seed checkpoint") |
| 996 | seed_dump = output_dir / "seed" | 968 | seed_dump = output_dir / "seed" |
| 997 | - distributed_seed = args.seed_mode == "distributed" | ||
| 998 | - seed_env = training_env( | ||
| 999 | - base_n if distributed_seed else 1, _merged_env(args.baseline_env), upstream=args.baseline_upstream | ||
| 1000 | - ) | ||
| 1001 | - if distributed_seed: | ||
| 1002 | - # Use this CLI's helper even when the baseline ref predates it. | ||
| 1003 | - # Expose only the helper, not sibling modules such as utils. | ||
| 1004 | - seed_entrypoint = seed_dump / "entrypoint" | ||
| 1005 | - seed_entrypoint.mkdir(parents=True) | ||
| 1006 | - shutil.copy2(Path(__file__).with_name("create_seed_checkpoint.py"), seed_entrypoint) | ||
| 1007 | - seed_env["TRAIN_FILE"] = "create_seed_checkpoint" | ||
| 1008 | - seed_env["PYTHONPATH"] = os.pathsep.join( | ||
| 1009 | - filter(None, (str(seed_entrypoint), seed_env.get("PYTHONPATH", ""))) | ||
| 1010 | - ) | ||
| 1011 | run_with_realtime_output( | 969 | run_with_realtime_output( |
| 1012 | build_seed_command( | 970 | build_seed_command( |
| 1013 | baseline_runner, | 971 | baseline_runner, |
| @@ -1015,17 +973,14 @@ def main() -> None: | |||
| 1015 | deterministic=not args.no_deterministic, | 973 | deterministic=not args.no_deterministic, |
| 1016 | seq_len=args.seq_len, | 974 | seq_len=args.seq_len, |
| 1017 | training_api=args.baseline_training_api, | 975 | training_api=args.baseline_training_api, |
| 1018 | - distributed=distributed_seed, | ||
| 1019 | - options=args.baseline_options, | ||
| 1020 | ), | 976 | ), |
| 1021 | cwd=baseline_worktree, | 977 | cwd=baseline_worktree, |
| 1022 | - env=seed_env, | 978 | + env=training_env(1, _merged_env(args.baseline_env), upstream=args.baseline_upstream), |
| 1023 | log_file=seed_dump / "training.log", | 979 | log_file=seed_dump / "training.log", |
| 1024 | ) | 980 | ) |
| 1025 | seed_checkpoint = seed_dump / "checkpoint" / "step-0" | 981 | seed_checkpoint = seed_dump / "checkpoint" / "step-0" |
| 1026 | if not seed_checkpoint.is_dir(): | 982 | if not seed_checkpoint.is_dir(): |
| 1027 | - hint = "; check that the runner supports TRAIN_FILE=create_seed_checkpoint" if distributed_seed else "" | 983 | + raise RuntimeError(f"seed checkpoint was not created: {seed_checkpoint}") |
| 1028 | - raise RuntimeError(f"seed checkpoint was not created: {seed_checkpoint}{hint}") | ||
| 1029 | log_success(f"Seed checkpoint is ready: {seed_checkpoint}") | 984 | log_success(f"Seed checkpoint is ready: {seed_checkpoint}") |
| 1030 | else: | 985 | else: |
| 1031 | log_info("Shared seed checkpoint disabled; using deterministic seeds") | 986 | log_info("Shared seed checkpoint disabled; using deterministic seeds") |
| @@ -1107,7 +1062,6 @@ def main() -> None: | |||
| 1107 | mode=args.mode, | 1062 | mode=args.mode, |
| 1108 | thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS), | 1063 | thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS), |
| 1109 | comparisons=comparisons, | 1064 | comparisons=comparisons, |
| 1110 | - seed_mode="none" if args.no_seed_checkpoint else args.seed_mode, | ||
| 1111 | runtime_options={ | 1065 | runtime_options={ |
| 1112 | side: { | 1066 | side: { |
| 1113 | "training_api": getattr(args, f"{side}_training_api"), | 1067 | "training_api": getattr(args, f"{side}_training_api"), |
| @@ -632,9 +632,7 @@ def _filter_tests( | |||
| 632 | continue | 632 | continue |
| 633 | if test_flavor.disabled or test_flavor.test_name in exclude_set: | 633 | if test_flavor.disabled or test_flavor.test_name in exclude_set: |
| 634 | continue | 634 | continue |
| 635 | - # This branch validates the folded-token AdamW training paths first. | 635 | + # Keep unrelated, unmigrated features out of the selected suite. |
| 636 | - # Keep the unmigrated cases defined, with an explicit reason when a | ||
| 637 | - # default suite or a manual selector encounters one. | ||
| 638 | migration_pending = _migration_pending_reason(test_flavor) | 636 | migration_pending = _migration_pending_reason(test_flavor) |
| 639 | if migration_pending is not None: | 637 | if migration_pending is not None: |
| 640 | log_print(f"Skipping {test_flavor.test_name}: {migration_pending}") | 638 | log_print(f"Skipping {test_flavor.test_name}: {migration_pending}") |
| @@ -652,10 +650,20 @@ def _migration_pending_reason(case: OverrideDefinitions) -> str | None: | |||
| 652 | if case.test_name.startswith("dsv3_2_"): | 650 | if case.test_name.startswith("dsv3_2_"): |
| 653 | return "DeepSeek-V3.2 model boundary still requires the folded-token migration" | 651 | return "DeepSeek-V3.2 model boundary still requires the folded-token migration" |
| 654 | arguments = {arg for phase in case.override_args for arg in phase} | 652 | arguments = {arg for phase in case.override_args for arg in phase} |
| 655 | - if "--optimizer.name=Muon" in arguments: | 653 | + if "--optimizer.name=Muon" in arguments and "--training.enable-cpu-offload" in arguments: |
| 656 | - return "Muon migration is pending" | 654 | + return "native CPU-offload Muon migration is pending" |
| 657 | - if case.check_resume or case.verify_ema_checkpoint or "--checkpoint.enable" in arguments: | 655 | + if "--optimizer.name=Muon" in arguments and ( |
| 658 | - return "checkpoint/EMA migration is pending" | 656 | + "lora" in case.test_name |
| 657 | + or any( | ||
| 658 | + arg.startswith("--parallelism.context-parallel-degree=") and arg.rsplit("=", 1)[1] != "1" | ||
| 659 | + for arg in arguments | ||
| 660 | + ) | ||
| 661 | + ): | ||
| 662 | + return "Muon LoRA/context-parallel integration migration is pending" | ||
| 663 | + if case.verify_ema_checkpoint: | ||
| 664 | + return "EMA migration is pending" | ||
| 665 | + if case.check_resume and "lora" in case.test_name: | ||
| 666 | + return "LoRA checkpoint migration is pending" | ||
| 659 | return None | 667 | return None |
| 660 | 668 | ||
| 661 | 669 | ||
| @@ -36,8 +36,6 @@ collect_ignore = [ | |||
| 36 | "extensions/torchtitan/experiments/torchft", | 36 | "extensions/torchtitan/experiments/torchft", |
| 37 | "patches/torchft", | 37 | "patches/torchft", |
| 38 | "patches/torchtitan/experiments/graph_trainer", | 38 | "patches/torchtitan/experiments/graph_trainer", |
| 39 | - "test_dsv4_muon.py", | ||
| 40 | - "models/deepseek_v4_1/test_muon_profile.py", | ||
| 41 | # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only | 39 | # Qwen runtime migration is deferred. Upstream eagerly imports CUDA-only |
| 42 | # CuTeDSL code, which is not installed in the NPU test image. | 40 | # CuTeDSL code, which is not installed in the NPU test image. |
| 43 | "models/qwen3_5/test_qwen3_5_npu_adapter.py", | 41 | "models/qwen3_5/test_qwen3_5_npu_adapter.py", |
| @@ -135,14 +133,15 @@ def pytest_collection_modifyitems(items): | |||
| 135 | item.add_marker( | 133 | item.add_marker( |
| 136 | pytest.mark.skip(reason="DeepSeek-V3.2 model boundary still requires the folded-token migration") | 134 | pytest.mark.skip(reason="DeepSeek-V3.2 model boundary still requires the folded-token migration") |
| 137 | ) | 135 | ) |
| 138 | - # Checkpoint resume and Muon are deliberately deferred on this branch. | 136 | + if relative_path.startswith("extensions/cpu_offload/") and "muon" in item.name.lower(): |
| 139 | - if "muon" in item.name.lower() or item.name.startswith( | 137 | + item.add_marker(pytest.mark.skip(reason="native CPU-offload Muon migration is pending")) |
| 138 | + if item.name.startswith( | ||
| 140 | ( | 139 | ( |
| 141 | "test_lora_training_freezes_engram_and_native_dcp_resumes", | 140 | "test_lora_training_freezes_engram_and_native_dcp_resumes", |
| 142 | "test_v41_adapter_only_resume_restores_engram_and_next_step", | 141 | "test_v41_adapter_only_resume_restores_engram_and_next_step", |
| 143 | ) | 142 | ) |
| 144 | ): | 143 | ): |
| 145 | - item.add_marker(pytest.mark.skip(reason="checkpoint/Muon migration is pending")) | 144 | + item.add_marker(pytest.mark.skip(reason="LoRA checkpoint migration is pending")) |
| 146 | 145 | ||
| 147 | 146 | ||
| 148 | # --------------------------------------------------------------------------- | 147 | # --------------------------------------------------------------------------- |
| @@ -18,6 +18,7 @@ from torch.distributed.checkpoint import HuggingFaceStorageReader, HuggingFaceSt | |||
| 18 | from torch.distributed.checkpoint._consolidate_hf_safetensors import consolidate_safetensors_files_on_every_rank | 18 | from torch.distributed.checkpoint._consolidate_hf_safetensors import consolidate_safetensors_files_on_every_rank |
| 19 | 19 | ||
| 20 | from torchtitan_npu.models.deepseek_v4_1 import model_registry | 20 | from torchtitan_npu.models.deepseek_v4_1 import model_registry |
| 21 | +from torchtitan_npu.models.deepseek_v4_1.engram.checkpoint import checkpoint_shard | ||
| 21 | from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter | 22 | from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter |
| 22 | 23 | ||
| 23 | 24 | ||
| @@ -48,17 +49,23 @@ def main(): | |||
| 48 | weight = torch.arange(48 * 32, dtype=torch.float32).reshape(48, 32) | 49 | weight = torch.arange(48 * 32, dtype=torch.float32).reshape(48, 32) |
| 49 | gate = torch.arange(8, dtype=torch.float32).reshape(2, 4) | 50 | gate = torch.arange(8, dtype=torch.float32).reshape(2, 4) |
| 50 | # Four-rank local runs cover EP2 replicas and four distinct joint shards. | 51 | # Four-rank local runs cover EP2 replicas and four distinct joint shards. |
| 51 | - # The default two-rank UT remains small while checking both key formats. | 52 | + # All layouts use the same key and describe their rows through metadata. |
| 52 | for layout, mapped in product(("ep", "efsdp_ep"), (False, True)): | 53 | for layout, mapped in product(("ep", "efsdp_ep"), (False, True)): |
| 53 | shards = 2 if layout == "ep" else dist.get_world_size() | 54 | shards = 2 if layout == "ep" else dist.get_world_size() |
| 54 | shard_rank = rank % shards | 55 | shard_rank = rank % shards |
| 55 | rows = 48 // shards | 56 | rows = 48 // shards |
| 56 | offset = shard_rank * rows | 57 | offset = shard_rank * rows |
| 57 | - key = f"layers.1.engram.table.weight.{layout}_shard_{shard_rank:05d}_of_{shards:05d}" | 58 | + key = "layers.1.engram.table.weight" |
| 58 | adapter = DeepSeekV41StateDictAdapter(config, str(assets) if mapped else None) | 59 | adapter = DeepSeekV41StateDictAdapter(config, str(assets) if mapped else None) |
| 59 | native = {key: weight[offset : offset + rows].clone(), "layers.1.engram.gate.q_weight": gate} | 60 | native = {key: weight[offset : offset + rows].clone(), "layers.1.engram.gate.q_weight": gate} |
| 60 | - # Trainer casts native state before calling to_hf for last-save export. | 61 | + # Attach checkpoint metadata to the final typed view. |
| 61 | native = {name: value.to(torch.bfloat16) for name, value in native.items()} | 62 | native = {name: value.to(torch.bfloat16) for name, value in native.items()} |
| 63 | + native[key] = checkpoint_shard(native[key], offset=offset, logical_rows=48) | ||
| 64 | + native_path = root / f"native_{layout}_{mapped}" | ||
| 65 | + dcp.save(native, checkpoint_id=str(native_path)) | ||
| 66 | + full_native = {key: torch.empty_like(weight, dtype=torch.bfloat16)} | ||
| 67 | + dcp.load(full_native, checkpoint_id=str(native_path)) | ||
| 68 | + torch.testing.assert_close(full_native[key], weight.bfloat16(), rtol=0, atol=0) | ||
| 62 | hf = adapter.to_hf(native) | 69 | hf = adapter.to_hf(native) |
| 63 | assert type(hf["layers.1.engram.embed.weight"]) is torch.Tensor | 70 | assert type(hf["layers.1.engram.embed.weight"]) is torch.Tensor |
| 64 | path = root / f"{layout}_{'mapped' if mapped else 'unmapped'}" | 71 | path = root / f"{layout}_{'mapped' if mapped else 'unmapped'}" |
| @@ -85,7 +92,9 @@ def main(): | |||
| 85 | dcp.load(restored, storage_reader=HuggingFaceStorageReader(str(path))) | 92 | dcp.load(restored, storage_reader=HuggingFaceStorageReader(str(path))) |
| 86 | torch.testing.assert_close(restored["layers.1.engram.embed.weight"], weight[:41].bfloat16(), rtol=0, atol=0) | 93 | torch.testing.assert_close(restored["layers.1.engram.embed.weight"], weight[:41].bfloat16(), rtol=0, atol=0) |
| 87 | torch.testing.assert_close(restored["layers.1.engram.q_weight"], gate.bfloat16(), rtol=0, atol=0) | 94 | torch.testing.assert_close(restored["layers.1.engram.q_weight"], gate.bfloat16(), rtol=0, atol=0) |
| 88 | - target = adapter.to_hf({key: torch.full((rows, 32), -1.0)}) | 95 | + target = adapter.to_hf( |
| 96 | + {key: checkpoint_shard(torch.full((rows, 32), -1.0), offset=offset, logical_rows=48)} | ||
| 97 | + ) | ||
| 89 | dcp.load(target, storage_reader=HuggingFaceStorageReader(str(path))) | 98 | dcp.load(target, storage_reader=HuggingFaceStorageReader(str(path))) |
| 90 | loaded = adapter.from_hf(target) | 99 | loaded = adapter.from_hf(target) |
| 91 | assert set(loaded) == {key} | 100 | assert set(loaded) == {key} |
| @@ -12,6 +12,7 @@ from types import SimpleNamespace | |||
| 12 | import pytest | 12 | import pytest |
| 13 | import torch | 13 | import torch |
| 14 | from torch.utils.checkpoint import DefaultDeviceType, checkpoint | 14 | from torch.utils.checkpoint import DefaultDeviceType, checkpoint |
| 15 | +from torchtitan.components.optimizer import ParamGroupConfig | ||
| 15 | 16 | ||
| 16 | from torchtitan_npu.extensions.torchtitan.components.optimizer import optimizer as host_mod | 17 | from torchtitan_npu.extensions.torchtitan.components.optimizer import optimizer as host_mod |
| 17 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 18 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| @@ -164,7 +165,10 @@ def _host_table_config(): | |||
| 164 | ) | 165 | ) |
| 165 | 166 | ||
| 166 | 167 | ||
| 167 | -def test_host_offload_model_state_uses_rank_specific_shard_key(): | 168 | +@pytest.mark.skipif( |
| 169 | + not hasattr(torch.distributed.checkpoint, "CheckpointableTensor"), reason="CheckpointableTensor is required" | ||
| 170 | +) | ||
| 171 | +def test_host_offload_weight_and_moments_describe_global_row_shard(): | ||
| 168 | table = HostEngramTable(_host_table_config()) | 172 | table = HostEngramTable(_host_table_config()) |
| 169 | table.weight = torch.nn.Parameter(_ramp(5)) | 173 | table.weight = torch.nn.Parameter(_ramp(5)) |
| 170 | table._ep_rank = 1 | 174 | table._ep_rank = 1 |
| @@ -172,8 +176,27 @@ def test_host_offload_model_state_uses_rank_specific_shard_key(): | |||
| 172 | table._mark_host_weight() | 176 | table._mark_host_weight() |
| 173 | 177 | ||
| 174 | state = table.state_dict() | 178 | state = table.state_dict() |
| 175 | - assert "weight" not in state | 179 | + assert list(state) == ["weight"] |
| 176 | - assert list(state) == ["weight.ep_shard_00001_of_00002"] | 180 | + assert state["weight"].global_shape == (10, _DIM) |
| 181 | + assert state["weight"].global_offsets == ((5, 0),) | ||
| 182 | + assert state["weight"].local_offsets == ((0, 0),) | ||
| 183 | + assert state["weight"].local_sizes == ((5, _DIM),) | ||
| 184 | + | ||
| 185 | + model = torch.nn.Module() | ||
| 186 | + model.add_module("table", table) | ||
| 187 | + optimizer = host_mod.HostSparseOptimizersContainer.Config( | ||
| 188 | + implementation="for-loop", | ||
| 189 | + param_groups=[ParamGroupConfig(pattern=r"table\.weight$", optimizer_name="SparseAdam")], | ||
| 190 | + ).build(model_parts=[model]) | ||
| 191 | + | ||
| 192 | + optim_state = optimizer.state_dict() | ||
| 193 | + for name in ("exp_avg", "exp_avg_sq"): | ||
| 194 | + moment = optim_state[f"state.table.weight.{name}"] | ||
| 195 | + assert moment.global_shape == (10, _DIM) | ||
| 196 | + assert moment.global_offsets == ((5, 0),) | ||
| 197 | + assert moment.local_offsets == ((0, 0),) | ||
| 198 | + assert moment.local_sizes == ((5, _DIM),) | ||
| 199 | + assert moment.data_ptr() == optimizer.optimizers[0].state[table.weight][name].data_ptr() | ||
| 177 | 200 | ||
| 178 | restored = HostEngramTable(_host_table_config()) | 201 | restored = HostEngramTable(_host_table_config()) |
| 179 | restored.weight = torch.nn.Parameter(torch.zeros(5, _DIM)) | 202 | restored.weight = torch.nn.Parameter(torch.zeros(5, _DIM)) |
| @@ -19,14 +19,14 @@ from torchtitan.distributed.parallel_dims import MeshAxisName | |||
| 19 | from torchtitan_npu.models.deepseek_v4_1 import model_registry | 19 | from torchtitan_npu.models.deepseek_v4_1 import model_registry |
| 20 | from torchtitan_npu.models.deepseek_v4_1.config_registry import ( | 20 | from torchtitan_npu.models.deepseek_v4_1.config_registry import ( |
| 21 | _v41_muon_profile, | 21 | _v41_muon_profile, |
| 22 | - deepseek_v4_1_debugmodel_multimodal, | 22 | + deepseek_v4_1_debugmodel_text, |
| 23 | - deepseek_v4_1_flash_40layers_24experts_multimodal, | 23 | + deepseek_v4_1_flash_40layers_24experts_text, |
| 24 | ) | 24 | ) |
| 25 | 25 | ||
| 26 | 26 | ||
| 27 | @pytest.fixture(scope="module") | 27 | @pytest.fixture(scope="module") |
| 28 | def spec(): | 28 | def spec(): |
| 29 | - return model_registry("deepseek_v4_1_flash_40layers_24experts_multimodal") | 29 | + return model_registry("deepseek_v4_1_flash_40layers_24experts_text") |
| 30 | 30 | ||
| 31 | 31 | ||
| 32 | @pytest.fixture(scope="module") | 32 | @pytest.fixture(scope="module") |
| @@ -41,7 +41,7 @@ def layouts(profile): | |||
| 41 | 41 | ||
| 42 | class TestDefaultRecipe: | 42 | class TestDefaultRecipe: |
| 43 | def test_default_is_adamw(self): | 43 | def test_default_is_adamw(self): |
| 44 | - cfg = deepseek_v4_1_flash_40layers_24experts_multimodal() | 44 | + cfg = deepseek_v4_1_flash_40layers_24experts_text() |
| 45 | assert cfg.optimizer.name == "AdamW" | 45 | assert cfg.optimizer.name == "AdamW" |
| 46 | assert [group.optimizer_name for group in cfg.optimizer.param_groups] == ["SparseAdam", "AdamW"] | 46 | assert [group.optimizer_name for group in cfg.optimizer.param_groups] == ["SparseAdam", "AdamW"] |
| 47 | 47 | ||
| @@ -118,7 +118,7 @@ class TestRealModelReconciliation: | |||
| 118 | def test_pattern_layouts_and_buckets_partition_the_debugmodel(self): | 118 | def test_pattern_layouts_and_buckets_partition_the_debugmodel(self): |
| 119 | from tests.unit_tests.models.mtp_test_utils import build_cpu_model | 119 | from tests.unit_tests.models.mtp_test_utils import build_cpu_model |
| 120 | 120 | ||
| 121 | - trainer = deepseek_v4_1_debugmodel_multimodal() | 121 | + trainer = deepseek_v4_1_debugmodel_text() |
| 122 | model = build_cpu_model(trainer.model_spec.model) | 122 | model = build_cpu_model(trainer.model_spec.model) |
| 123 | fqns = [name for name, _ in model.named_parameters()] | 123 | fqns = [name for name, _ in model.named_parameters()] |
| 124 | 124 | ||
| @@ -157,7 +157,7 @@ class TestRealModelReconciliation: | |||
| 157 | assert not unexpected, sorted(unexpected)[:5] | 157 | assert not unexpected, sorted(unexpected)[:5] |
| 158 | 158 | ||
| 159 | def test_materialize_swaps_param_groups_to_distmuon_plus_adamw(self): | 159 | def test_materialize_swaps_param_groups_to_distmuon_plus_adamw(self): |
| 160 | - trainer = deepseek_v4_1_debugmodel_multimodal() | 160 | + trainer = deepseek_v4_1_debugmodel_text() |
| 161 | trainer.optimizer.name = "Muon" | 161 | trainer.optimizer.name = "Muon" |
| 162 | trainer.optimizer.lr = 1.23e-4 | 162 | trainer.optimizer.lr = 1.23e-4 |
| 163 | trainer.optimizer.materialize() | 163 | trainer.optimizer.materialize() |
| @@ -20,9 +20,9 @@ from torch.distributed.checkpoint import HuggingFaceStorageReader, HuggingFaceSt | |||
| 20 | from torchtitan_npu.models.deepseek_v4_1 import ( | 20 | from torchtitan_npu.models.deepseek_v4_1 import ( |
| 21 | model_registry, | 21 | model_registry, |
| 22 | ) | 22 | ) |
| 23 | +from torchtitan_npu.models.deepseek_v4_1.engram.checkpoint import checkpoint_shard | ||
| 23 | from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter | 24 | from torchtitan_npu.models.deepseek_v4_1.state_dict_adapter import DeepSeekV41StateDictAdapter |
| 24 | from torchtitan_npu.models.deepseek_v4_1.vision.state_dict_adapter import DeepSeekV41VisionStateDictAdapter | 25 | from torchtitan_npu.models.deepseek_v4_1.vision.state_dict_adapter import DeepSeekV41VisionStateDictAdapter |
| 25 | -from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import load_dcp_model | ||
| 26 | 26 | ||
| 27 | 27 | ||
| 28 | def _build_model_config(): | 28 | def _build_model_config(): |
| @@ -162,11 +162,9 @@ class TestComposedAdapterPartition: | |||
| 162 | assert torch.equal(local1[k], local2[k]), f"key {k} differs" | 162 | assert torch.equal(local1[k], local2[k]), f"key {k} differs" |
| 163 | 163 | ||
| 164 | 164 | ||
| 165 | -@pytest.mark.skipif( | 165 | +@pytest.mark.skipif(not hasattr(dcp, "CheckpointableTensor"), reason="PyTorch CheckpointableTensor support is required") |
| 166 | - not hasattr(dcp, "CheckpointableTensor"), reason="PyTorch CheckpointableTensor support is required" | 166 | +@pytest.mark.parametrize("shards", [2, 4], ids=["two-shards", "four-shards"]) |
| 167 | -) | 167 | +def test_engram_hf_shard_load_and_export(tmp_path, shards): |
| 168 | -@pytest.mark.parametrize("layout,shards", [("ep", 2), ("efsdp_ep", 4)]) | ||
| 169 | -def test_engram_hf_shard_load_and_export(tmp_path, layout, shards): | ||
| 170 | """DCP reads global HF rows into an EP shard and omits native padding on save.""" | 168 | """DCP reads global HF rows into an EP shard and omits native padding on save.""" |
| 171 | config = model_registry("deepseek_v4_1_debugmodel_text").model | 169 | config = model_registry("deepseek_v4_1_debugmodel_text").model |
| 172 | table = config.layers[1].engram.table | 170 | table = config.layers[1].engram.table |
| @@ -184,8 +182,8 @@ def test_engram_hf_shard_load_and_export(tmp_path, layout, shards): | |||
| 184 | rows = 48 // shards | 182 | rows = 48 // shards |
| 185 | offset = (shards - 1) * rows | 183 | offset = (shards - 1) * rows |
| 186 | valid = 41 - offset | 184 | valid = 41 - offset |
| 187 | - key = f"layers.1.engram.table.weight.{layout}_shard_{shards - 1:05d}_of_{shards:05d}" | 185 | + key = "layers.1.engram.table.weight" |
| 188 | - native = {key: torch.full((rows, 32), -1.0)} | 186 | + native = {key: checkpoint_shard(torch.full((rows, 32), -1.0), offset=offset, logical_rows=48)} |
| 189 | hf = adapter.to_hf(native) | 187 | hf = adapter.to_hf(native) |
| 190 | dcp.load(hf, storage_reader=adapter.get_hf_storage_reader(str(source))) | 188 | dcp.load(hf, storage_reader=adapter.get_hf_storage_reader(str(source))) |
| 191 | loaded = adapter.from_hf(hf) | 189 | loaded = adapter.from_hf(hf) |
| @@ -196,18 +194,10 @@ def test_engram_hf_shard_load_and_export(tmp_path, layout, shards): | |||
| 196 | full_native = adapter.from_hf({"layers.1.engram.embed.weight": weight}) | 194 | full_native = adapter.from_hf({"layers.1.engram.embed.weight": weight}) |
| 197 | native_path = tmp_path / "native" | 195 | native_path = tmp_path / "native" |
| 198 | full_key = "layers.1.engram.table.weight" | 196 | full_key = "layers.1.engram.table.weight" |
| 199 | - dcp.save( | 197 | + dcp.save(full_native, checkpoint_id=str(native_path)) |
| 200 | - { | ||
| 201 | - f"{full_key}.{layout}_shard_{rank:05d}_of_{shards:05d}": full_native[full_key][ | ||
| 202 | - rank * rows : (rank + 1) * rows | ||
| 203 | - ].clone() | ||
| 204 | - for rank in range(shards) | ||
| 205 | - }, | ||
| 206 | - checkpoint_id=str(native_path), | ||
| 207 | - ) | ||
| 208 | full_native[full_key].fill_(-1) | 198 | full_native[full_key].fill_(-1) |
| 209 | reader = dcp.FileSystemReader(str(native_path)) | 199 | reader = dcp.FileSystemReader(str(native_path)) |
| 210 | - load_dcp_model(full_native, reader) | 200 | + dcp.load(full_native, storage_reader=reader) |
| 211 | exported = adapter.to_hf(full_native) | 201 | exported = adapter.to_hf(full_native) |
| 212 | output = tmp_path / "export" | 202 | output = tmp_path / "export" |
| 213 | dcp.save(exported, storage_writer=HuggingFaceStorageWriter(str(output))) | 203 | dcp.save(exported, storage_writer=HuggingFaceStorageWriter(str(output))) |
| @@ -215,19 +205,6 @@ def test_engram_hf_shard_load_and_export(tmp_path, layout, shards): | |||
| 215 | dcp.load(restored, storage_reader=HuggingFaceStorageReader(str(output))) | 205 | dcp.load(restored, storage_reader=HuggingFaceStorageReader(str(output))) |
| 216 | torch.testing.assert_close(restored["layers.1.engram.embed.weight"], weight, rtol=0, atol=0) | 206 | torch.testing.assert_close(restored["layers.1.engram.embed.weight"], weight, rtol=0, atol=0) |
| 217 | 207 | ||
| 218 | - incomplete = tmp_path / "incomplete" | ||
| 219 | - dcp.save({key: torch.zeros(rows, 32)}, checkpoint_id=str(incomplete)) | ||
| 220 | - with pytest.raises(ValueError, match="Incomplete or unsupported Engram checkpoint shards"): | ||
| 221 | - load_dcp_model(full_native, dcp.FileSystemReader(str(incomplete))) | ||
| 222 | - | ||
| 223 | - mixed = tmp_path / "mixed" | ||
| 224 | - dcp.save( | ||
| 225 | - {f"{full_key}.{kind}_shard_00000_of_00002": torch.zeros(24, 32) for kind in ("ep", "efsdp_ep")}, | ||
| 226 | - checkpoint_id=str(mixed), | ||
| 227 | - ) | ||
| 228 | - with pytest.raises(ValueError, match="Mixed Engram checkpoint shard layouts"): | ||
| 229 | - load_dcp_model(full_native, dcp.FileSystemReader(str(mixed))) | ||
| 230 | - | ||
| 231 | 208 | ||
| 232 | def test_engram_quantized_hf_mapping(): | 209 | def test_engram_quantized_hf_mapping(): |
| 233 | """The adapter selects the CPU reader and maps official Engram keys.""" | 210 | """The adapter selects the CPU reader and maps official Engram keys.""" |
| @@ -353,9 +330,7 @@ class TestTextFlavorAdapter: | |||
| 353 | 330 | ||
| 354 | 331 | ||
| 355 | @pytest.mark.skipif(not torch.distributed.is_gloo_available(), reason="Gloo is required") | 332 | @pytest.mark.skipif(not torch.distributed.is_gloo_available(), reason="Gloo is required") |
| 356 | -@pytest.mark.skipif( | 333 | +@pytest.mark.skipif(not hasattr(dcp, "CheckpointableTensor"), reason="PyTorch CheckpointableTensor support is required") |
| 357 | - not hasattr(dcp, "CheckpointableTensor"), reason="PyTorch CheckpointableTensor support is required" | ||
| 358 | -) | ||
| 359 | def test_engram_hf_distributed_roundtrip(tmp_path): | 334 | def test_engram_hf_distributed_roundtrip(tmp_path): |
| 360 | worker = Path(__file__).with_name("engram_hf_worker.py") | 335 | worker = Path(__file__).with_name("engram_hf_worker.py") |
| 361 | result = subprocess.run( | 336 | result = subprocess.run( |
| @@ -179,7 +179,7 @@ def test_mxfp8_override_refreshes_derived_storage(monkeypatch): | |||
| 179 | torch.testing.assert_close(storage[1].float(), untouched_storage.float(), rtol=0, atol=0) | 179 | torch.testing.assert_close(storage[1].float(), untouched_storage.float(), rtol=0, atol=0) |
| 180 | torch.testing.assert_close(scale[1].float(), untouched_scale.float(), rtol=0, atol=0) | 180 | torch.testing.assert_close(scale[1].float(), untouched_scale.float(), rtol=0, atol=0) |
| 181 | 181 | ||
| 182 | - loaded = {name: torch.full_like(value, 0.125) for name, value in table.state_dict().items()} | 182 | + loaded = {"weight": torch.full_like(table.weight, 0.125)} |
| 183 | table.load_state_dict(loaded) | 183 | table.load_state_dict(loaded) |
| 184 | expected_storage, expected_scale = mxfp8._quantize_mxfp8_rows(table.weight) | 184 | expected_storage, expected_scale = mxfp8._quantize_mxfp8_rows(table.weight) |
| 185 | torch.testing.assert_close(storage.float(), expected_storage.float(), rtol=0, atol=0) | 185 | torch.testing.assert_close(storage.float(), expected_storage.float(), rtol=0, atol=0) |
| @@ -211,7 +211,11 @@ def test_joint_sharding_override_sets_storage_and_lookup_group(monkeypatch, back | |||
| 211 | table.parallelize(SimpleNamespace(get_optional_mesh=lambda name: ep)) | 211 | table.parallelize(SimpleNamespace(get_optional_mesh=lambda name: ep)) |
| 212 | assert table.weight.shape == (3, 128) | 212 | assert table.weight.shape == (3, 128) |
| 213 | assert table.ep_mesh is ep and table.lookup_mesh is joint | 213 | assert table.ep_mesh is ep and table.lookup_mesh is joint |
| 214 | - assert list(table.state_dict()) == ["weight.efsdp_ep_shard_00003_of_00004"] | 214 | + if hasattr(torch.distributed.checkpoint, "CheckpointableTensor"): |
| 215 | + state = table.state_dict() | ||
| 216 | + assert list(state) == ["weight"] | ||
| 217 | + assert state["weight"].global_shape == (12, 128) | ||
| 218 | + assert state["weight"].global_offsets == ((9, 0),) | ||
| 215 | if backend != "torch": | 219 | if backend != "torch": |
| 216 | monkeypatch.setattr(ascendc, "_dedicated_engram_group", lambda group: group) | 220 | monkeypatch.setattr(ascendc, "_dedicated_engram_group", lambda group: group) |
| 217 | monkeypatch.setattr(table, "_elastic_buffer_type", lambda: _FakeBuffer) | 221 | monkeypatch.setattr(table, "_elastic_buffer_type", lambda: _FakeBuffer) |
| @@ -6,11 +6,8 @@ | |||
| 6 | from __future__ import annotations | 6 | from __future__ import annotations |
| 7 | 7 | ||
| 8 | import ast | 8 | import ast |
| 9 | -from dataclasses import fields | ||
| 10 | from pathlib import Path | 9 | from pathlib import Path |
| 11 | 10 | ||
| 12 | -import torchtitan.distributed.flex_shard._optimizer_reshard_schedule as schedule | ||
| 13 | -import torchtitan.distributed.flex_shard.dist_muon as dist_muon | ||
| 14 | from torchtitan.distributed.flex_shard import BlockShard | 11 | from torchtitan.distributed.flex_shard import BlockShard |
| 15 | from torch.distributed.tensor import Shard | 12 | from torch.distributed.tensor import Shard |
| 16 | from torchtitan.distributed.parallel_dims import MeshAxisName | 13 | from torchtitan.distributed.parallel_dims import MeshAxisName |
| @@ -29,17 +26,6 @@ def _function_source(path: Path, name: str) -> str: | |||
| 29 | raise AssertionError(f"function {name!r} not found in {path}") | 26 | raise AssertionError(f"function {name!r} not found in {path}") |
| 30 | 27 | ||
| 31 | 28 | ||
| 32 | -def test_dist_muon_patch_admits_only_npu_storage(): | ||
| 33 | - path = _ROOT / "torchtitan_npu/patches/torchtitan/distributed/flex_shard/dist_muon.py" | ||
| 34 | - source = _function_source(path, "_validate_parameter_storage") | ||
| 35 | - | ||
| 36 | - assert "isinstance(param, DTensor)" in source | ||
| 37 | - assert 'local_device.type != "npu"' in source | ||
| 38 | - assert "requires NPU parameters" in source | ||
| 39 | - assert "len(local_devices) != 1" in source | ||
| 40 | - assert "requires one device per process" in source | ||
| 41 | - | ||
| 42 | - | ||
| 43 | def test_d2h_swap_cleanup_warns_before_releasing_the_pinned_buffer(): | 29 | def test_d2h_swap_cleanup_warns_before_releasing_the_pinned_buffer(): |
| 44 | path = _ROOT / "torchtitan_npu/extensions/novaswap/swap_primitive.py" | 30 | path = _ROOT / "torchtitan_npu/extensions/novaswap/swap_primitive.py" |
| 45 | source = _function_source(path, "d2h") | 31 | source = _function_source(path, "d2h") |
| @@ -132,31 +118,6 @@ def test_dsv4_unified_muon_policy_follows_paper_parameter_split(): | |||
| 132 | assert unified_muon_parameter in active_source | 118 | assert unified_muon_parameter in active_source |
| 133 | 119 | ||
| 134 | 120 | ||
| 135 | -def test_dist_muon_patch_backports_pr4122_shard_order_support(): | ||
| 136 | - patch_root = _ROOT / "torchtitan_npu/patches/torchtitan/distributed/flex_shard" | ||
| 137 | - optimizer_source = (patch_root / "optimizer_reshard.py").read_text() | ||
| 138 | - schedule_source = (patch_root / "_optimizer_reshard_schedule.py").read_text() | ||
| 139 | - dist_muon_source = (patch_root / "dist_muon.py").read_text() | ||
| 140 | - | ||
| 141 | - for source in (optimizer_source, schedule_source, dist_muon_source): | ||
| 142 | - assert "https://github.com/pytorch/torchtitan/pull/4122" in source | ||
| 143 | - assert "6ee6b10b934730df00cbcd0cab5c93d04ae2e38a" in source | ||
| 144 | - assert "class ComputeLayout" in optimizer_source | ||
| 145 | - assert "optimizer_reshard.ComputeLayout = ComputeLayout" in optimizer_source | ||
| 146 | - assert "flex_shard.ComputeLayout = ComputeLayout" in optimizer_source | ||
| 147 | - assert "def _build_dim0_shard_redistribution_plan" in schedule_source | ||
| 148 | - assert "def _lower_shard_order_to_strided_shards" in dist_muon_source | ||
| 149 | - assert "def _is_supported_orthogonal_dim0_shard_redistribution" in dist_muon_source | ||
| 150 | - | ||
| 151 | - | ||
| 152 | -def test_dist_muon_patch_rebinds_redistribution_group(): | ||
| 153 | - assert dist_muon._RedistributionGroup is schedule._RedistributionGroup | ||
| 154 | - assert tuple(field.name for field in fields(dist_muon._RedistributionGroup)) == ( | ||
| 155 | - "process_group", | ||
| 156 | - "participants", | ||
| 157 | - "mesh_axis_participants", | ||
| 158 | - "local_participant", | ||
| 159 | - ) | ||
| 160 | def test_dsv4_muon_indexer_query_uses_per_head_block_sharding(): | 121 | def test_dsv4_muon_indexer_query_uses_per_head_block_sharding(): |
| 161 | model_spec = model_registry("debugmodel") | 122 | model_spec = model_registry("debugmodel") |
| 162 | profile = _dsv4_muon_profile(model_spec) | 123 | profile = _dsv4_muon_profile(model_spec) |
| @@ -1,114 +0,0 @@ | |||
| 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() | ||
| @@ -71,13 +71,8 @@ p.add_argument('--recorded-steps') | |||
| 71 | p.add_argument('--checkpoint.folder', type=Path, dest='checkpoint_folder') | 71 | p.add_argument('--checkpoint.folder', type=Path, dest='checkpoint_folder') |
| 72 | p.add_argument('--checkpoint.create_seed_checkpoint', action='store_true', dest='create_seed_checkpoint') | 72 | p.add_argument('--checkpoint.create_seed_checkpoint', action='store_true', dest='create_seed_checkpoint') |
| 73 | args, _ = p.parse_known_args() | 73 | args, _ = p.parse_known_args() |
| 74 | -if args.create_seed_checkpoint or os.environ.get('TRAIN_FILE') == 'create_seed_checkpoint': | 74 | +if args.create_seed_checkpoint: |
| 75 | - if os.environ.get('TRAIN_FILE') == 'create_seed_checkpoint': | ||
| 76 | - entrypoint = Path(os.environ['PYTHONPATH'].split(os.pathsep)[0]) | ||
| 77 | - print('seed-imports=' + ','.join(sorted(path.name for path in entrypoint.iterdir()))) | ||
| 78 | - print('seed-processes=' + os.environ.get('NGPU', 'unset')) | ||
| 79 | (args.checkpoint_folder / 'step-0').mkdir(parents=True) | 75 | (args.checkpoint_folder / 'step-0').mkdir(parents=True) |
| 80 | - print('seed-value=' + str(args.value)) | ||
| 81 | print('seed-ngpu=' + os.environ.get('NGPU', 'unset')) | 76 | print('seed-ngpu=' + os.environ.get('NGPU', 'unset')) |
| 82 | raise SystemExit(0) | 77 | raise SystemExit(0) |
| 83 | print('runner-ngpu=' + os.environ.get('NGPU', 'unset')) | 78 | print('runner-ngpu=' + os.environ.get('NGPU', 'unset')) |
| @@ -127,109 +122,6 @@ def _compare(repo, refs, output, runner, *options): | |||
| 127 | ) | 122 | ) |
| 128 | 123 | ||
| 129 | 124 | ||
| 130 | -def test_loss_compare_distributed_seed_uses_baseline_layout_and_options(tmp_path, runner_repo): | ||
| 131 | - repo, refs = runner_repo | ||
| 132 | - output = tmp_path / "comparison" | ||
| 133 | - | ||
| 134 | - result = subprocess.run( | ||
| 135 | - [ | ||
| 136 | - sys.executable, | ||
| 137 | - str(CLI), | ||
| 138 | - refs[0], | ||
| 139 | - refs[0], | ||
| 140 | - "--runner=runner.sh", | ||
| 141 | - "--seed-mode=distributed", | ||
| 142 | - "--baseline-ngpus=2", | ||
| 143 | - "--test-ngpus=2", | ||
| 144 | - "--steps=2", | ||
| 145 | - "--baseline-options=--value=3", | ||
| 146 | - "--test-options=--value=3", | ||
| 147 | - "--output-dir", | ||
| 148 | - str(output), | ||
| 149 | - ], | ||
| 150 | - cwd=repo, | ||
| 151 | - text=True, | ||
| 152 | - capture_output=True, | ||
| 153 | - timeout=40, | ||
| 154 | - ) | ||
| 155 | - | ||
| 156 | - assert result.returncode == 0, result.stdout + result.stderr | ||
| 157 | - assert "seed-processes=2" in result.stdout | ||
| 158 | - assert "seed-value=3.0" in result.stdout | ||
| 159 | - assert "seed-imports=create_seed_checkpoint.py" in result.stdout | ||
| 160 | - report = json.loads((output / "comparison.json").read_text()) | ||
| 161 | - assert report["seed_mode"] == "distributed" | ||
| 162 | - assert report["passed"] | ||
| 163 | - assert "runner-value=3.0" in (output / "baseline" / "training.log").read_text() | ||
| 164 | - assert "runner-value=3.0" in (output / "test" / "training.log").read_text() | ||
| 165 | - | ||
| 166 | - | ||
| 167 | -def test_loss_compare_rejects_distributed_seed_with_custom_baseline_entrypoint(tmp_path): | ||
| 168 | - output = tmp_path / "comparison" | ||
| 169 | - | ||
| 170 | - result = subprocess.run( | ||
| 171 | - [ | ||
| 172 | - sys.executable, | ||
| 173 | - str(CLI), | ||
| 174 | - "HEAD", | ||
| 175 | - "HEAD", | ||
| 176 | - "--seed-mode=distributed", | ||
| 177 | - "--baseline-env=EXAMPLE=1,TRAIN_FILE=custom.train", | ||
| 178 | - "--baseline-env=EXAMPLE=2", | ||
| 179 | - "--output-dir", | ||
| 180 | - str(output), | ||
| 181 | - ], | ||
| 182 | - cwd=tmp_path, | ||
| 183 | - text=True, | ||
| 184 | - capture_output=True, | ||
| 185 | - timeout=10, | ||
| 186 | - ) | ||
| 187 | - | ||
| 188 | - assert result.returncode == 2, result.stdout + result.stderr | ||
| 189 | - assert "--seed-mode distributed cannot be combined with --baseline-env TRAIN_FILE" in result.stderr | ||
| 190 | - assert not output.exists() | ||
| 191 | - | ||
| 192 | - | ||
| 193 | -def test_loss_compare_bounds_training_when_runner_ignores_seed_entrypoint(tmp_path, runner_repo): | ||
| 194 | - repo, refs = runner_repo | ||
| 195 | - observed_steps = tmp_path / "observed_steps" | ||
| 196 | - training = ( | ||
| 197 | - "import argparse; from pathlib import Path; " | ||
| 198 | - "parser = argparse.ArgumentParser(); " | ||
| 199 | - "parser.add_argument('--training.steps', dest='steps', type=int); " | ||
| 200 | - "args, _ = parser.parse_known_args(); " | ||
| 201 | - f"Path({str(observed_steps)!r}).write_text(','.join(map(str, range(1, args.steps + 1))))" | ||
| 202 | - ) | ||
| 203 | - runner = repo / "ignore_entrypoint.sh" | ||
| 204 | - runner.write_text(f'#!/bin/bash\nexec {shlex.quote(sys.executable)} -c {shlex.quote(training)} "$@"\n') | ||
| 205 | - runner.chmod(0o755) | ||
| 206 | - output = tmp_path / "comparison" | ||
| 207 | - | ||
| 208 | - result = subprocess.run( | ||
| 209 | - [ | ||
| 210 | - sys.executable, | ||
| 211 | - str(CLI), | ||
| 212 | - refs[0], | ||
| 213 | - refs[0], | ||
| 214 | - f"--runner={runner}", | ||
| 215 | - "--seed-mode=distributed", | ||
| 216 | - "--steps=5", | ||
| 217 | - "--output-dir", | ||
| 218 | - str(output), | ||
| 219 | - ], | ||
| 220 | - cwd=repo, | ||
| 221 | - text=True, | ||
| 222 | - capture_output=True, | ||
| 223 | - timeout=40, | ||
| 224 | - ) | ||
| 225 | - | ||
| 226 | - assert result.returncode != 0 | ||
| 227 | - assert "check that the runner supports TRAIN_FILE=create_seed_checkpoint" in result.stderr | ||
| 228 | - assert observed_steps.read_text() == "1" | ||
| 229 | - assert not (output / "baseline").exists() | ||
| 230 | - assert not (output / "comparison.json").exists() | ||
| 231 | - | ||
| 232 | - | ||
| 233 | def _write_metric_runner(repo, name, value, *, ngpus=None): | 125 | def _write_metric_runner(repo, name, value, *, ngpus=None): |
| 234 | runner = repo / name | 126 | runner = repo / name |
| 235 | environment = f'export NGPU="${{NGPU:-{ngpus}}}"\n' if ngpus is not None else "" | 127 | environment = f'export NGPU="${{NGPU:-{ngpus}}}"\n' if ngpus is not None else "" |
| @@ -241,7 +133,6 @@ def _write_metric_runner(repo, name, value, *, ngpus=None): | |||
| 241 | return runner | 133 | return runner |
| 242 | 134 | ||
| 243 | 135 | ||
| 244 | -@pytest.mark.parametrize("seed_mode", ["unsharded", "distributed"]) | ||
| 245 | @pytest.mark.parametrize( | 136 | @pytest.mark.parametrize( |
| 246 | ("inherited_ngpu", "options", "baseline_ngpu", "test_ngpu", "baseline_config", "test_config"), | 137 | ("inherited_ngpu", "options", "baseline_ngpu", "test_ngpu", "baseline_config", "test_config"), |
| 247 | [ | 138 | [ |
| @@ -288,7 +179,6 @@ def test_loss_compare_preserves_runner_card_counts_unless_overridden( | |||
| 288 | tmp_path, | 179 | tmp_path, |
| 289 | runner_repo, | 180 | runner_repo, |
| 290 | monkeypatch, | 181 | monkeypatch, |
| 291 | - seed_mode, | ||
| 292 | inherited_ngpu, | 182 | inherited_ngpu, |
| 293 | options, | 183 | options, |
| 294 | baseline_ngpu, | 184 | baseline_ngpu, |
| @@ -311,7 +201,6 @@ def test_loss_compare_preserves_runner_card_counts_unless_overridden( | |||
| 311 | "--baseline-runner=base.sh", | 201 | "--baseline-runner=base.sh", |
| 312 | "--test-runner=test.sh", | 202 | "--test-runner=test.sh", |
| 313 | "--steps=2", | 203 | "--steps=2", |
| 314 | - f"--seed-mode={seed_mode}", | ||
| 315 | "--output-dir", | 204 | "--output-dir", |
| 316 | str(output), | 205 | str(output), |
| 317 | *options, | 206 | *options, |
| @@ -323,8 +212,7 @@ def test_loss_compare_preserves_runner_card_counts_unless_overridden( | |||
| 323 | ) | 212 | ) |
| 324 | 213 | ||
| 325 | assert result.returncode == 0, result.stdout + result.stderr | 214 | assert result.returncode == 0, result.stdout + result.stderr |
| 326 | - seed_ngpu = 1 if seed_mode == "unsharded" else baseline_ngpu | 215 | + assert "seed-ngpu=1\n" in result.stdout |
| 327 | - assert f"seed-ngpu={seed_ngpu}\n" in result.stdout | ||
| 328 | report = json.loads((output / "comparison.json").read_text()) | 216 | report = json.loads((output / "comparison.json").read_text()) |
| 329 | for side, ngpu, config in (("baseline", baseline_ngpu, baseline_config), ("test", test_ngpu, test_config)): | 217 | for side, ngpu, config in (("baseline", baseline_ngpu, baseline_config), ("test", test_ngpu, test_config)): |
| 330 | assert f"runner-ngpu={ngpu}\n" in (output / side / "training.log").read_text() | 218 | assert f"runner-ngpu={ngpu}\n" in (output / side / "training.log").read_text() |
| @@ -360,7 +248,7 @@ def test_loss_compare_runs_uncommitted_scripts_with_shared_seed(tmp_path, runner | |||
| 360 | ) | 248 | ) |
| 361 | 249 | ||
| 362 | assert result.returncode == (0 if test_value == 1 else 1), result.stdout + result.stderr | 250 | assert result.returncode == (0 if test_value == 1 else 1), result.stdout + result.stderr |
| 363 | - assert "seed-value=1.0" in result.stdout | 251 | + assert "seed-ngpu=1\n" in result.stdout |
| 364 | report = json.loads((output / "comparison.json").read_text()) | 252 | report = json.loads((output / "comparison.json").read_text()) |
| 365 | assert report["runner_scope"] == "working-tree" | 253 | assert report["runner_scope"] == "working-tree" |
| 366 | assert report["passed"] is (test_value == 1) | 254 | assert report["passed"] is (test_value == 1) |
| @@ -13,7 +13,6 @@ from typing import TYPE_CHECKING, Any, overload | |||
| 13 | import torch | 13 | import torch |
| 14 | import torch.distributed as dist | 14 | import torch.distributed as dist |
| 15 | from torch.profiler import record_function | 15 | from torch.profiler import record_function |
| 16 | -from torchtitan.components.checkpointer.utils import canonical_fqn | ||
| 17 | from torchtitan.components.optimizer import OptimizersContainer, ParamGroupConfig | 16 | from torchtitan.components.optimizer import OptimizersContainer, ParamGroupConfig |
| 18 | 17 | ||
| 19 | from torchtitan_npu.config import OptimizerConfig | 18 | from torchtitan_npu.config import OptimizerConfig |
| @@ -182,10 +181,6 @@ class HostSparseOptimizersContainer(OptimizersContainer): | |||
| 182 | # selected explicitly by the recipe, not inferred from a model type. | 181 | # selected explicitly by the recipe, not inferred from a model type. |
| 183 | group.pop("fused", None) | 182 | group.pop("fused", None) |
| 184 | group.pop("foreach", None) | 183 | group.pop("foreach", None) |
| 185 | - group["param_names"] = [ | ||
| 186 | - canonical_fqn(name) + getattr(param, "_engram_checkpoint_suffix", "") | ||
| 187 | - for name, param in zip(group["param_names"], group["params"], strict=True) | ||
| 188 | - ] | ||
| 189 | return groups, patterns | 184 | return groups, patterns |
| 190 | 185 | ||
| 191 | def _iter_host_tables(self) -> Iterator[Any]: | 186 | def _iter_host_tables(self) -> Iterator[Any]: |
| @@ -239,7 +234,21 @@ class HostSparseOptimizersContainer(OptimizersContainer): | |||
| 239 | for optimizer in self.optimizers: | 234 | for optimizer in self.optimizers: |
| 240 | if isinstance(optimizer, (torch.optim.Adam, torch.optim.AdamW, torch.optim.SparseAdam)): | 235 | if isinstance(optimizer, (torch.optim.Adam, torch.optim.AdamW, torch.optim.SparseAdam)): |
| 241 | _materialize_missing_adam_state(optimizer) | 236 | _materialize_missing_adam_state(optimizer) |
| 242 | - return super().state_dict() | 237 | + result = super().state_dict() |
| 238 | + for optimizer in self.optimizers: | ||
| 239 | + for group in optimizer.param_groups: | ||
| 240 | + for name, param in zip(group["param_names"], group["params"], strict=True): | ||
| 241 | + metadata = getattr(param, "_engram_checkpoint_metadata", None) | ||
| 242 | + if metadata is None: | ||
| 243 | + continue | ||
| 244 | + # Moments own the same global rows as their Host table. | ||
| 245 | + for state_name, value in optimizer.state[param].items(): | ||
| 246 | + if isinstance(value, torch.Tensor) and value.shape == param.shape: | ||
| 247 | + key = f"state.{name}.{state_name}" | ||
| 248 | + view = result[key].detach() | ||
| 249 | + view.__dict__.update(metadata) | ||
| 250 | + result[key] = view | ||
| 251 | + return result | ||
| 243 | 252 | ||
| 244 | def load_state_dict(self, state_dict: dict[str, Any]) -> None: | 253 | def load_state_dict(self, state_dict: dict[str, Any]) -> None: |
| 245 | for optimizer in self.optimizers: | 254 | for optimizer in self.optimizers: |
| @@ -8,7 +8,7 @@ | |||
| 8 | import torch.distributed.checkpoint as dcp | 8 | import torch.distributed.checkpoint as dcp |
| 9 | 9 | ||
| 10 | 10 | ||
| 11 | -def checkpoint_shard(weight, *, key, offset, logical_rows): | 11 | +def checkpoint_shard(weight, *, offset, logical_rows): |
| 12 | if not hasattr(dcp, "CheckpointableTensor"): | 12 | if not hasattr(dcp, "CheckpointableTensor"): |
| 13 | raise RuntimeError( | 13 | raise RuntimeError( |
| 14 | "Engram HF row shards require PyTorch CheckpointableTensor support; " | 14 | "Engram HF row shards require PyTorch CheckpointableTensor support; " |
| @@ -21,6 +21,5 @@ def checkpoint_shard(weight, *, key, offset, logical_rows): | |||
| 21 | result.global_offsets = ((offset, 0),) if rows else () | 21 | result.global_offsets = ((offset, 0),) if rows else () |
| 22 | result.local_offsets = ((0, 0),) if rows else () | 22 | result.local_offsets = ((0, 0),) if rows else () |
| 23 | result.local_sizes = ((rows, weight.shape[1]),) if rows else () | 23 | result.local_sizes = ((rows, weight.shape[1]),) if rows else () |
| 24 | - result._engram_native_key = key | ||
| 25 | result._engram_valid_rows = rows | 24 | result._engram_valid_rows = rows |
| 26 | return result | 25 | return result |
| @@ -12,6 +12,7 @@ from typing import cast | |||
| 12 | 12 | ||
| 13 | import torch | 13 | import torch |
| 14 | import torch.distributed as dist | 14 | import torch.distributed as dist |
| 15 | +import torch.distributed.checkpoint as dcp | ||
| 15 | from torch.distributed.device_mesh import DeviceMesh | 16 | from torch.distributed.device_mesh import DeviceMesh |
| 16 | 17 | ||
| 17 | try: # torch builds differ in the opaque-object custom-class API surface | 18 | try: # torch builds differ in the opaque-object custom-class API surface |
| @@ -25,6 +26,7 @@ except ImportError: # torch build without the opaque-object custom-class API | |||
| 25 | _HAS_OPAQUE_OBJECT_API = False | 26 | _HAS_OPAQUE_OBJECT_API = False |
| 26 | from torchtitan.tools.logging import logger | 27 | from torchtitan.tools.logging import logger |
| 27 | 28 | ||
| 29 | +from .checkpoint import checkpoint_shard | ||
| 28 | from .core import EngramTable | 30 | from .core import EngramTable |
| 29 | from .lookup import HostEngramLookup, _lookup_grad_rows, _lookup_rows | 31 | from .lookup import HostEngramLookup, _lookup_grad_rows, _lookup_rows |
| 30 | 32 | ||
| @@ -86,21 +88,30 @@ class HostEngramTable(EngramTable): | |||
| 86 | 88 | ||
| 87 | def _mark_host_weight(self) -> None: | 89 | def _mark_host_weight(self) -> None: |
| 88 | # Optimizer construction follows parallelize/to_empty, so preserve the | 90 | # Optimizer construction follows parallelize/to_empty, so preserve the |
| 89 | - # Host marker and checkpoint shard suffix on replacement parameters. | 91 | + # Host marker and global row geometry survive parameter replacement. |
| 90 | self.weight._engram_host_offload = True # type: ignore[attr-defined] | 92 | self.weight._engram_host_offload = True # type: ignore[attr-defined] |
| 91 | - self.weight._engram_checkpoint_suffix = self._checkpoint_suffix() # type: ignore[attr-defined] | 93 | + shard_rank = self._table_mesh.get_local_rank() if self._table_mesh is not None else self._ep_rank |
| 94 | + shape = tuple(self.weight.shape) | ||
| 95 | + self.weight._engram_checkpoint_metadata = { # type: ignore[attr-defined] | ||
| 96 | + "global_shape": (self.num_embeddings, self.embedding_dim), | ||
| 97 | + "global_offsets": ((shard_rank * shape[0], 0),), | ||
| 98 | + "local_offsets": ((0, 0),), | ||
| 99 | + "local_sizes": (shape,), | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + def _checkpoint_view(self, tensor): | ||
| 103 | + if not hasattr(dcp, "CheckpointableTensor") and tuple(tensor.shape) == ( | ||
| 104 | + self.num_embeddings, | ||
| 105 | + self.embedding_dim, | ||
| 106 | + ): | ||
| 107 | + return tensor | ||
| 108 | + shard_rank = self._table_mesh.get_local_rank() if self._table_mesh is not None else self._ep_rank | ||
| 109 | + return checkpoint_shard(tensor, offset=shard_rank * self.weight.shape[0], logical_rows=self.num_embeddings) | ||
| 92 | 110 | ||
| 93 | @property | 111 | @property |
| 94 | def lookup_mesh(self): | 112 | def lookup_mesh(self): |
| 95 | return self._table_mesh if self._table_mesh is not None else self.ep_mesh | 113 | return self._table_mesh if self._table_mesh is not None else self.ep_mesh |
| 96 | 114 | ||
| 97 | - def _checkpoint_suffix(self) -> str: | ||
| 98 | - if self._table_mesh is not None: | ||
| 99 | - return f".efsdp_ep_shard_{self._table_mesh.get_local_rank():05d}_of_{self._table_mesh.size():05d}" | ||
| 100 | - if self._ep_size <= 1: | ||
| 101 | - return "" | ||
| 102 | - return f".ep_shard_{self._ep_rank:05d}_of_{self._ep_size:05d}" | ||
| 103 | - | ||
| 104 | def parallelize(self, parallel_dims) -> None: | 115 | def parallelize(self, parallel_dims) -> None: |
| 105 | ep_mesh = parallel_dims.get_optional_mesh("ep") | 116 | ep_mesh = parallel_dims.get_optional_mesh("ep") |
| 106 | ep_size = ep_mesh.size() if ep_mesh is not None else 1 | 117 | ep_size = ep_mesh.size() if ep_mesh is not None else 1 |
| @@ -311,34 +322,8 @@ class HostEngramTable(EngramTable): | |||
| 311 | 322 | ||
| 312 | def _save_to_state_dict(self, destination, prefix, keep_vars): | 323 | def _save_to_state_dict(self, destination, prefix, keep_vars): |
| 313 | super()._save_to_state_dict(destination, prefix, keep_vars) | 324 | super()._save_to_state_dict(destination, prefix, keep_vars) |
| 314 | - suffix = self._checkpoint_suffix() | 325 | + key = prefix + "weight" |
| 315 | - if suffix: | 326 | + destination[key] = self._checkpoint_view(destination[key]) |
| 316 | - destination[prefix + "weight" + suffix] = destination.pop(prefix + "weight") | ||
| 317 | - | ||
| 318 | - def _load_from_state_dict( | ||
| 319 | - self, | ||
| 320 | - state_dict, | ||
| 321 | - prefix, | ||
| 322 | - local_metadata, | ||
| 323 | - strict, | ||
| 324 | - missing_keys, | ||
| 325 | - unexpected_keys, | ||
| 326 | - error_msgs, | ||
| 327 | - ): | ||
| 328 | - suffix = self._checkpoint_suffix() | ||
| 329 | - shard_key = prefix + "weight" + suffix | ||
| 330 | - weight_key = prefix + "weight" | ||
| 331 | - if suffix and shard_key in state_dict: | ||
| 332 | - state_dict[weight_key] = state_dict.pop(shard_key) | ||
| 333 | - super()._load_from_state_dict( | ||
| 334 | - state_dict, | ||
| 335 | - prefix, | ||
| 336 | - local_metadata, | ||
| 337 | - strict, | ||
| 338 | - missing_keys, | ||
| 339 | - unexpected_keys, | ||
| 340 | - error_msgs, | ||
| 341 | - ) | ||
| 342 | 327 | ||
| 343 | def accumulate_sparse_gradient( | 328 | def accumulate_sparse_gradient( |
| 344 | self, | 329 | self, |
| @@ -177,9 +177,9 @@ class DeepSeekV41StateDictAdapter(DeepSeekV3StateDictAdapter): | |||
| 177 | raise ValueError(f"HF checkpoint contains Engram for unconfigured layer {layer_id}") | 177 | raise ValueError(f"HF checkpoint contains Engram for unconfigured layer {layer_id}") |
| 178 | abstract = re.sub(r"(\d+)", "{}", key, count=1) | 178 | abstract = re.sub(r"(\d+)", "{}", key, count=1) |
| 179 | local_key = self.from_hf_map[abstract].format(layer_id) | 179 | local_key = self.from_hf_map[abstract].format(layer_id) |
| 180 | - if hasattr(value, "_engram_native_key"): | 180 | + if hasattr(value, "_engram_valid_rows"): |
| 181 | value[value._engram_valid_rows :].zero_() | 181 | value[value._engram_valid_rows :].zero_() |
| 182 | - state_dict[value._engram_native_key] = value | 182 | + state_dict[local_key] = value |
| 183 | continue | 183 | continue |
| 184 | scale = hf_state_dict.get(key.removesuffix("weight") + "scale") if key.endswith(".weight") else None | 184 | scale = hf_state_dict.get(key.removesuffix("weight") + "scale") if key.endswith(".weight") else None |
| 185 | if scale is not None: | 185 | if scale is not None: |
| @@ -250,24 +250,26 @@ class DeepSeekV41StateDictAdapter(DeepSeekV3StateDictAdapter): | |||
| 250 | 250 | ||
| 251 | for key, value in state_dict.items(): | 251 | for key, value in state_dict.items(): |
| 252 | if ".engram.table.weight" in key: | 252 | if ".engram.table.weight" in key: |
| 253 | - match = re.fullmatch( | 253 | + match = re.fullmatch(r"layers\.(\d+)\.engram\.table\.weight", key) |
| 254 | - r"layers\.(\d+)\.engram\.table\.weight(?:\.(?:efsdp_)?ep_shard_(\d+)_of_(\d+))?", key | ||
| 255 | - ) | ||
| 256 | if match is None: | 254 | if match is None: |
| 257 | raise ValueError(f"Unexpected Engram table key: {key}") | 255 | raise ValueError(f"Unexpected Engram table key: {key}") |
| 258 | layer_id = int(match[1]) | 256 | layer_id = int(match[1]) |
| 259 | config = self._engram_tables[layer_id] | 257 | config = self._engram_tables[layer_id] |
| 260 | - rank, size = (int(match[2]), int(match[3])) if match[2] else (0, 1) | 258 | + shard_rows = config.num_embeddings |
| 261 | - if not 0 <= rank < size or config.num_embeddings % size: | 259 | + offset = 0 |
| 262 | - raise ValueError(f"Invalid Engram table shard: {key}") | 260 | + if hasattr(value, "global_shape"): |
| 263 | - shard_rows = config.num_embeddings // size | 261 | + if tuple(value.global_shape) != (config.num_embeddings, config.embedding_dim): |
| 262 | + raise ValueError(f"Unexpected global Engram table shape for {key}: {value.global_shape}") | ||
| 263 | + offset = value.global_offsets[0][0] | ||
| 264 | + shard_rows = value.local_sizes[0][0] | ||
| 264 | if tuple(value.shape) != (shard_rows, config.embedding_dim): | 265 | if tuple(value.shape) != (shard_rows, config.embedding_dim): |
| 265 | raise ValueError(f"Unexpected native Engram shard shape for {key}: {value.shape}") | 266 | raise ValueError(f"Unexpected native Engram shard shape for {key}: {value.shape}") |
| 266 | logical_rows = sum(config.head_vocab_sizes) | 267 | logical_rows = sum(config.head_vocab_sizes) |
| 268 | + # Full-table HF exports also support writers that do not read shard metadata. | ||
| 267 | hf_state_dict[f"layers.{layer_id}.engram.embed.weight"] = ( | 269 | hf_state_dict[f"layers.{layer_id}.engram.embed.weight"] = ( |
| 268 | - value[:logical_rows] | 270 | + checkpoint_shard(value, offset=offset, logical_rows=logical_rows) |
| 269 | - if size == 1 | 271 | + if offset != 0 or shard_rows != config.num_embeddings |
| 270 | - else checkpoint_shard(value, key=key, offset=rank * shard_rows, logical_rows=logical_rows) | 272 | + else value[:logical_rows] |
| 271 | ) | 273 | ) |
| 272 | 274 | ||
| 273 | elif any(t in key for t in ("compressor", "indexer")): | 275 | elif any(t in key for t in ("compressor", "indexer")): |
| @@ -151,43 +151,6 @@ def _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir): | |||
| 151 | dcp.save(hf_state_dict, storage_writer=storage_writer) | 151 | dcp.save(hf_state_dict, storage_writer=storage_writer) |
| 152 | 152 | ||
| 153 | 153 | ||
| 154 | -def load_dcp_model(state_dict, reader): | ||
| 155 | - """Load native CPU Engram shards into full-table views for offline export. | ||
| 156 | - | ||
| 157 | - This is a converter implementation detail, not a StateDictAdapter hook. | ||
| 158 | - Unsupported or incomplete table layouts must fail before loading weights. | ||
| 159 | - """ | ||
| 160 | - metadata = reader.read_metadata().state_dict_metadata | ||
| 161 | - targets = dict(state_dict) | ||
| 162 | - for key, target in state_dict.items(): | ||
| 163 | - if not key.endswith(".engram.table.weight") or key in metadata: | ||
| 164 | - continue | ||
| 165 | - layouts = [ | ||
| 166 | - (prefix, sorted(k for k in metadata if k.startswith(key + prefix))) | ||
| 167 | - for prefix in (".ep_shard_", ".efsdp_ep_shard_") | ||
| 168 | - ] | ||
| 169 | - layouts = [(prefix, shards) for prefix, shards in layouts if shards] | ||
| 170 | - if len(layouts) > 1: | ||
| 171 | - raise ValueError(f"Mixed Engram checkpoint shard layouts for {key}") | ||
| 172 | - prefix, shards = layouts[0] if layouts else ("", []) | ||
| 173 | - if not shards: | ||
| 174 | - raise ValueError(f"Missing or unsupported Engram checkpoint layout for {key}") | ||
| 175 | - targets.pop(key) | ||
| 176 | - offset = 0 | ||
| 177 | - for rank, shard_key in enumerate(shards): | ||
| 178 | - suffix = f"{prefix}{rank:05d}_of_{len(shards):05d}" | ||
| 179 | - if shard_key != key + suffix: | ||
| 180 | - raise ValueError(f"Incomplete or unsupported Engram checkpoint shards for {key}") | ||
| 181 | - shape = metadata[shard_key].size | ||
| 182 | - if len(shape) != 2 or shape[1] != target.shape[1] or offset + shape[0] > target.shape[0]: | ||
| 183 | - raise ValueError(f"Engram checkpoint geometry differs from model config: {shard_key}") | ||
| 184 | - targets[shard_key] = target[offset : offset + shape[0]] | ||
| 185 | - offset += shape[0] | ||
| 186 | - if offset != target.shape[0]: | ||
| 187 | - raise ValueError(f"Engram checkpoint does not cover the full table: {key}") | ||
| 188 | - dcp.load(targets, storage_reader=reader) | ||
| 189 | - | ||
| 190 | - | ||
| 191 | @torch.inference_mode() | 154 | @torch.inference_mode() |
| 192 | def convert_to_hf(args: argparse.Namespace): | 155 | def convert_to_hf(args: argparse.Namespace): |
| 193 | input_dir = args.input_dir | 156 | input_dir = args.input_dir |
| @@ -220,7 +183,7 @@ def convert_to_hf(args: argparse.Namespace): | |||
| 220 | # allocate state dict memory with empty weights to load checkpoint | 183 | # allocate state dict memory with empty weights to load checkpoint |
| 221 | state_dict = model.state_dict() | 184 | state_dict = model.state_dict() |
| 222 | reader = ParallelFileSystemReader(input_dir, thread_count=read_threads) | 185 | reader = ParallelFileSystemReader(input_dir, thread_count=read_threads) |
| 223 | - load_dcp_model(state_dict, reader) | 186 | + dcp.load(state_dict, storage_reader=reader) |
| 224 | 187 | ||
| 225 | target_dtype = TORCH_DTYPE_MAP[export_dtype] | 188 | target_dtype = TORCH_DTYPE_MAP[export_dtype] |
| 226 | _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir) | 189 | _save_as_hf(state_dict, sd_adapter, target_dtype, output_dir) |
| @@ -33,6 +33,7 @@ from pathlib import Path | |||
| 33 | from typing import Any | 33 | from typing import Any |
| 34 | 34 | ||
| 35 | import torch | 35 | import torch |
| 36 | +import torch.distributed.checkpoint as dcp | ||
| 36 | from torch import nn | 37 | from torch import nn |
| 37 | 38 | ||
| 38 | _SCRIPT_DIR = Path(__file__).resolve().parent | 39 | _SCRIPT_DIR = Path(__file__).resolve().parent |
| @@ -802,7 +803,7 @@ def _load_dcp_state_dict(model, input_dir: Path, master_dtype: str, read_threads | |||
| 802 | """Load the DCP checkpoint into the model's state-dict container.""" | 803 | """Load the DCP checkpoint into the model's state-dict container.""" |
| 803 | from torchtitan.config import TORCH_DTYPE_MAP | 804 | from torchtitan.config import TORCH_DTYPE_MAP |
| 804 | 805 | ||
| 805 | - from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import ParallelFileSystemReader, load_dcp_model | 806 | + from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import ParallelFileSystemReader |
| 806 | 807 | ||
| 807 | state_dict = model.state_dict() | 808 | state_dict = model.state_dict() |
| 808 | # The model is built in float32, but dcp.load copies the stored dtype into | 809 | # The model is built in float32, but dcp.load copies the stored dtype into |
| @@ -814,7 +815,7 @@ def _load_dcp_state_dict(model, input_dir: Path, master_dtype: str, read_threads | |||
| 814 | if value.is_floating_point() and value.dtype != container_dtype and ".engram.table.weight" not in fqn: | 815 | if value.is_floating_point() and value.dtype != container_dtype and ".engram.table.weight" not in fqn: |
| 815 | state_dict[fqn] = value.detach().to(container_dtype) | 816 | state_dict[fqn] = value.detach().to(container_dtype) |
| 816 | reader = ParallelFileSystemReader(str(input_dir), thread_count=read_threads) | 817 | reader = ParallelFileSystemReader(str(input_dir), thread_count=read_threads) |
| 817 | - load_dcp_model(state_dict, reader) | 818 | + dcp.load(state_dict, storage_reader=reader) |
| 818 | return state_dict | 819 | return state_dict |
| 819 | 820 | ||
| 820 | 821 | ||