Merged
fix: 修复 Engram SparseAdam checkpoint 跨 EP 拓扑恢复 #1092
没有杰Add on Oct 26
fix: 修复 Engram SparseAdam checkpoint 跨 EP 拓扑恢复 #1092
Merged
Total: 15 files changed+129-491
| @@ -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 | #### 输出与清理 | 160 | #### 输出与清理 |
| @@ -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() | ||
| @@ -25,11 +25,6 @@ TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close | |||
| 25 | 随机种子、TensorBoard 配置不能放入 `--baseline-options` / `--test-options`。 | 25 | 随机种子、TensorBoard 配置不能放入 `--baseline-options` / `--test-options`。 |
| 26 | `--no-seed-checkpoint` 可跳过共享 checkpoint。 | 26 | `--no-seed-checkpoint` 可跳过共享 checkpoint。 |
| 27 | 27 | ||
| 28 | -Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-mode distributed`。 | ||
| 29 | -该模式按 baseline 的 NPU 数、入口配置及额外选项构建模型,在训练前保存 step-0, | ||
| 30 | -不执行 forward、backward 或 optimizer 更新。两侧仍加载同一份权重;checkpoint | ||
| 31 | -是否支持两侧不同的并行布局由模型决定,不兼容时加载会失败。 | ||
| 32 | - | ||
| 33 | 用法示例: | 28 | 用法示例: |
| 34 | 29 | ||
| 35 | 1. 比较自行准备的两个训练脚本 | 30 | 1. 比较自行准备的两个训练脚本 |
| @@ -109,10 +104,7 @@ Engram 等按并行布局保存原生 checkpoint 的模型,应使用 `--seed-m | |||
| 109 | - --seq-len:seed 和两侧训练的序列长度,默认 4096;例如 `--seq-len 2048`。 | 104 | - --seq-len:seed 和两侧训练的序列长度,默认 4096;例如 `--seq-len 2048`。 |
| 110 | - --ngpus:可选的两侧 NPU 进程数覆盖值;默认沿用环境变量和各自 runner 的卡数设置。 | 105 | - --ngpus:可选的两侧 NPU 进程数覆盖值;默认沿用环境变量和各自 runner 的卡数设置。 |
| 111 | 两侧拓扑不同时用 --baseline-ngpus / --test-ngpus 分别覆盖;显式卡数参数优先于 | 106 | 两侧拓扑不同时用 --baseline-ngpus / --test-ngpus 分别覆盖;显式卡数参数优先于 |
| 112 | - NGPU 环境变量。默认 unsharded seed 使用单进程初始化。 | 107 | + NGPU 环境变量。seed 使用单进程 CPU 初始化。 |
| 113 | -- --seed-mode:默认 unsharded 使用单卡 CPU 初始化;distributed 保留 baseline | ||
| 114 | - 的并行布局,需要与 baseline 相同的卡数和显存资源,runner 必须支持 TRAIN_FILE。 | ||
| 115 | - distributed 不能与 --baseline-env TRAIN_FILE=... 同用。 | ||
| 116 | - --output-dir:结果输出目录,必须为空或尚未存在;默认在当前目录的 | 108 | - --output-dir:结果输出目录,必须为空或尚未存在;默认在当前目录的 |
| 117 | outputs/compare_results/ 下创建独立的结果子目录。 | 109 | outputs/compare_results/ 下创建独立的结果子目录。 |
| 118 | - --cleanup-after-test / --no-cleanup-after-test:默认清理 seed 目录和临时 | 110 | - --cleanup-after-test / --no-cleanup-after-test:默认清理 seed 目录和临时 |
| @@ -333,34 +325,25 @@ def build_seed_command( | |||
| 333 | *, | 325 | *, |
| 334 | deterministic: bool = True, | 326 | deterministic: bool = True, |
| 335 | seq_len: int = DEFAULT_SEQ_LEN, | 327 | seq_len: int = DEFAULT_SEQ_LEN, |
| 336 | - distributed: bool = False, | ||
| 337 | - options: str = "", | ||
| 338 | ) -> list[str]: | 328 | ) -> list[str]: |
| 339 | - # CPU seed creation skips parallelize_fn but still builds an optimizer; | 329 | + # Seed creation skips parallelize_fn but still builds an optimizer. Use |
| 340 | - # DistMuon requires DTensor parameters. Distributed creation preserves | 330 | + # AdamW here because DistMuon requires DTensor parameters. Only model |
| 341 | - # the baseline optimizer and layout. Both modes save only model weights. | 331 | + # weights are saved; training keeps the runner's optimizer selection. |
| 342 | - initialization = ( | ||
| 343 | - [*shlex.split(options), "--checkpoint.no-create-seed-checkpoint", "--training.steps=1"] | ||
| 344 | - if distributed | ||
| 345 | - else [ | ||
| 346 | - "--checkpoint.create_seed_checkpoint", | ||
| 347 | - "--optimizer.name=AdamW", | ||
| 348 | - "--parallelism.data-parallel-replicate-degree=1", | ||
| 349 | - "--parallelism.data-parallel-shard-degree=1", | ||
| 350 | - "--parallelism.tensor-parallel-degree=1", | ||
| 351 | - "--parallelism.pipeline-parallel-degree=1", | ||
| 352 | - "--parallelism.context-parallel-degree=1", | ||
| 353 | - "--parallelism.expert-parallel-degree=1", | ||
| 354 | - ] | ||
| 355 | - ) | ||
| 356 | return [ | 332 | return [ |
| 357 | str(runner), | 333 | str(runner), |
| 358 | f"--dump_folder={dump_folder}", | 334 | f"--dump_folder={dump_folder}", |
| 359 | - *initialization, | 335 | + "--checkpoint.create_seed_checkpoint", |
| 360 | "--checkpoint.enable", | 336 | "--checkpoint.enable", |
| 361 | "--checkpoint.no-load-only", | 337 | "--checkpoint.no-load-only", |
| 362 | f"--checkpoint.folder={dump_folder / 'checkpoint'}", | 338 | f"--checkpoint.folder={dump_folder / 'checkpoint'}", |
| 363 | "--checkpoint.last-save-model-only", | 339 | "--checkpoint.last-save-model-only", |
| 340 | + "--optimizer.name=AdamW", | ||
| 341 | + "--parallelism.data-parallel-replicate-degree=1", | ||
| 342 | + "--parallelism.data-parallel-shard-degree=1", | ||
| 343 | + "--parallelism.tensor-parallel-degree=1", | ||
| 344 | + "--parallelism.pipeline-parallel-degree=1", | ||
| 345 | + "--parallelism.context-parallel-degree=1", | ||
| 346 | + "--parallelism.expert-parallel-degree=1", | ||
| 364 | *_fixed_training_options(deterministic=deterministic, seq_len=seq_len), | 347 | *_fixed_training_options(deterministic=deterministic, seq_len=seq_len), |
| 365 | ] | 348 | ] |
| 366 | 349 | ||
| @@ -685,7 +668,6 @@ def write_report( | |||
| 685 | mode: str, | 668 | mode: str, |
| 686 | thresholds: MetricThresholds, | 669 | thresholds: MetricThresholds, |
| 687 | comparisons: Sequence[MetricComparison], | 670 | comparisons: Sequence[MetricComparison], |
| 688 | - seed_mode: str = "unsharded", | ||
| 689 | ) -> None: | 671 | ) -> None: |
| 690 | report: dict[str, Any] = { | 672 | report: dict[str, Any] = { |
| 691 | "baseline": { | 673 | "baseline": { |
| @@ -703,7 +685,6 @@ def write_report( | |||
| 703 | "runner_scope": runner_scope, | 685 | "runner_scope": runner_scope, |
| 704 | "expected_step_range": {"first": 1, "last": expected_steps}, | 686 | "expected_step_range": {"first": 1, "last": expected_steps}, |
| 705 | "mode": mode, | 687 | "mode": mode, |
| 706 | - "seed_mode": seed_mode, | ||
| 707 | "thresholds": asdict(thresholds), | 688 | "thresholds": asdict(thresholds), |
| 708 | "passed": all(result.passed for result in comparisons), | 689 | "passed": all(result.passed for result in comparisons), |
| 709 | "metrics": [asdict(result) for result in comparisons], | 690 | "metrics": [asdict(result) for result in comparisons], |
| @@ -822,14 +803,7 @@ def parse_args() -> argparse.Namespace: | |||
| 822 | default=[], | 803 | default=[], |
| 823 | help="extra KEY=VALUE[,...] environment for the test run (repeatable)", | 804 | help="extra KEY=VALUE[,...] environment for the test run (repeatable)", |
| 824 | ) | 805 | ) |
| 825 | - seed_group = parser.add_mutually_exclusive_group() | 806 | + parser.add_argument( |
| 826 | - seed_group.add_argument( | ||
| 827 | - "--seed-mode", | ||
| 828 | - choices=("unsharded", "distributed"), | ||
| 829 | - default="unsharded", | ||
| 830 | - help="shared checkpoint initialization: single-rank CPU or baseline's distributed layout", | ||
| 831 | - ) | ||
| 832 | - seed_group.add_argument( | ||
| 833 | "--no-seed-checkpoint", | 807 | "--no-seed-checkpoint", |
| 834 | action="store_true", | 808 | action="store_true", |
| 835 | help="initialize both runs from deterministic seeds instead of one checkpoint", | 809 | help="initialize both runs from deterministic seeds instead of one checkpoint", |
| @@ -842,8 +816,6 @@ def parse_args() -> argparse.Namespace: | |||
| 842 | args = parser.parse_args() | 816 | args = parser.parse_args() |
| 843 | if (args.baseline_ref is None) != (args.test_ref is None): | 817 | if (args.baseline_ref is None) != (args.test_ref is None): |
| 844 | parser.error("provide both baseline_ref and test_ref, or omit both to use the current working tree") | 818 | parser.error("provide both baseline_ref and test_ref, or omit both to use the current working tree") |
| 845 | - if args.seed_mode == "distributed" and "TRAIN_FILE" in _merged_env(args.baseline_env): | ||
| 846 | - parser.error("--seed-mode distributed cannot be combined with --baseline-env TRAIN_FILE=...") | ||
| 847 | if args.steps <= 0: | 819 | if args.steps <= 0: |
| 848 | parser.error("--steps must be positive") | 820 | parser.error("--steps must be positive") |
| 849 | if args.seq_len <= 0: | 821 | if args.seq_len <= 0: |
| @@ -964,35 +936,20 @@ def main() -> None: | |||
| 964 | if not args.no_seed_checkpoint: | 936 | if not args.no_seed_checkpoint: |
| 965 | log_step("Creating shared seed checkpoint") | 937 | log_step("Creating shared seed checkpoint") |
| 966 | seed_dump = output_dir / "seed" | 938 | seed_dump = output_dir / "seed" |
| 967 | - distributed_seed = args.seed_mode == "distributed" | ||
| 968 | - seed_env = training_env(base_n if distributed_seed else 1, _merged_env(args.baseline_env)) | ||
| 969 | - if distributed_seed: | ||
| 970 | - # Use this CLI's helper even when the baseline ref predates it. | ||
| 971 | - # Expose only the helper, not sibling modules such as utils. | ||
| 972 | - seed_entrypoint = seed_dump / "entrypoint" | ||
| 973 | - seed_entrypoint.mkdir(parents=True) | ||
| 974 | - shutil.copy2(Path(__file__).with_name("create_seed_checkpoint.py"), seed_entrypoint) | ||
| 975 | - seed_env["TRAIN_FILE"] = "create_seed_checkpoint" | ||
| 976 | - seed_env["PYTHONPATH"] = os.pathsep.join( | ||
| 977 | - filter(None, (str(seed_entrypoint), seed_env.get("PYTHONPATH", ""))) | ||
| 978 | - ) | ||
| 979 | run_with_realtime_output( | 939 | run_with_realtime_output( |
| 980 | build_seed_command( | 940 | build_seed_command( |
| 981 | baseline_runner, | 941 | baseline_runner, |
| 982 | seed_dump, | 942 | seed_dump, |
| 983 | deterministic=not args.no_deterministic, | 943 | deterministic=not args.no_deterministic, |
| 984 | seq_len=args.seq_len, | 944 | seq_len=args.seq_len, |
| 985 | - distributed=distributed_seed, | ||
| 986 | - options=args.baseline_options, | ||
| 987 | ), | 945 | ), |
| 988 | cwd=baseline_worktree, | 946 | cwd=baseline_worktree, |
| 989 | - env=seed_env, | 947 | + env=training_env(1, _merged_env(args.baseline_env)), |
| 990 | log_file=seed_dump / "training.log", | 948 | log_file=seed_dump / "training.log", |
| 991 | ) | 949 | ) |
| 992 | seed_checkpoint = seed_dump / "checkpoint" / "step-0" | 950 | seed_checkpoint = seed_dump / "checkpoint" / "step-0" |
| 993 | if not seed_checkpoint.is_dir(): | 951 | if not seed_checkpoint.is_dir(): |
| 994 | - hint = "; check that the runner supports TRAIN_FILE=create_seed_checkpoint" if distributed_seed else "" | 952 | + raise RuntimeError(f"seed checkpoint was not created: {seed_checkpoint}") |
| 995 | - raise RuntimeError(f"seed checkpoint was not created: {seed_checkpoint}{hint}") | ||
| 996 | log_success(f"Seed checkpoint is ready: {seed_checkpoint}") | 953 | log_success(f"Seed checkpoint is ready: {seed_checkpoint}") |
| 997 | else: | 954 | else: |
| 998 | log_info("Shared seed checkpoint disabled; using deterministic seeds") | 955 | log_info("Shared seed checkpoint disabled; using deterministic seeds") |
| @@ -1072,7 +1029,6 @@ def main() -> None: | |||
| 1072 | mode=args.mode, | 1029 | mode=args.mode, |
| 1073 | thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS), | 1030 | thresholds=(thresholds if args.mode == "close" else BITWISE_THRESHOLDS), |
| 1074 | comparisons=comparisons, | 1031 | comparisons=comparisons, |
| 1075 | - seed_mode="none" if args.no_seed_checkpoint else args.seed_mode, | ||
| 1076 | ) | 1032 | ) |
| 1077 | log_success(f"Report written: {output_dir / 'comparison.json'}") | 1033 | log_success(f"Report written: {output_dir / 'comparison.json'}") |
| 1078 | if not all(result.passed for result in comparisons): | 1034 | if not all(result.passed for result in comparisons): |
| @@ -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 checkpoint, DefaultDeviceType | 14 | from torch.utils.checkpoint import checkpoint, DefaultDeviceType |
| 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 |
| @@ -91,7 +92,10 @@ def _host_table_config(): | |||
| 91 | ) | 92 | ) |
| 92 | 93 | ||
| 93 | 94 | ||
| 94 | -def test_host_offload_model_state_uses_rank_specific_shard_key(): | 95 | +@pytest.mark.skipif( |
| 96 | + not hasattr(torch.distributed.checkpoint, "CheckpointableTensor"), reason="CheckpointableTensor is required" | ||
| 97 | +) | ||
| 98 | +def test_host_offload_weight_and_moments_describe_global_row_shard(): | ||
| 95 | table = HostEngramTable(_host_table_config()) | 99 | table = HostEngramTable(_host_table_config()) |
| 96 | table.weight = torch.nn.Parameter(_ramp(5)) | 100 | table.weight = torch.nn.Parameter(_ramp(5)) |
| 97 | table._ep_rank = 1 | 101 | table._ep_rank = 1 |
| @@ -99,8 +103,27 @@ def test_host_offload_model_state_uses_rank_specific_shard_key(): | |||
| 99 | table._mark_host_weight() | 103 | table._mark_host_weight() |
| 100 | 104 | ||
| 101 | state = table.state_dict() | 105 | state = table.state_dict() |
| 102 | - assert "weight" not in state | 106 | + assert list(state) == ["weight"] |
| 103 | - assert list(state) == ["weight.ep_shard_00001_of_00002"] | 107 | + assert state["weight"].global_shape == (10, _DIM) |
| 108 | + assert state["weight"].global_offsets == ((5, 0),) | ||
| 109 | + assert state["weight"].local_offsets == ((0, 0),) | ||
| 110 | + assert state["weight"].local_sizes == ((5, _DIM),) | ||
| 111 | + | ||
| 112 | + model = torch.nn.Module() | ||
| 113 | + model.add_module("table", table) | ||
| 114 | + optimizer = host_mod.HostSparseOptimizersContainer.Config( | ||
| 115 | + implementation="for-loop", | ||
| 116 | + param_groups=[ParamGroupConfig(pattern=r"table\.weight$", optimizer_name="SparseAdam")], | ||
| 117 | + ).build(model_parts=[model]) | ||
| 118 | + | ||
| 119 | + optim_state = optimizer.state_dict() | ||
| 120 | + for name in ("exp_avg", "exp_avg_sq"): | ||
| 121 | + moment = optim_state[f"state.table.weight.{name}"] | ||
| 122 | + assert moment.global_shape == (10, _DIM) | ||
| 123 | + assert moment.global_offsets == ((5, 0),) | ||
| 124 | + assert moment.local_offsets == ((0, 0),) | ||
| 125 | + assert moment.local_sizes == ((5, _DIM),) | ||
| 126 | + assert moment.data_ptr() == optimizer.optimizers[0].state[table.weight][name].data_ptr() | ||
| 104 | 127 | ||
| 105 | restored = HostEngramTable(_host_table_config()) | 128 | restored = HostEngramTable(_host_table_config()) |
| 106 | restored.weight = torch.nn.Parameter(torch.zeros(5, _DIM)) | 129 | restored.weight = torch.nn.Parameter(torch.zeros(5, _DIM)) |
| @@ -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) |
| @@ -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() | ||
| @@ -50,13 +50,8 @@ p.add_argument('--recorded-steps') | |||
| 50 | p.add_argument('--checkpoint.folder', type=Path, dest='checkpoint_folder') | 50 | p.add_argument('--checkpoint.folder', type=Path, dest='checkpoint_folder') |
| 51 | p.add_argument('--checkpoint.create_seed_checkpoint', action='store_true', dest='create_seed_checkpoint') | 51 | p.add_argument('--checkpoint.create_seed_checkpoint', action='store_true', dest='create_seed_checkpoint') |
| 52 | args, _ = p.parse_known_args() | 52 | args, _ = p.parse_known_args() |
| 53 | -if args.create_seed_checkpoint or os.environ.get('TRAIN_FILE') == 'create_seed_checkpoint': | 53 | +if args.create_seed_checkpoint: |
| 54 | - if os.environ.get('TRAIN_FILE') == 'create_seed_checkpoint': | ||
| 55 | - entrypoint = Path(os.environ['PYTHONPATH'].split(os.pathsep)[0]) | ||
| 56 | - print('seed-imports=' + ','.join(sorted(path.name for path in entrypoint.iterdir()))) | ||
| 57 | - print('seed-processes=' + os.environ.get('NGPU', 'unset')) | ||
| 58 | (args.checkpoint_folder / 'step-0').mkdir(parents=True) | 54 | (args.checkpoint_folder / 'step-0').mkdir(parents=True) |
| 59 | - print('seed-value=' + str(args.value)) | ||
| 60 | print('seed-ngpu=' + os.environ.get('NGPU', 'unset')) | 55 | print('seed-ngpu=' + os.environ.get('NGPU', 'unset')) |
| 61 | raise SystemExit(0) | 56 | raise SystemExit(0) |
| 62 | print('runner-ngpu=' + os.environ.get('NGPU', 'unset')) | 57 | print('runner-ngpu=' + os.environ.get('NGPU', 'unset')) |
| @@ -106,109 +101,6 @@ def _compare(repo, refs, output, runner, *options): | |||
| 106 | ) | 101 | ) |
| 107 | 102 | ||
| 108 | 103 | ||
| 109 | -def test_loss_compare_distributed_seed_uses_baseline_layout_and_options(tmp_path, runner_repo): | ||
| 110 | - repo, refs = runner_repo | ||
| 111 | - output = tmp_path / "comparison" | ||
| 112 | - | ||
| 113 | - result = subprocess.run( | ||
| 114 | - [ | ||
| 115 | - sys.executable, | ||
| 116 | - str(CLI), | ||
| 117 | - refs[0], | ||
| 118 | - refs[0], | ||
| 119 | - "--runner=runner.sh", | ||
| 120 | - "--seed-mode=distributed", | ||
| 121 | - "--baseline-ngpus=2", | ||
| 122 | - "--test-ngpus=2", | ||
| 123 | - "--steps=2", | ||
| 124 | - "--baseline-options=--value=3", | ||
| 125 | - "--test-options=--value=3", | ||
| 126 | - "--output-dir", | ||
| 127 | - str(output), | ||
| 128 | - ], | ||
| 129 | - cwd=repo, | ||
| 130 | - text=True, | ||
| 131 | - capture_output=True, | ||
| 132 | - timeout=40, | ||
| 133 | - ) | ||
| 134 | - | ||
| 135 | - assert result.returncode == 0, result.stdout + result.stderr | ||
| 136 | - assert "seed-processes=2" in result.stdout | ||
| 137 | - assert "seed-value=3.0" in result.stdout | ||
| 138 | - assert "seed-imports=create_seed_checkpoint.py" in result.stdout | ||
| 139 | - report = json.loads((output / "comparison.json").read_text()) | ||
| 140 | - assert report["seed_mode"] == "distributed" | ||
| 141 | - assert report["passed"] | ||
| 142 | - assert "runner-value=3.0" in (output / "baseline" / "training.log").read_text() | ||
| 143 | - assert "runner-value=3.0" in (output / "test" / "training.log").read_text() | ||
| 144 | - | ||
| 145 | - | ||
| 146 | -def test_loss_compare_rejects_distributed_seed_with_custom_baseline_entrypoint(tmp_path): | ||
| 147 | - output = tmp_path / "comparison" | ||
| 148 | - | ||
| 149 | - result = subprocess.run( | ||
| 150 | - [ | ||
| 151 | - sys.executable, | ||
| 152 | - str(CLI), | ||
| 153 | - "HEAD", | ||
| 154 | - "HEAD", | ||
| 155 | - "--seed-mode=distributed", | ||
| 156 | - "--baseline-env=EXAMPLE=1,TRAIN_FILE=custom.train", | ||
| 157 | - "--baseline-env=EXAMPLE=2", | ||
| 158 | - "--output-dir", | ||
| 159 | - str(output), | ||
| 160 | - ], | ||
| 161 | - cwd=tmp_path, | ||
| 162 | - text=True, | ||
| 163 | - capture_output=True, | ||
| 164 | - timeout=10, | ||
| 165 | - ) | ||
| 166 | - | ||
| 167 | - assert result.returncode == 2, result.stdout + result.stderr | ||
| 168 | - assert "--seed-mode distributed cannot be combined with --baseline-env TRAIN_FILE" in result.stderr | ||
| 169 | - assert not output.exists() | ||
| 170 | - | ||
| 171 | - | ||
| 172 | -def test_loss_compare_bounds_training_when_runner_ignores_seed_entrypoint(tmp_path, runner_repo): | ||
| 173 | - repo, refs = runner_repo | ||
| 174 | - observed_steps = tmp_path / "observed_steps" | ||
| 175 | - training = ( | ||
| 176 | - "import argparse; from pathlib import Path; " | ||
| 177 | - "parser = argparse.ArgumentParser(); " | ||
| 178 | - "parser.add_argument('--training.steps', dest='steps', type=int); " | ||
| 179 | - "args, _ = parser.parse_known_args(); " | ||
| 180 | - f"Path({str(observed_steps)!r}).write_text(','.join(map(str, range(1, args.steps + 1))))" | ||
| 181 | - ) | ||
| 182 | - runner = repo / "ignore_entrypoint.sh" | ||
| 183 | - runner.write_text(f'#!/bin/bash\nexec {shlex.quote(sys.executable)} -c {shlex.quote(training)} "$@"\n') | ||
| 184 | - runner.chmod(0o755) | ||
| 185 | - output = tmp_path / "comparison" | ||
| 186 | - | ||
| 187 | - result = subprocess.run( | ||
| 188 | - [ | ||
| 189 | - sys.executable, | ||
| 190 | - str(CLI), | ||
| 191 | - refs[0], | ||
| 192 | - refs[0], | ||
| 193 | - f"--runner={runner}", | ||
| 194 | - "--seed-mode=distributed", | ||
| 195 | - "--steps=5", | ||
| 196 | - "--output-dir", | ||
| 197 | - str(output), | ||
| 198 | - ], | ||
| 199 | - cwd=repo, | ||
| 200 | - text=True, | ||
| 201 | - capture_output=True, | ||
| 202 | - timeout=40, | ||
| 203 | - ) | ||
| 204 | - | ||
| 205 | - assert result.returncode != 0 | ||
| 206 | - assert "check that the runner supports TRAIN_FILE=create_seed_checkpoint" in result.stderr | ||
| 207 | - assert observed_steps.read_text() == "1" | ||
| 208 | - assert not (output / "baseline").exists() | ||
| 209 | - assert not (output / "comparison.json").exists() | ||
| 210 | - | ||
| 211 | - | ||
| 212 | def _write_metric_runner(repo, name, value, *, ngpus=None): | 104 | def _write_metric_runner(repo, name, value, *, ngpus=None): |
| 213 | runner = repo / name | 105 | runner = repo / name |
| 214 | environment = f'export NGPU="${{NGPU:-{ngpus}}}"\n' if ngpus is not None else "" | 106 | environment = f'export NGPU="${{NGPU:-{ngpus}}}"\n' if ngpus is not None else "" |
| @@ -220,7 +112,6 @@ def _write_metric_runner(repo, name, value, *, ngpus=None): | |||
| 220 | return runner | 112 | return runner |
| 221 | 113 | ||
| 222 | 114 | ||
| 223 | -@pytest.mark.parametrize("seed_mode", ["unsharded", "distributed"]) | ||
| 224 | @pytest.mark.parametrize( | 115 | @pytest.mark.parametrize( |
| 225 | ("inherited_ngpu", "options", "baseline_ngpu", "test_ngpu", "baseline_config", "test_config"), | 116 | ("inherited_ngpu", "options", "baseline_ngpu", "test_ngpu", "baseline_config", "test_config"), |
| 226 | [ | 117 | [ |
| @@ -267,7 +158,6 @@ def test_loss_compare_preserves_runner_card_counts_unless_overridden( | |||
| 267 | tmp_path, | 158 | tmp_path, |
| 268 | runner_repo, | 159 | runner_repo, |
| 269 | monkeypatch, | 160 | monkeypatch, |
| 270 | - seed_mode, | ||
| 271 | inherited_ngpu, | 161 | inherited_ngpu, |
| 272 | options, | 162 | options, |
| 273 | baseline_ngpu, | 163 | baseline_ngpu, |
| @@ -290,7 +180,6 @@ def test_loss_compare_preserves_runner_card_counts_unless_overridden( | |||
| 290 | "--baseline-runner=base.sh", | 180 | "--baseline-runner=base.sh", |
| 291 | "--test-runner=test.sh", | 181 | "--test-runner=test.sh", |
| 292 | "--steps=2", | 182 | "--steps=2", |
| 293 | - f"--seed-mode={seed_mode}", | ||
| 294 | "--output-dir", | 183 | "--output-dir", |
| 295 | str(output), | 184 | str(output), |
| 296 | *options, | 185 | *options, |
| @@ -302,8 +191,7 @@ def test_loss_compare_preserves_runner_card_counts_unless_overridden( | |||
| 302 | ) | 191 | ) |
| 303 | 192 | ||
| 304 | assert result.returncode == 0, result.stdout + result.stderr | 193 | assert result.returncode == 0, result.stdout + result.stderr |
| 305 | - seed_ngpu = 1 if seed_mode == "unsharded" else baseline_ngpu | 194 | + assert "seed-ngpu=1\n" in result.stdout |
| 306 | - assert f"seed-ngpu={seed_ngpu}\n" in result.stdout | ||
| 307 | report = json.loads((output / "comparison.json").read_text()) | 195 | report = json.loads((output / "comparison.json").read_text()) |
| 308 | for side, ngpu, config in (("baseline", baseline_ngpu, baseline_config), ("test", test_ngpu, test_config)): | 196 | for side, ngpu, config in (("baseline", baseline_ngpu, baseline_config), ("test", test_ngpu, test_config)): |
| 309 | assert f"runner-ngpu={ngpu}\n" in (output / side / "training.log").read_text() | 197 | assert f"runner-ngpu={ngpu}\n" in (output / side / "training.log").read_text() |
| @@ -339,7 +227,7 @@ def test_loss_compare_runs_uncommitted_scripts_with_shared_seed(tmp_path, runner | |||
| 339 | ) | 227 | ) |
| 340 | 228 | ||
| 341 | assert result.returncode == (0 if test_value == 1 else 1), result.stdout + result.stderr | 229 | assert result.returncode == (0 if test_value == 1 else 1), result.stdout + result.stderr |
| 342 | - assert "seed-value=1.0" in result.stdout | 230 | + assert "seed-ngpu=1\n" in result.stdout |
| 343 | report = json.loads((output / "comparison.json").read_text()) | 231 | report = json.loads((output / "comparison.json").read_text()) |
| 344 | assert report["runner_scope"] == "working-tree" | 232 | assert report["runner_scope"] == "working-tree" |
| 345 | assert report["passed"] is (test_value == 1) | 233 | 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.checkpoint_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 |
| @@ -801,7 +802,7 @@ def _load_dcp_state_dict(model, input_dir: Path, master_dtype: str, read_threads | |||
| 801 | """Load the DCP checkpoint into the model's state-dict container.""" | 802 | """Load the DCP checkpoint into the model's state-dict container.""" |
| 802 | from torchtitan.config import TORCH_DTYPE_MAP | 803 | from torchtitan.config import TORCH_DTYPE_MAP |
| 803 | 804 | ||
| 804 | - from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import ParallelFileSystemReader, load_dcp_model | 805 | + from torchtitan_npu.tools.checkpoint_conversion.convert_to_hf import ParallelFileSystemReader |
| 805 | 806 | ||
| 806 | state_dict = model.state_dict() | 807 | state_dict = model.state_dict() |
| 807 | # The model is built in float32, but dcp.load copies the stored dtype into | 808 | # The model is built in float32, but dcp.load copies the stored dtype into |
| @@ -813,7 +814,7 @@ def _load_dcp_state_dict(model, input_dir: Path, master_dtype: str, read_threads | |||
| 813 | if value.is_floating_point() and value.dtype != container_dtype and ".engram.table.weight" not in fqn: | 814 | if value.is_floating_point() and value.dtype != container_dtype and ".engram.table.weight" not in fqn: |
| 814 | state_dict[fqn] = value.detach().to(container_dtype) | 815 | state_dict[fqn] = value.detach().to(container_dtype) |
| 815 | reader = ParallelFileSystemReader(str(input_dir), thread_count=read_threads) | 816 | reader = ParallelFileSystemReader(str(input_dir), thread_count=read_threads) |
| 816 | - load_dcp_model(state_dict, reader) | 817 | + dcp.load(state_dict, storage_reader=reader) |
| 817 | return state_dict | 818 | return state_dict |
| 818 | 819 | ||
| 819 | 820 | ||