| @@ -12,21 +12,21 @@ HF_ASSETS_PATH=/path/to/tokenizer \ | |||
| 12 | CKPT_INIT_LOAD_PATH=/path/to/v41-hf-base \ | 12 | CKPT_INIT_LOAD_PATH=/path/to/v41-hf-base \ |
| 13 | CKPT_SAVE_LOAD_PATH=/path/to/run/checkpoint \ | 13 | CKPT_SAVE_LOAD_PATH=/path/to/run/checkpoint \ |
| 14 | bash examples/deepseek_v4_1/deepseek_v4_1_flash_lora_4k_a3.sh \ | 14 | bash examples/deepseek_v4_1/deepseek_v4_1_flash_lora_4k_a3.sh \ |
| 15 | - --optimizer.name Muon \ | 15 | + --optim.optimizer.name Muon \ |
| 16 | - --training.steps 150 --checkpoint.interval 50 | 16 | + --training.steps 150 --checkpointer.interval 50 |
| 17 | ``` | 17 | ``` |
| 18 | 18 | ||
| 19 | -使用 `--optimizer.name AdamW` 选择 AdamW。默认 rank 为 16、alpha 为 32,专家 rank 为 16。通过 `CONFIG=deepseek_v4_1_flash_text_lora` 使用同一脚本训练正式纯文本模型:脚本将默认数据集切换为 `c4_test`,也可用 `DATASET`、`DATASET_PATH` 选择文本数据。多模态默认数据集为 `cc12m-test`。用户环境变量与末尾 CLI 参数可覆盖脚本默认值。 | 19 | +使用 `--optim.optimizer.name AdamW` 选择 AdamW。默认 rank 为 16、alpha 为 32,专家 rank 为 16。通过 `CONFIG=deepseek_v4_1_flash_text_lora` 使用同一脚本训练正式纯文本模型:脚本将默认数据集切换为 `c4_test`,也可用 `DATASET`、`DATASET_PATH` 选择文本数据。多模态默认数据集为 `cc12m-test`。用户环境变量与末尾 CLI 参数可覆盖脚本默认值。 |
| 20 | 20 | ||
| 21 | `deepseek_v4_1_debugmodel_lora` 为纯文本调试配置。设备数量应满足模型内存需求,仅缩小并行度不会缩小模型。 | 21 | `deepseek_v4_1_debugmodel_lora` 为纯文本调试配置。设备数量应满足模型内存需求,仅缩小并行度不会缩小模型。 |
| 22 | 22 | ||
| 23 | -从 native DCP 基座初始化时增加 `--checkpoint.no-initial-load-in-hf`。恢复 native checkpoint 时,保持 EP 度数、Engram 表结构、tokenizer 映射和 LoRA 配置一致。 | 23 | +从 native DCP 基座初始化时增加 `--checkpointer.no-initial-load-in-hf`。恢复 native checkpoint 时,保持 EP 度数、Engram 表结构、tokenizer 映射和 LoRA 配置一致。保持相同的 `CKPT_INIT_LOAD_PATH` 和 `CKPT_SAVE_LOAD_PATH`,使用 `--checkpointer.load-step 50` 指定恢复点。 |
| 24 | 24 | ||
| 25 | ## Checkpoint 与导出 | 25 | ## Checkpoint 与导出 |
| 26 | 26 | ||
| 27 | -初始化加载基座时保留新建的 adapter。周期 checkpoint 默认保存 adapter、持久化模型 buffer 和训练状态;恢复时先加载固定基座,再恢复这些状态,因此需要保留 `initial_load_path`。使用 `--checkpoint.no-periodic-save-adapter-only` 可将基座和 Engram 分片一并写入周期 DCP。恢复路径中的 checkpoint 必须包含 adapter。 | 27 | +初始化加载基座时保留新建的 adapter。周期 checkpoint 默认保存 adapter、持久化模型 buffer 和训练状态;恢复时先加载固定基座,再恢复这些状态,因此需要保留 `initial_load_path`。使用 `--checkpointer.no-periodic-save-adapter-only` 可将基座和 Engram 分片一并写入周期 DCP。恢复路径中的 checkpoint 必须包含 adapter。 |
| 28 | 28 | ||
| 29 | -最后一步保存 `adapter_model.safetensors` 和 `adapter_config.json`。Engram 权重保留在所引用的基座中,PEFT 仅导出训练的 adapter。使用 `--checkpoint.no-last-save-in-peft` 可改为保存 native checkpoint。`last_save_in_hf` 会被拒绝,因为普通全模型 HF 导出不保留 LoRA adapter。 | 29 | +最后一步保存 `adapter_model.safetensors` 和 `adapter_config.json`。Engram 权重保留在所引用的基座中,PEFT 仅导出训练的 adapter。使用 `--checkpointer.no-last-save-in-peft --checkpointer.no-last-save-model-only` 可在最后一步保存可续训的 native checkpoint。`last_save_in_hf` 会被拒绝,因为普通全模型 HF 导出不保留 LoRA adapter。 |
| 30 | 30 | ||
| 31 | 将 adapter 合并到浮点 V4.1 HF 基座: | 31 | 将 adapter 合并到浮点 V4.1 HF 基座: |
| 32 | 32 | ||
| @@ -12,21 +12,40 @@ HF_ASSETS_PATH=/path/to/tokenizer \ | |||
| 12 | CKPT_INIT_LOAD_PATH=/path/to/base-weights \ | 12 | CKPT_INIT_LOAD_PATH=/path/to/base-weights \ |
| 13 | CKPT_SAVE_LOAD_PATH=/path/to/run/checkpoint \ | 13 | CKPT_SAVE_LOAD_PATH=/path/to/run/checkpoint \ |
| 14 | bash examples/deepseek_v4/deepseek_v4_flash_lora_4k_a3.sh \ | 14 | bash examples/deepseek_v4/deepseek_v4_flash_lora_4k_a3.sh \ |
| 15 | - --optimizer.name AdamW \ | 15 | + --optim.optimizer.name AdamW \ |
| 16 | --training.steps 500 \ | 16 | --training.steps 500 \ |
| 17 | - --checkpoint.interval 100 | 17 | + --checkpointer.interval 100 |
| 18 | ``` | 18 | ``` |
| 19 | 19 | ||
| 20 | -A5 使用 `CONFIG=deepseek_v4_flash_lora bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh --checkpoint.no-load-only --checkpoint.save-training-state`,直接调用 A5 CPT 入口,默认启用 block-FP8。运行前按实际设备和数据设置节点、卡数、并行参数及输入路径,详见[训练示例](../../examples/deepseek_v4/readme.md)。命令末尾的普通 CLI 参数可覆盖默认值。 | 20 | +A5 使用 `CONFIG=deepseek_v4_flash_lora bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh --checkpointer.no-load-only --checkpointer.save-training-state`,直接调用 A5 CPT 入口,默认启用 block-FP8。运行前按实际设备和数据设置节点、卡数、并行参数及输入路径,详见[训练示例](../../examples/deepseek_v4/readme.md)。命令末尾的普通 CLI 参数可覆盖默认值。 |
| 21 | 21 | ||
| 22 | ### 模型与优化器配置 | 22 | ### 模型与优化器配置 |
| 23 | 23 | ||
| 24 | -自定义配置通过 `deepseek_v4_flash(converters=[DeepSeekV4LoRAConverter.Config(...)])` 启用 LoRA;秩、缩放参数和目标模块在转换器中设置,无需额外启用开关。配置自动选择 LoRA 并行化与检查点管理器。 | 24 | +自定义秩和缩放参数时,在 AdamW 训练配置中应用原生 LoRA transform,并选择 LoRA 检查点管理器: |
| 25 | + | ||
| 26 | +```python | ||
| 27 | +from torchtitan.config.transform import apply_transforms | ||
| 28 | + | ||
| 29 | +from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash | ||
| 30 | +from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform | ||
| 31 | +from torchtitan_npu.models.deepseek_v4.peft import DeepSeekV4PEFTCheckpointManager | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def custom_v4_lora(): | ||
| 35 | + config = apply_transforms( | ||
| 36 | + deepseek_v4_flash(num_mtp_layers=0), | ||
| 37 | + [deepseek_v4_lora_transform(rank=8, alpha=16)], | ||
| 38 | + ) | ||
| 39 | + config.checkpointer = DeepSeekV4PEFTCheckpointManager.Config(save_training_state=True) | ||
| 40 | + return config | ||
| 41 | +``` | ||
| 42 | + | ||
| 43 | +运行时将 `CKPT_INIT_LOAD_PATH` 指向固定基座,将 `CKPT_SAVE_LOAD_PATH` 指向检查点目录。 | ||
| 25 | 44 | ||
| 26 | | 配置项 | 用途 | | 45 | | 配置项 | 用途 | |
| 27 | | --- | --- | | 46 | | --- | --- | |
| 28 | -| `--optimizer.name AdamW` | 使用 AdamW 更新适配器 | | 47 | +| `--optim.optimizer.name AdamW` | 使用 AdamW 更新适配器 | |
| 29 | -| `--optimizer.name Muon` | 使用 Muon 与 AdamW 混合更新;专家 gate/up 适配器 B 分开由 Muon 更新,要求 TP=PP=1 | | 48 | +| `--optim.optimizer.name Muon` | 使用 Muon 与 AdamW 混合更新;专家 gate/up 适配器 B 分开由 Muon 更新,要求 TP=PP=1 | |
| 30 | | `--extension.quantization.no-enable-quantized-training` | 关闭量化训练,使用 BF16 基座 | | 49 | | `--extension.quantization.no-enable-quantized-training` | 关闭量化训练,使用 BF16 基座 | |
| 31 | | `--extension.quantization.recipe` | 选择已有量化方案;A5 入口默认 `all_block_fp8` | | 50 | | `--extension.quantization.recipe` | 选择已有量化方案;A5 入口默认 `all_block_fp8` | |
| 32 | 51 | ||
| @@ -36,21 +55,23 @@ A5 使用 `CONFIG=deepseek_v4_flash_lora bash examples/deepseek_v4/deepseek_v4_f | |||
| 36 | 55 | ||
| 37 | ## 检查点与断点续训 | 56 | ## 检查点与断点续训 |
| 38 | 57 | ||
| 39 | -周期检查点使用原生 DCP 格式。`checkpoint.periodic_save_adapter_only=True` 时,只保存适配器和路由缓冲区,不重复保存冻结的基座。启用 `checkpoint.save_training_state=True` 后,还会保存优化器、调度器、数据加载器和训练步数;上述 LoRA 启动脚本已启用此选项。 | 58 | +周期检查点使用原生 DCP 格式。`checkpointer.periodic_save_adapter_only=True` 时,只保存适配器和路由缓冲区,不重复保存冻结的基座。启用 `checkpointer.save_training_state=True` 后,还会保存优化器、调度器、数据加载器和训练步数;上述 LoRA 启动脚本已启用此选项。 |
| 40 | 59 | ||
| 41 | -断点续训时保持相同基座、训练总步数和检查点目录,并通过 `--checkpoint.load-step 100` 指定恢复点。 | 60 | +断点续训时保持相同基座、训练总步数和检查点目录,并通过 `--checkpointer.load-step 100` 指定恢复点。 |
| 61 | + | ||
| 62 | +自动恢复优先选择包含完整训练状态的 LoRA DCP,检查点清理会保留该恢复点。 | ||
| 42 | 63 | ||
| 43 | 最后一步默认导出 PEFT 适配器。若需要将最后一步也保存为可续训的 DCP 检查点,设置: | 64 | 最后一步默认导出 PEFT 适配器。若需要将最后一步也保存为可续训的 DCP 检查点,设置: |
| 44 | 65 | ||
| 45 | ```bash | 66 | ```bash |
| 46 | ---checkpoint.no-last-save-in-peft --checkpoint.no-last-save-model-only | 67 | +--checkpointer.no-last-save-in-peft --checkpointer.no-last-save-model-only |
| 47 | ``` | 68 | ``` |
| 48 | 69 | ||
| 49 | ## 导出与加载适配器 | 70 | ## 导出与加载适配器 |
| 50 | 71 | ||
| 51 | PEFT 导出生成 `adapter_model.safetensors` 和 `adapter_config.json`,只包含适配器权重及配置。导出目录须为本地文件系统路径。 | 72 | PEFT 导出生成 `adapter_model.safetensors` 和 `adapter_config.json`,只包含适配器权重及配置。导出目录须为本地文件系统路径。 |
| 52 | 73 | ||
| 53 | -使用 `--checkpoint.peft-base-model-name-or-path` 指定供外部加载器使用的 Hugging Face 基座 ID 或目录。未指定时,优先采用 HF 初始检查点路径,否则采用 HF 资源路径;原生 DCP 路径不会写入基座标识。 | 74 | +使用 `--checkpointer.peft-base-model-name-or-path` 指定供外部加载器使用的 Hugging Face 基座 ID 或目录。未指定时,优先采用 HF 初始检查点路径,否则采用 HF 资源路径;原生 DCP 路径不会写入基座标识。 |
| 54 | 75 | ||
| 55 | 加载时使用与训练相同、且 Transformers 能够加载的基座: | 76 | 加载时使用与训练相同、且 Transformers 能够加载的基座: |
| 56 | 77 | ||
| @@ -84,14 +105,19 @@ python -m scripts.lora.merge_adapter \ | |||
| 84 | | 项目 | 约束 | | 105 | | 项目 | 约束 | |
| 85 | | --- | --- | | 106 | | --- | --- | |
| 86 | | PEFT 专家导出 | 普通层与专家适配器的秩须相同 | | 107 | | PEFT 专家导出 | 普通层与专家适配器的秩须相同 | |
| 87 | -| MTP 适配器 | 使用原生检查点;需要 PEFT 导出时设置 `include_mtp=False` | | 108 | +| MTP 适配器 | 使用原生检查点;需要 PEFT 导出时用 `num_mtp_layers=0` 构建基座配置 | |
| 88 | | 完整模型 HF 导出 | `last_save_in_hf=True` 不合并 LoRA 增量,本检查点管理器不接受该选项;使用上述离线合并工具 | | 109 | | 完整模型 HF 导出 | `last_save_in_hf=True` 不合并 LoRA 增量,本检查点管理器不接受该选项;使用上述离线合并工具 | |
| 89 | | 离线合并 | 支持标准 LoRA 的 `alpha/r` 缩放,不支持 DoRA、RSLoRA 或逐目标秩与缩放参数 | | 110 | | 离线合并 | 支持标准 LoRA 的 `alpha/r` 缩放,不支持 DoRA、RSLoRA 或逐目标秩与缩放参数 | |
| 90 | 111 | ||
| 91 | 集成测试复用现有入口:`deepseek_v4` 中的 `dsv4_lora_ep2_fsdp2` 检查训练与导出,独立 `deepseek_v4_checkpoint` suite 中的 `dsv4_lora_resume_ep2_fsdp2` 在支持分布式 DCP 的运行环境中检查断点续训。运行方式见[集成测试说明](../../tests/integration_tests/README.md)。 | 112 | 集成测试复用现有入口:`deepseek_v4` 中的 `dsv4_lora_ep2_fsdp2` 检查训练与导出,独立 `deepseek_v4_checkpoint` suite 中的 `dsv4_lora_resume_ep2_fsdp2` 在支持分布式 DCP 的运行环境中检查断点续训。运行方式见[集成测试说明](../../tests/integration_tests/README.md)。 |
| 92 | 113 | ||
| 114 | +```bash | ||
| 115 | +python -m tests.integration_tests.run_tests /tmp/v4-lora-resume \ | ||
| 116 | + --test_suite deepseek_v4_checkpoint --test_name dsv4_lora_resume_ep2_fsdp2 --ngpu 2 --no-parallel | ||
| 117 | +``` | ||
| 118 | + | ||
| 93 | 合并工具先验证 rank、专家数和量化序列化格式,再按需读取 adapter A/B。结果写入临时目录,全部成功后才发布输出;写入失败会清理临时文件。 | 119 | 合并工具先验证 rank、专家数和量化序列化格式,再按需读取 adapter A/B。结果写入临时目录,全部成功后才发布输出;写入失败会清理临时文件。 |
| 94 | 120 | ||
| 95 | 支持 block-FP8 的 Ascend 950 设备(CANN 9.2.0 release,2026-09-09 软件包)使用 `deepseek_v4_quantized` suite 运行 `dsv4_lora_block_fp8_ep2_fsdp2`,使用真实 TorchAO-NPU block-FP8 recipe 验证量化基座、浮点 adapter 及训练更新。 | 121 | 支持 block-FP8 的 Ascend 950 设备(CANN 9.2.0 release,2026-09-09 软件包)使用 `deepseek_v4_quantized` suite 运行 `dsv4_lora_block_fp8_ep2_fsdp2`,使用真实 TorchAO-NPU block-FP8 recipe 验证量化基座、浮点 adapter 及训练更新。 |
| 96 | 122 | ||
| 97 | -专家 gate/up B 参数分别保存为 `w1_lora_b` 和 `w3_lora_b`,共享 `w13_lora_a`,PEFT 导出格式保持不变。普通 `model.load_state_dict` 可拆分旧的 `w13_lora_b` 权重;旧版交错参数的原生 DCP 不能直接续训,因为参数分组及优化器状态已改变。请使用生成该 checkpoint 的版本导出并合并适配器,再从合并后的基座开始新训练。 | 123 | +融合专家 gate/up 适配器使用 `w13.lora_a.weight` 和 `w13.lora_b.weight` 保存。旧版使用 `w13_lora_b` 的原生 DCP 不能直接续训。请使用生成该 checkpoint 的版本导出并合并适配器,再从合并后的基座开始新训练。 |
| @@ -29,6 +29,8 @@ GOLDEN_OVERRIDES = ( | |||
| 29 | "torchtitan_npu.override.common.rope.workaround", | 29 | "torchtitan_npu.override.common.rope.workaround", |
| 30 | ) | 30 | ) |
| 31 | 31 | ||
| 32 | +_LORA_ROPE_OVERRIDES = ("--override.imports", "tests.integration_tests.lora_config.lora_rope_workaround") | ||
| 33 | + | ||
| 32 | # The V4 Grain recipe already points at tests/assets/c4_test/data.json. | 34 | # The V4 Grain recipe already points at tests/assets/c4_test/data.json. |
| 33 | V4_TRAIN_ARGS = ( | 35 | V4_TRAIN_ARGS = ( |
| 34 | "--metrics.enable_tensorboard", | 36 | "--metrics.enable_tensorboard", |
| @@ -103,13 +105,18 @@ def build_deepseek_v4_checkpoint_resume_test_list() -> list[OverrideDefinitions] | |||
| 103 | check_loss=False, | 105 | check_loss=False, |
| 104 | check_resume=True, | 106 | check_resume=True, |
| 105 | ) | 107 | ) |
| 106 | - lora_args = GOLDEN_OVERRIDES + checkpoint_args + ("--checkpoint.save-training-state", "--optimizer.name=Muon") | 108 | + lora_args = ( |
| 109 | + *_LORA_ROPE_OVERRIDES, | ||
| 110 | + *(arg.replace("--checkpoint.", "--checkpointer.") for arg in checkpoint_args if arg != "--checkpoint.enable"), | ||
| 111 | + "--checkpointer.save-training-state", | ||
| 112 | + "--optim.optimizer.name=Muon", | ||
| 113 | + ) | ||
| 107 | lora_checkpoint_case = replace( | 114 | lora_checkpoint_case = replace( |
| 108 | checkpoint_case, | 115 | checkpoint_case, |
| 109 | test_name="dsv4_lora_resume_ep2_fsdp2", | 116 | test_name="dsv4_lora_resume_ep2_fsdp2", |
| 110 | test_descr="DeepSeek-V4 LoRA checkpoint resume EP2/FSDP2", | 117 | test_descr="DeepSeek-V4 LoRA checkpoint resume EP2/FSDP2", |
| 111 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_training"}, | 118 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_training"}, |
| 112 | - override_args=[lora_args, (*lora_args, "--checkpoint.load-step=2")], | 119 | + override_args=[lora_args, (*lora_args, "--checkpointer.load-step=2")], |
| 113 | ) | 120 | ) |
| 114 | return [checkpoint_case, lora_checkpoint_case] | 121 | return [checkpoint_case, lora_checkpoint_case] |
| 115 | 122 | ||
| @@ -151,10 +158,10 @@ def build_deepseek_v4_quantized_test_list() -> list[OverrideDefinitions]: | |||
| 151 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_quantized_training"}, | 158 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_quantized_training"}, |
| 152 | override_args=[ | 159 | override_args=[ |
| 153 | ( | 160 | ( |
| 154 | - *GOLDEN_OVERRIDES, | 161 | + *_LORA_ROPE_OVERRIDES, |
| 155 | "--training.steps=2", | 162 | "--training.steps=2", |
| 156 | "--training.num-tokens-per-train-step=4096", | 163 | "--training.num-tokens-per-train-step=4096", |
| 157 | - "--optimizer.name=AdamW", | 164 | + "--optim.optimizer.name=AdamW", |
| 158 | "--parallelism.data-parallel-shard-degree=2", | 165 | "--parallelism.data-parallel-shard-degree=2", |
| 159 | "--parallelism.expert-parallel-degree=2", | 166 | "--parallelism.expert-parallel-degree=2", |
| 160 | "--hf-assets-path=tests/assets/deepseek_v3", | 167 | "--hf-assets-path=tests/assets/deepseek_v3", |
| @@ -248,15 +255,14 @@ def build_deepseek_v4_test_list() -> list[OverrideDefinitions]: | |||
| 248 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_training"}, | 255 | env_vars={"MODULE": "tests.integration_tests.lora_config", "CONFIG": "deepseek_v4_lora_training"}, |
| 249 | override_args=[ | 256 | override_args=[ |
| 250 | ( | 257 | ( |
| 251 | - *GOLDEN_OVERRIDES, | 258 | + *_LORA_ROPE_OVERRIDES, |
| 252 | "--training.steps=2", | 259 | "--training.steps=2", |
| 253 | "--training.num-tokens-per-train-step=4096", | 260 | "--training.num-tokens-per-train-step=4096", |
| 254 | - "--optimizer.name=Muon", | 261 | + "--optim.optimizer.name=Muon", |
| 255 | "--parallelism.data-parallel-shard-degree=2", | 262 | "--parallelism.data-parallel-shard-degree=2", |
| 256 | "--parallelism.expert-parallel-degree=2", | 263 | "--parallelism.expert-parallel-degree=2", |
| 257 | "--hf-assets-path=tests/assets/deepseek_v3", | 264 | "--hf-assets-path=tests/assets/deepseek_v3", |
| 258 | - "--checkpoint.enable", | 265 | + "--checkpointer.interval=10000", |
| 259 | - "--checkpoint.interval=10000", | ||
| 260 | ) | 266 | ) |
| 261 | ], | 267 | ], |
| 262 | ngpu=2, | 268 | ngpu=2, |
| @@ -25,14 +25,14 @@ from tests.integration_tests import OverrideDefinitions | |||
| 25 | 25 | ||
| 26 | def build_deepseek_v4_1_test_list() -> list[OverrideDefinitions]: | 26 | def build_deepseek_v4_1_test_list() -> list[OverrideDefinitions]: |
| 27 | args = ( | 27 | args = ( |
| 28 | - "--override.imports", "torchtitan_npu.override.common.rope.workaround", | 28 | + "--override.imports", "tests.integration_tests.lora_config.lora_rope_workaround", |
| 29 | "--hf-assets-path=tests/assets/deepseek_v3", "--training.steps=2", | 29 | "--hf-assets-path=tests/assets/deepseek_v3", "--training.steps=2", |
| 30 | "--training.num-tokens-per-microbatch-per-dp-rank=128", | 30 | "--training.num-tokens-per-microbatch-per-dp-rank=128", |
| 31 | "--training.num-tokens-per-train-step=256", "--training.max-context-length=128", | 31 | "--training.num-tokens-per-train-step=256", "--training.max-context-length=128", |
| 32 | "--parallelism.data-parallel-shard-degree=2", "--parallelism.expert-parallel-degree=2", | 32 | "--parallelism.data-parallel-shard-degree=2", "--parallelism.expert-parallel-degree=2", |
| 33 | - "--checkpoint.enable", "--checkpoint.no-last-save-model-only", | 33 | + "--checkpointer.no-last-save-model-only", |
| 34 | - "--checkpoint.keep-latest-k=0", "--debug.seed=42", "--debug.deterministic", | 34 | + "--checkpointer.keep-latest-k=0", "--debug.seed=42", "--debug.deterministic", |
| 35 | - "--optimizer.name=AdamW", | 35 | + "--optim.optimizer.name=AdamW", |
| 36 | ) | 36 | ) |
| 37 | text = OverrideDefinitions( | 37 | text = OverrideDefinitions( |
| 38 | test_name="dsv41_lora_engram_ep2_fsdp2", | 38 | test_name="dsv41_lora_engram_ep2_fsdp2", |
| @@ -118,14 +118,14 @@ def build_deepseek_v4_1_checkpoint_test_list( | |||
| 118 | *, optimizers: tuple[str, ...] = ("AdamW", "Muon"), include_adapter_only: bool = True, | 118 | *, optimizers: tuple[str, ...] = ("AdamW", "Muon"), include_adapter_only: bool = True, |
| 119 | ) -> list[OverrideDefinitions]: | 119 | ) -> list[OverrideDefinitions]: |
| 120 | case = build_deepseek_v4_1_test_list()[0] | 120 | case = build_deepseek_v4_1_test_list()[0] |
| 121 | - common = tuple(arg for arg in case.override_args[0] if not arg.startswith(("--training.steps=", "--optimizer.name="))) | 121 | + common = tuple(arg for arg in case.override_args[0] if not arg.startswith(("--training.steps=", "--optim.optimizer.name="))) |
| 122 | result = [] | 122 | result = [] |
| 123 | for optimizer in optimizers: | 123 | for optimizer in optimizers: |
| 124 | - args = (*common, "--training.steps=4", "--checkpoint.interval=2", f"--optimizer.name={optimizer}") | 124 | + args = (*common, "--training.steps=4", "--checkpointer.interval=2", f"--optim.optimizer.name={optimizer}") |
| 125 | result.append(replace( | 125 | result.append(replace( |
| 126 | case, test_name=f"dsv41_lora_{optimizer.lower()}_resume_ep2_fsdp2", | 126 | case, test_name=f"dsv41_lora_{optimizer.lower()}_resume_ep2_fsdp2", |
| 127 | test_descr=f"V4.1 LoRA {optimizer} exact native checkpoint resume", | 127 | test_descr=f"V4.1 LoRA {optimizer} exact native checkpoint resume", |
| 128 | - override_args=[args, (*args, "--checkpoint.load-step=2")], | 128 | + override_args=[args, (*args, "--checkpointer.load-step=2")], |
| 129 | expected_steps=((1, 2, 3, 4), (3, 4)), check_resume=True, | 129 | expected_steps=((1, 2, 3, 4), (3, 4)), check_resume=True, |
| 130 | env_vars={ | 130 | env_vars={ |
| 131 | "MODULE": "tests.integration_tests.v41_lora_config", | 131 | "MODULE": "tests.integration_tests.v41_lora_config", |
| @@ -134,11 +134,11 @@ def build_deepseek_v4_1_checkpoint_test_list( | |||
| 134 | }, | 134 | }, |
| 135 | )) | 135 | )) |
| 136 | if include_adapter_only and "Muon" in optimizers: | 136 | if include_adapter_only and "Muon" in optimizers: |
| 137 | - args = (*common, "--training.steps=10", "--checkpoint.interval=5", "--optimizer.name=Muon") | 137 | + args = (*common, "--training.steps=10", "--checkpointer.interval=5", "--optim.optimizer.name=Muon") |
| 138 | result.append(replace( | 138 | result.append(replace( |
| 139 | case, test_name="dsv41_lora_muon_adapter_only_resume_ep2_fsdp2", | 139 | case, test_name="dsv41_lora_muon_adapter_only_resume_ep2_fsdp2", |
| 140 | test_descr="V4.1 LoRA Muon adapter-only resume with five exact post-resume steps", | 140 | test_descr="V4.1 LoRA Muon adapter-only resume with five exact post-resume steps", |
| 141 | - override_args=[args, (*args, "--checkpoint.load-step=5")], | 141 | + override_args=[args, (*args, "--checkpointer.load-step=5")], |
| 142 | expected_steps=(tuple(range(1, 11)), tuple(range(6, 11))), check_resume=True, | 142 | expected_steps=(tuple(range(1, 11)), tuple(range(6, 11))), check_resume=True, |
| 143 | env_vars={ | 143 | env_vars={ |
| 144 | "MODULE": "tests.integration_tests.v41_lora_config", | 144 | "MODULE": "tests.integration_tests.v41_lora_config", |
| @@ -6,19 +6,33 @@ | |||
| 6 | """LoRA training, selective freezing and PEFT export on real NPUs.""" | 6 | """LoRA training, selective freezing and PEFT export on real NPUs.""" |
| 7 | 7 | ||
| 8 | import json | 8 | import json |
| 9 | -from dataclasses import dataclass, fields | 9 | +import logging |
| 10 | +from dataclasses import dataclass, fields, replace | ||
| 10 | from pathlib import Path | 11 | from pathlib import Path |
| 11 | 12 | ||
| 12 | import torch | 13 | import torch |
| 13 | import torch.distributed as dist | 14 | import torch.distributed as dist |
| 14 | from safetensors.torch import load_file | 15 | from safetensors.torch import load_file |
| 15 | from torch.distributed.tensor import DTensor | 16 | from torch.distributed.tensor import DTensor |
| 16 | -from torchtitan.tools.logging import logger | 17 | +from torchtitan.components.optim import DistMuon |
| 18 | +from torchtitan.config import override | ||
| 19 | +from torchtitan.config.transform import apply_transforms | ||
| 17 | 20 | ||
| 18 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx | 21 | from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx |
| 19 | -from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel | 22 | +from torchtitan_npu.models.deepseek_v4.config_registry import _dsv4_muon_profile, deepseek_v4_debugmodel |
| 20 | -from torchtitan_npu.models.deepseek_v4.lora import DeepSeekV4LoRAConverter, is_lora_parameter | 23 | +from torchtitan_npu.models.deepseek_v4.lora import deepseek_v4_lora_transform, is_lora_parameter |
| 21 | -from torchtitan.distributed.flex_shard.dist_muon import DistMuon | 24 | +from torchtitan_npu.models.deepseek_v4.peft import DeepSeekV4PEFTCheckpointManager |
| 25 | +from torchtitan_npu.override.common.rope import WorkaroundComplexRoPE, workaround | ||
| 26 | +from torchtitan_npu.patches.torchtitan.models.common.rope import SplitComplexRoPEConfig | ||
| 27 | + | ||
| 28 | +logger = logging.getLogger(__name__) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +@override(target=SplitComplexRoPEConfig) | ||
| 32 | +def lora_rope_workaround(cfg: SplitComplexRoPEConfig) -> WorkaroundComplexRoPE.Config: | ||
| 33 | + # LoRA wraps the config in a frozen subclass, so the exact-type override skips it. | ||
| 34 | + # This RoPE module has buffers only. | ||
| 35 | + return workaround(cfg) | ||
| 22 | 36 | ||
| 23 | 37 | ||
| 24 | def _cpu_tensor(tensor): | 38 | def _cpu_tensor(tensor): |
| @@ -34,16 +48,24 @@ class LoRATrainer(TrainerEx): | |||
| 34 | class Config(TrainerEx.Config): | 48 | class Config(TrainerEx.Config): |
| 35 | pass | 49 | pass |
| 36 | 50 | ||
| 51 | + def __init__(self, config): | ||
| 52 | + if config.checkpointer.load_step > 0: | ||
| 53 | + # Compare with the uninterrupted artifacts without overwriting them. | ||
| 54 | + config.checkpointer.load_only = True | ||
| 55 | + super().__init__(config) | ||
| 56 | + | ||
| 37 | def train_step(self, data_iterator): | 57 | def train_step(self, data_iterator): |
| 38 | - checkpoint = self.config.checkpoint | 58 | + engine = self.engine |
| 39 | - if checkpoint.save_training_state and (checkpoint.load_step or 0) > 0 and self.step == checkpoint.load_step + 1: | 59 | + checkpoint = self.config.checkpointer |
| 60 | + step = engine.num_completed_steps + 1 | ||
| 61 | + if checkpoint.save_training_state and checkpoint.load_step > 0 and step == checkpoint.load_step + 1: | ||
| 40 | expected = torch.load( | 62 | expected = torch.load( |
| 41 | self._optimizer_snapshot_path(checkpoint.load_step), | 63 | self._optimizer_snapshot_path(checkpoint.load_step), |
| 42 | map_location="cpu", | 64 | map_location="cpu", |
| 43 | weights_only=True, | 65 | weights_only=True, |
| 44 | ) | 66 | ) |
| 45 | torch.testing.assert_close(self._optimizer_snapshot(), expected, rtol=0, atol=0) | 67 | torch.testing.assert_close(self._optimizer_snapshot(), expected, rtol=0, atol=0) |
| 46 | - model = self.model_parts[0] | 68 | + model = engine.model_parts[0] |
| 47 | self._check_quantized_parameters(model) | 69 | self._check_quantized_parameters(model) |
| 48 | frozen = {name: _cpu_tensor(p) for name, p in model.named_parameters() if not p.requires_grad} | 70 | frozen = {name: _cpu_tensor(p) for name, p in model.named_parameters() if not p.requires_grad} |
| 49 | biases = {name: _cpu_tensor(b) for name, b in model.named_buffers() if name.endswith("expert_bias_E")} | 71 | biases = {name: _cpu_tensor(b) for name, b in model.named_buffers() if name.endswith("expert_bias_E")} |
| @@ -51,15 +73,17 @@ class LoRATrainer(TrainerEx): | |||
| 51 | before = _cpu_tensor(adapter) | 73 | before = _cpu_tensor(adapter) |
| 52 | adapter_a = model.layers["0"].attention.wq_a.lora_a.weight | 74 | adapter_a = model.layers["0"].attention.wq_a.lora_a.weight |
| 53 | before_a = _cpu_tensor(adapter_a) | 75 | before_a = _cpu_tensor(adapter_a) |
| 54 | - experts = model.layers["0"].moe.routed_experts.inner_experts | 76 | + expert_b = model.layers["0"].moe.routed_experts.w13.lora_b.weight |
| 55 | - expert_b = (experts.w1_lora_b, experts.w3_lora_b) | 77 | + before_expert_b = _cpu_tensor(expert_b.full_tensor() if isinstance(expert_b, DTensor) else expert_b) |
| 56 | - before_expert_b = [_cpu_tensor(p.full_tensor() if isinstance(p, DTensor) else p) for p in expert_b] | 78 | + if self.config.optim.optimizer.name == "Muon": |
| 57 | - if self.config.optimizer.name == "Muon": | ||
| 58 | muon_parameters = { | 79 | muon_parameters = { |
| 59 | - id(p) for optimizer in self.optimizers.optimizers if isinstance(optimizer, DistMuon) | 80 | + id(p) |
| 60 | - for group in optimizer.param_groups for p in group["params"] | 81 | + for optimizer in engine.optim.optimizers.optimizers |
| 82 | + if isinstance(optimizer, DistMuon) | ||
| 83 | + for group in optimizer.param_groups | ||
| 84 | + for p in group["params"] | ||
| 61 | } | 85 | } |
| 62 | - assert all(id(p) in muon_parameters for p in expert_b) | 86 | + assert id(expert_b) in muon_parameters |
| 63 | assert biases | 87 | assert biases |
| 64 | super().train_step(data_iterator) | 88 | super().train_step(data_iterator) |
| 65 | for name, expected in frozen.items(): | 89 | for name, expected in frozen.items(): |
| @@ -69,36 +93,39 @@ class LoRATrainer(TrainerEx): | |||
| 69 | for name, expected in biases.items(): | 93 | for name, expected in biases.items(): |
| 70 | torch.testing.assert_close(_cpu_tensor(model.get_buffer(name)), expected, rtol=0, atol=0) | 94 | torch.testing.assert_close(_cpu_tensor(model.get_buffer(name)), expected, rtol=0, atol=0) |
| 71 | assert not torch.equal(_cpu_tensor(adapter), before) | 95 | assert not torch.equal(_cpu_tensor(adapter), before) |
| 72 | - for parameter, previous in zip(expert_b, before_expert_b, strict=True): | 96 | + current = _cpu_tensor(expert_b.full_tensor() if isinstance(expert_b, DTensor) else expert_b) |
| 73 | - current = parameter.full_tensor() if isinstance(parameter, DTensor) else parameter | 97 | + assert current.shape[1] == 2 |
| 74 | - assert not torch.equal(_cpu_tensor(current), previous) | 98 | + for gate_up in range(2): |
| 99 | + assert not torch.equal(current[:, gate_up], before_expert_b[:, gate_up]) | ||
| 75 | if adapter_a.requires_grad and torch.count_nonzero(before): | 100 | if adapter_a.requires_grad and torch.count_nonzero(before): |
| 76 | assert not torch.equal(_cpu_tensor(adapter_a), before_a) | 101 | assert not torch.equal(_cpu_tensor(adapter_a), before_a) |
| 77 | 102 | ||
| 78 | - if checkpoint.save_training_state and checkpoint.interval > 0 and self.step % checkpoint.interval == 0: | 103 | + if checkpoint.save_training_state and not checkpoint.load_only and step % checkpoint.interval == 0: |
| 79 | state = self._optimizer_snapshot() | 104 | state = self._optimizer_snapshot() |
| 80 | - state_fields = ("momentum_buffer", "exp_avg") if self.config.optimizer.name == "Muon" else ("exp_avg",) | 105 | + state_fields = ("momentum_buffer", "exp_avg") if self.config.optim.optimizer.name == "Muon" else ("exp_avg",) |
| 81 | for field in state_fields: | 106 | for field in state_fields: |
| 82 | values = [value for name, value in state.items() if field in name] | 107 | values = [value for name, value in state.items() if field in name] |
| 83 | assert values and any(torch.count_nonzero(value) for value in values), field | 108 | assert values and any(torch.count_nonzero(value) for value in values), field |
| 84 | - torch.save(state, self._optimizer_snapshot_path(self.step)) | 109 | + torch.save(state, self._optimizer_snapshot_path(step)) |
| 85 | 110 | ||
| 86 | def train(self): | 111 | def train(self): |
| 87 | super().train() | 112 | super().train() |
| 113 | + engine = self.engine | ||
| 114 | + checkpointer = engine.checkpointer | ||
| 88 | state = { | 115 | state = { |
| 89 | name: (value.full_tensor() if isinstance(value, DTensor) else value).detach().cpu() | 116 | name: (value.full_tensor() if isinstance(value, DTensor) else value).detach().cpu() |
| 90 | - for name, value in self.model_parts[0].state_dict().items() | 117 | + for name, value in engine.model_parts[0].state_dict().items() |
| 91 | if is_lora_parameter(name) | 118 | if is_lora_parameter(name) |
| 92 | } | 119 | } |
| 93 | - expected = self.checkpointer.sd_adapter.to_peft(state) | 120 | + expected = checkpointer.sd_adapter.to_peft(state) |
| 94 | - checkpoint = Path(self.checkpointer._create_checkpoint_id(self.step)) | 121 | + checkpoint = Path(checkpointer._create_checkpoint_id(engine.num_completed_steps)) |
| 95 | exported = load_file(checkpoint / "adapter_model.safetensors") | 122 | exported = load_file(checkpoint / "adapter_model.safetensors") |
| 96 | assert exported.keys() == expected.keys() | 123 | assert exported.keys() == expected.keys() |
| 97 | for name, value in expected.items(): | 124 | for name, value in expected.items(): |
| 98 | - torch.testing.assert_close(exported[name], value.to(self.checkpointer.export_dtype), rtol=0, atol=0) | 125 | + torch.testing.assert_close(exported[name], value.to(checkpointer.export_dtype), rtol=0, atol=0) |
| 99 | with (checkpoint / "adapter_config.json").open(encoding="utf-8") as source: | 126 | with (checkpoint / "adapter_config.json").open(encoding="utf-8") as source: |
| 100 | metadata = json.load(source) | 127 | metadata = json.load(source) |
| 101 | - options = self.config.model_spec.model.lora | 128 | + options = self.config.model.layers[0].attention.wq_a |
| 102 | assert metadata["r"] == options.rank | 129 | assert metadata["r"] == options.rank |
| 103 | assert metadata["lora_alpha"] == options.alpha | 130 | assert metadata["lora_alpha"] == options.alpha |
| 104 | target_parameters = set(metadata["target_parameters"]) | 131 | target_parameters = set(metadata["target_parameters"]) |
| @@ -124,7 +151,7 @@ class LoRATrainer(TrainerEx): | |||
| 124 | def _optimizer_snapshot(self): | 151 | def _optimizer_snapshot(self): |
| 125 | return { | 152 | return { |
| 126 | name: _cpu_tensor(value) | 153 | name: _cpu_tensor(value) |
| 127 | - for name, value in self.optimizers.state_dict().items() | 154 | + for name, value in self.engine.optim.optimizers.state_dict().items() |
| 128 | if isinstance(value, torch.Tensor) | 155 | if isinstance(value, torch.Tensor) |
| 129 | } | 156 | } |
| 130 | 157 | ||
| @@ -153,10 +180,9 @@ class LoRATrainer(TrainerEx): | |||
| 153 | 180 | ||
| 154 | 181 | ||
| 155 | def deepseek_v4_lora_training(): | 182 | def deepseek_v4_lora_training(): |
| 156 | - config = deepseek_v4_debugmodel(converters=[DeepSeekV4LoRAConverter.Config()]) | 183 | + config = apply_transforms(deepseek_v4_debugmodel(), [deepseek_v4_lora_transform()]) |
| 157 | - config.checkpoint.enable = True | 184 | + config.optim.optimizer = replace(config.optim.optimizer, _muon_profile=_dsv4_muon_profile(config.model)) |
| 158 | - config.checkpoint.interval = 10000 | 185 | + config.checkpointer = DeepSeekV4PEFTCheckpointManager.Config(interval=10000, periodic_save_adapter_only=False) |
| 159 | - config.checkpoint.periodic_save_adapter_only = False | ||
| 160 | return LoRATrainer.Config( | 186 | return LoRATrainer.Config( |
| 161 | **{field.name: getattr(config, field.name) for field in fields(config) if field.init}, | 187 | **{field.name: getattr(config, field.name) for field in fields(config) if field.init}, |
| 162 | ) | 188 | ) |
| @@ -662,7 +662,9 @@ def _migration_pending_reason(case: OverrideDefinitions) -> str | None: | |||
| 662 | return "Muon LoRA/context-parallel integration migration is pending" | 662 | return "Muon LoRA/context-parallel integration migration is pending" |
| 663 | if case.verify_ema_checkpoint: | 663 | if case.verify_ema_checkpoint: |
| 664 | return "EMA migration is pending" | 664 | return "EMA migration is pending" |
| 665 | - if case.check_resume and "lora" in case.test_name: | 665 | + if case.check_resume and "lora" in case.test_name and not any( |
| 666 | + arg.startswith("--checkpointer.load-step=") for arg in arguments | ||
| 667 | + ): | ||
| 666 | return "LoRA checkpoint migration is pending" | 668 | return "LoRA checkpoint migration is pending" |
| 667 | return None | 669 | return None |
| 668 | 670 | ||
| @@ -3,6 +3,7 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | +import logging | ||
| 6 | from dataclasses import dataclass | 7 | from dataclasses import dataclass |
| 7 | from pathlib import Path | 8 | from pathlib import Path |
| 8 | 9 | ||
| @@ -11,7 +12,6 @@ import torch.distributed as dist | |||
| 11 | import torch.distributed.checkpoint as dcp | 12 | import torch.distributed.checkpoint as dcp |
| 12 | from torchtitan.components.checkpointer.utils import canonical_fqn | 13 | from torchtitan.components.checkpointer.utils import canonical_fqn |
| 13 | from torchtitan.config import derive | 14 | from torchtitan.config import derive |
| 14 | -from torchtitan.tools.logging import logger | ||
| 15 | 15 | ||
| 16 | from tests.integration_tests.lora_config import LoRATrainer, _cpu_tensor | 16 | from tests.integration_tests.lora_config import LoRATrainer, _cpu_tensor |
| 17 | from torchtitan_npu.models.deepseek_v4.lora import is_lora_parameter | 17 | from torchtitan_npu.models.deepseek_v4.lora import is_lora_parameter |
| @@ -23,6 +23,8 @@ from torchtitan_npu.models.deepseek_v4_1.config_registry import ( | |||
| 23 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable | 23 | from torchtitan_npu.models.deepseek_v4_1.engram.host import HostEngramTable |
| 24 | from torchtitan_npu.models.deepseek_v4_1.vision.data import build_image_token_layout | 24 | from torchtitan_npu.models.deepseek_v4_1.vision.data import build_image_token_layout |
| 25 | 25 | ||
| 26 | +logger = logging.getLogger(__name__) | ||
| 27 | + | ||
| 26 | 28 | ||
| 27 | class V41LoRATrainer(LoRATrainer, DeepSeekV41Trainer): | 29 | class V41LoRATrainer(LoRATrainer, DeepSeekV41Trainer): |
| 28 | @dataclass(kw_only=True, slots=True) | 30 | @dataclass(kw_only=True, slots=True) |
| @@ -30,24 +32,25 @@ class V41LoRATrainer(LoRATrainer, DeepSeekV41Trainer): | |||
| 30 | check_resume_state: bool = False | 32 | check_resume_state: bool = False |
| 31 | 33 | ||
| 32 | def __init__(self, config): | 34 | def __init__(self, config): |
| 33 | - if config.checkpoint.periodic_save_adapter_only: | 35 | + if config.checkpointer.periodic_save_adapter_only: |
| 34 | - config.checkpoint.initial_load_path = str(Path(config.dump_folder) / "fixed_base") | 36 | + config.checkpointer.initial_load_path = str(Path(config.dump_folder) / "fixed_base") |
| 35 | super().__init__(config) | 37 | super().__init__(config) |
| 36 | - if config.checkpoint.periodic_save_adapter_only: | 38 | + if config.checkpointer.periodic_save_adapter_only: |
| 37 | - base = Path(self.checkpointer.initial_load_path) | 39 | + base = Path(self.engine.checkpointer.initial_load_path) |
| 38 | if not (base / ".metadata").exists(): | 40 | if not (base / ".metadata").exists(): |
| 39 | # All ranks save the initialized, sharded base once; resumed runs reuse it. | 41 | # All ranks save the initialized, sharded base once; resumed runs reuse it. |
| 40 | dcp.save( | 42 | dcp.save( |
| 41 | - {name: value for name, value in self.model_parts[0].state_dict().items() if not is_lora_parameter(name)}, | 43 | + {name: value for name, value in self.engine.model_parts[0].state_dict().items() |
| 44 | + if not is_lora_parameter(name)}, | ||
| 42 | checkpoint_id=base, | 45 | checkpoint_id=base, |
| 43 | ) | 46 | ) |
| 44 | 47 | ||
| 45 | def train(self): | 48 | def train(self): |
| 46 | super().train() | 49 | super().train() |
| 47 | - if self.checkpointer.periodic_save_adapter_only: | 50 | + if self.engine.checkpointer.periodic_save_adapter_only: |
| 48 | - path = Path(self.checkpointer.folder) / f"step-{self.config.checkpoint.interval}" | 51 | + path = Path(self.engine.checkpointer.folder) / f"step-{self.config.checkpointer.interval}" |
| 49 | keys = dcp.FileSystemReader(path).read_metadata().state_dict_metadata | 52 | keys = dcp.FileSystemReader(path).read_metadata().state_dict_metadata |
| 50 | - model = self.model_parts[0] | 53 | + model = self.engine.model_parts[0] |
| 51 | assert any(is_lora_parameter(name) for name in keys) | 54 | assert any(is_lora_parameter(name) for name in keys) |
| 52 | assert any(name.startswith("optimizer.") for name in keys) | 55 | assert any(name.startswith("optimizer.") for name in keys) |
| 53 | buffers = {canonical_fqn(name) for name, _ in model.named_buffers()} | 56 | buffers = {canonical_fqn(name) for name, _ in model.named_buffers()} |
| @@ -56,10 +59,11 @@ class V41LoRATrainer(LoRATrainer, DeepSeekV41Trainer): | |||
| 56 | assert not frozen.intersection(keys) | 59 | assert not frozen.intersection(keys) |
| 57 | 60 | ||
| 58 | def _check_resume_state(self, step): | 61 | def _check_resume_state(self, step): |
| 59 | - optimizer = self.optimizers.state_dict() | 62 | + optimizer = self.engine.optim.optimizers.state_dict() |
| 60 | tensors = { | 63 | tensors = { |
| 61 | "adapters": { | 64 | "adapters": { |
| 62 | - name: _cpu_tensor(value) for name, value in self.model_parts[0].named_parameters() | 65 | + name: _cpu_tensor(value) |
| 66 | + for name, value in self.engine.model_parts[0].named_parameters() | ||
| 63 | if is_lora_parameter(name) | 67 | if is_lora_parameter(name) |
| 64 | }, | 68 | }, |
| 65 | "optimizer": {name: _cpu_tensor(value) for name, value in optimizer.items() | 69 | "optimizer": {name: _cpu_tensor(value) for name, value in optimizer.items() |
| @@ -68,7 +72,7 @@ class V41LoRATrainer(LoRATrainer, DeepSeekV41Trainer): | |||
| 68 | assert tensors["adapters"] and tensors["optimizer"] | 72 | assert tensors["adapters"] and tensors["optimizer"] |
| 69 | metadata = {name: value for name, value in optimizer.items() if not isinstance(value, torch.Tensor)} | 73 | metadata = {name: value for name, value in optimizer.items() if not isinstance(value, torch.Tensor)} |
| 70 | path = Path(self.config.dump_folder) / f"resume_state_step{step}_rank{dist.get_rank()}.pt" | 74 | path = Path(self.config.dump_folder) / f"resume_state_step{step}_rank{dist.get_rank()}.pt" |
| 71 | - if (self.config.checkpoint.load_step or 0) > 0: | 75 | + if self.config.checkpointer.load_step > 0: |
| 72 | expected = torch.load(path, map_location="cpu", weights_only=True) | 76 | expected = torch.load(path, map_location="cpu", weights_only=True) |
| 73 | torch.testing.assert_close(tensors, expected["tensors"], rtol=0, atol=0) | 77 | torch.testing.assert_close(tensors, expected["tensors"], rtol=0, atol=0) |
| 74 | assert metadata == expected["metadata"] | 78 | assert metadata == expected["metadata"] |
| @@ -79,22 +83,23 @@ class V41LoRATrainer(LoRATrainer, DeepSeekV41Trainer): | |||
| 79 | torch.save({"tensors": tensors, "metadata": metadata}, stream) | 83 | torch.save({"tensors": tensors, "metadata": metadata}, stream) |
| 80 | 84 | ||
| 81 | def train_step(self, data_iterator): | 85 | def train_step(self, data_iterator): |
| 82 | - checkpoint = self.config.checkpoint | 86 | + checkpoint = self.config.checkpointer |
| 83 | - load_step = checkpoint.load_step or 0 | 87 | + load_step = checkpoint.load_step |
| 84 | - if self.config.check_resume_state and load_step > 0 and self.step == load_step + 1: | 88 | + if self.config.check_resume_state and load_step > 0 and self.engine.num_completed_steps == load_step: |
| 85 | self._check_resume_state(load_step) | 89 | self._check_resume_state(load_step) |
| 86 | - tables = [m for m in self.model_parts[0].modules() if isinstance(m, HostEngramTable)] | 90 | + tables = [m for m in self.engine.model_parts[0].modules() if isinstance(m, HostEngramTable)] |
| 87 | assert len(tables) == 2 | 91 | assert len(tables) == 2 |
| 88 | super().train_step(data_iterator) | 92 | super().train_step(data_iterator) |
| 89 | assert all(table.pending_sparse_grad() is None for table in tables) | 93 | assert all(table.pending_sparse_grad() is None for table in tables) |
| 90 | assert all(not table.weight.requires_grad for table in tables) | 94 | assert all(not table.weight.requires_grad for table in tables) |
| 91 | - if self.config.check_resume_state and self.step >= checkpoint.interval: | 95 | + step = self.engine.num_completed_steps |
| 92 | - self._check_resume_state(self.step) | 96 | + if self.config.check_resume_state and step >= checkpoint.interval: |
| 97 | + self._check_resume_state(step) | ||
| 93 | 98 | ||
| 94 | 99 | ||
| 95 | def deepseek_v4_1_lora_training(): | 100 | def deepseek_v4_1_lora_training(): |
| 96 | config = deepseek_v4_1_debugmodel_lora() | 101 | config = deepseek_v4_1_debugmodel_lora() |
| 97 | - config.checkpoint.periodic_save_adapter_only = False | 102 | + config.checkpointer.periodic_save_adapter_only = False |
| 98 | return derive(config, V41LoRATrainer.Config) | 103 | return derive(config, V41LoRATrainer.Config) |
| 99 | 104 | ||
| 100 | 105 | ||
| @@ -109,7 +114,7 @@ def deepseek_v4_1_lora_quantized_training(): | |||
| 109 | def deepseek_v4_1_lora_adapter_only_training(): | 114 | def deepseek_v4_1_lora_adapter_only_training(): |
| 110 | config = deepseek_v4_1_lora_training() | 115 | config = deepseek_v4_1_lora_training() |
| 111 | config.check_resume_state = True | 116 | config.check_resume_state = True |
| 112 | - config.checkpoint.periodic_save_adapter_only = True | 117 | + config.checkpointer.periodic_save_adapter_only = True |
| 113 | return config | 118 | return config |
| 114 | 119 | ||
| 115 | 120 | ||
| @@ -33,6 +33,7 @@ from torchtitan_npu.extensions.adaptor.torchao.converter import ( | |||
| 33 | apply_quantization_converter, | 33 | apply_quantization_converter, |
| 34 | ) | 34 | ) |
| 35 | from torchtitan_npu.models.deepseek_v4 import model_registry | 35 | from torchtitan_npu.models.deepseek_v4 import model_registry |
| 36 | +from torchtitan_npu.models.deepseek_v4_1 import model_registry as v41_model_registry | ||
| 36 | 37 | ||
| 37 | 38 | ||
| 38 | def _quantization_config(**overrides) -> QuantizationExtensionConfig: | 39 | def _quantization_config(**overrides) -> QuantizationExtensionConfig: |
| @@ -50,15 +51,22 @@ def _collect_flags(model_config) -> dict[str, bool]: | |||
| 50 | return flags | 51 | return flags |
| 51 | 52 | ||
| 52 | 53 | ||
| 53 | -def test_default_whitelist_keeps_prequantize_on_all_dense_projections(): | 54 | +@pytest.mark.parametrize("family", ["v4", "v41"]) |
| 55 | +def test_default_whitelist_keeps_prequantize_on_all_dense_projections(family): | ||
| 54 | """fsdp_prequantize_fqns=None resolves to the recipe default whitelist.""" | 56 | """fsdp_prequantize_fqns=None resolves to the recipe default whitelist.""" |
| 55 | - spec = model_registry("debugmodel", num_mtp_layers=0) | 57 | + spec = ( |
| 58 | + model_registry("debugmodel", num_mtp_layers=0) | ||
| 59 | + if family == "v4" | ||
| 60 | + else v41_model_registry("deepseek_v4_1_stripped") | ||
| 61 | + ) | ||
| 56 | quantization = _quantization_config(enable_fsdp_prequantize=True) | 62 | quantization = _quantization_config(enable_fsdp_prequantize=True) |
| 57 | 63 | ||
| 58 | converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False) | 64 | converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False) |
| 59 | 65 | ||
| 60 | flags = _collect_flags(converted) | 66 | flags = _collect_flags(converted) |
| 61 | assert flags, "debugmodel must expose quantized Linear nodes" | 67 | assert flags, "debugmodel must expose quantized Linear nodes" |
| 68 | + shared_gate_up = {fqn for fqn, _, _, _ in spec.traverse(Linear.Config) if fqn.endswith(".moe.shared_experts.w13")} | ||
| 69 | + assert shared_gate_up and shared_gate_up <= flags.keys() | ||
| 62 | assert all(flags.values()), f"default whitelist must enable every dense weight: {flags}" | 70 | assert all(flags.values()), f"default whitelist must enable every dense weight: {flags}" |
| 63 | 71 | ||
| 64 | 72 | ||
| @@ -18,7 +18,7 @@ from torch import multiprocessing as mp | |||
| 18 | from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper | 18 | from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import checkpoint_wrapper |
| 19 | from torch.distributed.device_mesh import init_device_mesh | 19 | from torch.distributed.device_mesh import init_device_mesh |
| 20 | from torch.distributed.tensor import Shard, distribute_tensor | 20 | from torch.distributed.tensor import Shard, distribute_tensor |
| 21 | -from torchtitan.components.checkpointer import ModelWrapper | 21 | +from torchtitan.components.checkpointer import AsyncMode, ModelWrapper |
| 22 | 22 | ||
| 23 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _build_model_config | 23 | from tests.unit_tests.models.deepseek_v4.lora_test_utils import _build_model_config |
| 24 | from torchtitan_npu.models.deepseek_v4 import lora, peft, state_dict_adapter | 24 | from torchtitan_npu.models.deepseek_v4 import lora, peft, state_dict_adapter |
| @@ -279,7 +279,7 @@ class _FinalSaveCheckpoint(peft.DeepSeekV4PEFTCheckpointManager): | |||
| 279 | return self.checkpoint_dir | 279 | return self.checkpoint_dir |
| 280 | 280 | ||
| 281 | 281 | ||
| 282 | -def _save_peft(rank, root, fail_finalization): | 282 | +def _save_peft(rank, root, failure): |
| 283 | model = torch.nn.Module() | 283 | model = torch.nn.Module() |
| 284 | mesh = init_device_mesh("cpu", (2,)) | 284 | mesh = init_device_mesh("cpu", (2,)) |
| 285 | adapter = distribute_tensor(torch.arange(6).reshape(2, 3).float(), mesh, [Shard(0)]) | 285 | adapter = distribute_tensor(torch.arange(6).reshape(2, 3).float(), mesh, [Shard(0)]) |
| @@ -288,11 +288,16 @@ def _save_peft(rank, root, fail_finalization): | |||
| 288 | manager.states = {"model": ModelWrapper(model)} | 288 | manager.states = {"model": ModelWrapper(model)} |
| 289 | manager.last_save_in_peft = True | 289 | manager.last_save_in_peft = True |
| 290 | manager.peft_base_model_name_or_path = None | 290 | manager.peft_base_model_name_or_path = None |
| 291 | - manager.sd_adapter = _MappingStubAdapter(fail_finalization) | 291 | + manager.sd_adapter = _MappingStubAdapter(failure == "finalization") |
| 292 | manager.initial_load_path = "" | 292 | manager.initial_load_path = "" |
| 293 | manager.initial_load_in_hf = False | 293 | manager.initial_load_in_hf = False |
| 294 | manager.export_dtype = torch.float32 | 294 | manager.export_dtype = torch.float32 |
| 295 | manager.checkpoint_dir = str(Path(root) / "checkpoint") | 295 | manager.checkpoint_dir = str(Path(root) / "checkpoint") |
| 296 | + manager.load_only = manager.enable_first_step_checkpoint = manager.verify_hash_manifest = False | ||
| 297 | + manager.keep_latest_k = 0 | ||
| 298 | + manager.async_mode = AsyncMode.DISABLED | ||
| 299 | + manager.stager = None | ||
| 300 | + manager.staging_future = manager.save_future = None | ||
| 296 | 301 | ||
| 297 | def unexpected_dcp_save(*args, **kwargs): | 302 | def unexpected_dcp_save(*args, **kwargs): |
| 298 | raise AssertionError("PEFT export must not use DCP save") | 303 | raise AssertionError("PEFT export must not use DCP save") |
| @@ -300,15 +305,24 @@ def _save_peft(rank, root, fail_finalization): | |||
| 300 | original_save = dcp.save | 305 | original_save = dcp.save |
| 301 | try: | 306 | try: |
| 302 | dcp.save = unexpected_dcp_save | 307 | dcp.save = unexpected_dcp_save |
| 303 | - manager._save_last_step(1) | 308 | + assert manager.save(1, last_step=True) |
| 304 | finally: | 309 | finally: |
| 305 | dcp.save = original_save | 310 | dcp.save = original_save |
| 306 | 311 | ||
| 307 | 312 | ||
| 308 | -@pytest.mark.parametrize("fail_finalization", [False, True], ids=["adapter-file", "rank-zero-io-failure"]) | 313 | +@pytest.mark.parametrize("failure", [None, "preflight", "finalization"]) |
| 309 | -def test_final_peft_save_finishes_consistently_across_ranks(tmp_path, fail_finalization): | 314 | +def test_final_peft_save_finishes_consistently_across_ranks(tmp_path, failure): |
| 310 | - messages = _run_distributed(tmp_path, _save_peft, fail_finalization) | 315 | + checkpoint = tmp_path / "checkpoint" |
| 311 | - if fail_finalization: | 316 | + if failure == "preflight": |
| 317 | + peft.DeepSeekV4PEFTCheckpointManager._finalize_peft_directory( | ||
| 318 | + str(checkpoint), {"peft_type": "LORA"}, {"lora_a": torch.ones(1)} | ||
| 319 | + ) | ||
| 320 | + messages = _run_distributed(tmp_path, _save_peft, failure) | ||
| 321 | + if failure == "preflight": | ||
| 322 | + assert messages[0] and "PEFT checkpoint preflight failed: FileExistsError" in messages[0] | ||
| 323 | + assert messages[1] == messages[0] | ||
| 324 | + torch.testing.assert_close(load_file(checkpoint / "adapter_model.safetensors")["lora_a"], torch.ones(1)) | ||
| 325 | + elif failure == "finalization": | ||
| 312 | assert all( | 326 | assert all( |
| 313 | message and "PEFT checkpoint finalization failed: OSError: injected" in message for message in messages | 327 | message and "PEFT checkpoint finalization failed: OSError: injected" in message for message in messages |
| 314 | ) | 328 | ) |
| @@ -5,6 +5,7 @@ | |||
| 5 | 5 | ||
| 6 | import copy | 6 | import copy |
| 7 | import json | 7 | import json |
| 8 | +from contextlib import closing | ||
| 8 | from dataclasses import dataclass | 9 | from dataclasses import dataclass |
| 9 | 10 | ||
| 10 | import pytest | 11 | import pytest |
| @@ -119,7 +120,7 @@ def _write_native_base(path, model): | |||
| 119 | validation._write_manifest(path) | 120 | validation._write_manifest(path) |
| 120 | 121 | ||
| 121 | 122 | ||
| 122 | -def _manager(path, base, config, family, model, *, save_training_state=True, verify=False, initial_hf=True): | 123 | +def _manager(path, base, config, family, model, *, save_training_state=True, verify=False, initial_hf=True, keep=0): |
| 123 | optimizer = OptimizersContainer.Config( | 124 | optimizer = OptimizersContainer.Config( |
| 124 | optimizers=[AdamW.Config(pattern=".*", lr=0.02, weight_decay=0.0, fused=False)] | 125 | optimizers=[AdamW.Config(pattern=".*", lr=0.02, weight_decay=0.0, fused=False)] |
| 125 | ).build(model_parts=[model]) | 126 | ).build(model_parts=[model]) |
| @@ -129,7 +130,7 @@ def _manager(path, base, config, family, model, *, save_training_state=True, ver | |||
| 129 | manager = owner.Config( | 130 | manager = owner.Config( |
| 130 | folder=str(path), | 131 | folder=str(path), |
| 131 | interval=1, | 132 | interval=1, |
| 132 | - keep_latest_k=0, | 133 | + keep_latest_k=keep, |
| 133 | initial_load_path=str(base), | 134 | initial_load_path=str(base), |
| 134 | initial_load_in_hf=initial_hf, | 135 | initial_load_in_hf=initial_hf, |
| 135 | last_save_in_peft=False, | 136 | last_save_in_peft=False, |
| @@ -147,6 +148,92 @@ def _manager(path, base, config, family, model, *, save_training_state=True, ver | |||
| 147 | return manager | 148 | return manager |
| 148 | 149 | ||
| 149 | 150 | ||
| 151 | +def test_peft_retention_preserves_resume_point_and_uses_normal_cleanup(tmp_path, monkeypatch): | ||
| 152 | + config = _model_config(monkeypatch, "v4") | ||
| 153 | + root = tmp_path / "checkpoints" | ||
| 154 | + base = tmp_path / "base" | ||
| 155 | + _write_native_base(base, _model(config)) | ||
| 156 | + monkeypatch.setattr(torch.distributed, "get_rank", lambda: 0) | ||
| 157 | + | ||
| 158 | + def new_manager(): | ||
| 159 | + return _manager(root, base, config, "v4", _model(config), verify=True, initial_hf=False, keep=2) | ||
| 160 | + | ||
| 161 | + def retained(): | ||
| 162 | + return {path.name for path in root.iterdir()} | ||
| 163 | + | ||
| 164 | + with closing(new_manager()) as manager: | ||
| 165 | + manager.states["train_state"].step = manager.states["dataloader"].step = 1 | ||
| 166 | + assert manager.save(1) | ||
| 167 | + weights_only = root / "step-3" | ||
| 168 | + adapters = { | ||
| 169 | + name: value for name, value in manager.states["model"].state_dict().items() if is_lora_parameter(name) | ||
| 170 | + } | ||
| 171 | + dcp.save(adapters, checkpoint_id=weights_only) | ||
| 172 | + validation._write_manifest(weights_only) | ||
| 173 | + manager._finalize_peft_directory(str(root / "step-4"), {"peft_type": "LORA"}, {"a": torch.ones(1)}) | ||
| 174 | + assert manager._find_load_step() == 1 | ||
| 175 | + assert retained() == {"step-1", "step-3", "step-4"} | ||
| 176 | + | ||
| 177 | + with closing(new_manager()) as manager: | ||
| 178 | + assert manager.load() | ||
| 179 | + assert manager.states["train_state"].step == manager.states["dataloader"].step == 1 | ||
| 180 | + native_save = manager.dcp_save | ||
| 181 | + | ||
| 182 | + def interrupted_save(*args, **kwargs): | ||
| 183 | + native_save(*args, **kwargs) | ||
| 184 | + raise OSError("injected failure before manifest completion") | ||
| 185 | + | ||
| 186 | + with monkeypatch.context() as patch: | ||
| 187 | + patch.setattr(manager, "dcp_save", interrupted_save) | ||
| 188 | + with pytest.raises(OSError, match="before manifest completion"): | ||
| 189 | + manager.save(5) | ||
| 190 | + assert (root / "step-5" / ".metadata").is_file() | ||
| 191 | + assert not validation.is_checkpoint_manifest_complete(root / "step-5", required=False) | ||
| 192 | + assert manager._find_load_step() == 1 | ||
| 193 | + assert retained() == {"step-1", "step-4", "step-5"} | ||
| 194 | + | ||
| 195 | + with closing(new_manager()) as manager: | ||
| 196 | + manager.states["train_state"].step = manager.states["dataloader"].step = 5 | ||
| 197 | + assert manager.save(5) | ||
| 198 | + assert validation.is_checkpoint_manifest_complete(root / "step-5", required=True) | ||
| 199 | + assert manager._find_load_step() == 5 | ||
| 200 | + assert manager._find_load_step(max_step=4) == 1 | ||
| 201 | + assert retained() == {"step-1", "step-4", "step-5"} | ||
| 202 | + | ||
| 203 | + with closing(new_manager()) as manager: | ||
| 204 | + assert manager.load() | ||
| 205 | + assert manager.states["train_state"].step == manager.states["dataloader"].step == 5 | ||
| 206 | + assert manager.save(6) | ||
| 207 | + assert manager._find_load_step() == 6 | ||
| 208 | + assert retained() == {"step-5", "step-6"} | ||
| 209 | + | ||
| 210 | + | ||
| 211 | +def test_peft_retention_preserves_native_resume_when_newer_dcp_lacks_adapters(tmp_path, monkeypatch): | ||
| 212 | + config = _model_config(monkeypatch, "v4") | ||
| 213 | + root = tmp_path / "checkpoints" | ||
| 214 | + base = tmp_path / "base" | ||
| 215 | + _write_native_base(base, _model(config)) | ||
| 216 | + monkeypatch.setattr(torch.distributed, "get_rank", lambda: 0) | ||
| 217 | + | ||
| 218 | + with closing(_manager(root, base, config, "v4", _model(config), initial_hf=False, keep=2)) as manager: | ||
| 219 | + manager.states["train_state"].step = manager.states["dataloader"].step = 1 | ||
| 220 | + assert manager.save(1) | ||
| 221 | + saved = manager._flattened_model_states_sd() | ||
| 222 | + dcp.save( | ||
| 223 | + {name: value for name, value in saved.items() if not is_lora_parameter(name)}, checkpoint_id=root / "step-2" | ||
| 224 | + ) | ||
| 225 | + | ||
| 226 | + assert manager.load() | ||
| 227 | + assert manager.states["train_state"].step == 1 | ||
| 228 | + with pytest.raises(ValueError, match="requires adapter tensors"): | ||
| 229 | + manager.load(step=2) | ||
| 230 | + | ||
| 231 | + manager._purge_stale_checkpoints(saving_step=3) | ||
| 232 | + manager._finalize_peft_directory(str(root / "step-3"), {"peft_type": "LORA"}, {"a": torch.ones(1)}) | ||
| 233 | + | ||
| 234 | + assert {path.name for path in root.iterdir()} == {"step-1", "step-2", "step-3"} | ||
| 235 | + | ||
| 236 | + | ||
| 150 | def _clone_state(model): | 237 | def _clone_state(model): |
| 151 | return {key: value.detach().clone() for key, value in model.state_dict().items()} | 238 | return {key: value.detach().clone() for key, value in model.state_dict().items()} |
| 152 | 239 | ||
| @@ -371,15 +458,38 @@ def test_real_hf_entry_forwards_quantized_flag_to_reader_boundary(tmp_path, monk | |||
| 371 | manager.close() | 458 | manager.close() |
| 372 | 459 | ||
| 373 | 460 | ||
| 374 | -def test_v41_real_resume_entry_rejects_native_checkpoint_without_adapters(tmp_path, monkeypatch): | 461 | +@pytest.mark.parametrize("family", ["v4", "v41"]) |
| 375 | - config = _model_config(monkeypatch, "v41") | 462 | +@pytest.mark.parametrize("missing", ["all", "one"]) |
| 463 | +def test_real_resume_rejects_missing_adapters_before_loading_any_live_state(tmp_path, monkeypatch, family, missing): | ||
The A3 continuous/resume evidence for 28e378d is valuable and should remain part of the record. The reviewed head is now 5e435f3, the target branch has advanced, and both A3 smoke jobs in CI #2391 were skipped. Could a focused A3 check be attached for the current merged result and pinned upstream: nonzero adapter updates, native save, fresh-process resume, then PEFT export, comparing subsequent updates with an uninterrupted run? Please record the tested source/upstream SHAs, effective configuration, per-rank checks and exit codes. This is a current-revision validation gap; it does not mean that no hardware validation exists, and it does not require repeating unrelated full-length training. ![]() ![]() leedongkun30-arch 25 days ago Comments: 25 days ago Comments: ![]() ![]() | |||
| 464 | + config = _model_config(monkeypatch, family) | ||
| 376 | model = _model(config) | 465 | model = _model(config) |
| 377 | run = tmp_path / "run" | 466 | run = tmp_path / "run" |
| 378 | - _write_native_base(run / "step-3", model) | 467 | + saved = _clone_state(model) |
| 379 | - manager = _manager(run, tmp_path / "base", config, "v41", model) | 468 | + adapter_names = sorted(name for name in saved if is_lora_parameter(name)) |
| 469 | + assert len(adapter_names) > 1 | ||
| 470 | + for name in adapter_names if missing == "all" else adapter_names[:1]: | ||
| 471 | + del saved[name] | ||
| 472 | + # A complete base must not make an incomplete adapter resume acceptable. | ||
| 473 | + saved = {name: value + 3 for name, value in saved.items()} | ||
| 474 | + dcp.save(saved, checkpoint_id=run / "step-3") | ||
| 475 | + manager = _manager(run, tmp_path / "base", config, family, model) | ||
| 476 | + before = _clone_state(model) | ||
| 477 | + ema_before = copy.deepcopy(manager.states[EMA_KEY].state_dict()) | ||
| 478 | + loads = [] | ||
| 479 | + original_load = dcp.load | ||
| 480 | + | ||
| 481 | + def record_load(*args, **kwargs): | ||
| 482 | + loads.append(kwargs.get("checkpoint_id")) | ||
| 483 | + return original_load(*args, **kwargs) | ||
| 484 | + | ||
| 485 | + monkeypatch.setattr(dcp, "load", record_load) | ||
| 380 | try: | 486 | try: |
| 381 | with pytest.raises(ValueError, match="requires adapter tensors"): | 487 | with pytest.raises(ValueError, match="requires adapter tensors"): |
| 382 | manager.load() | 488 | manager.load() |
| 489 | + assert loads == [] | ||
| 490 | + _assert_state(model.state_dict(), before) | ||
| 491 | + _assert_state(manager.states[EMA_KEY].state_dict(), ema_before) | ||
| 492 | + assert manager.states["train_state"].step == manager.states["dataloader"].step == 0 | ||
| 383 | finally: | 493 | finally: |
| 384 | manager.close() | 494 | manager.close() |
| 385 | 495 | ||
| @@ -0,0 +1,113 @@ | |||
| 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 | +"""PEFT completion files must describe a successfully published export.""" | ||
| 7 | + | ||
| 8 | +import json | ||
| 9 | +from pathlib import Path | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | +import torch | ||
| 13 | +from safetensors.torch import load_file | ||
| 14 | + | ||
| 15 | +from torchtitan_npu.models.deepseek_v4 import peft | ||
| 16 | + | ||
| 17 | +pytestmark = pytest.mark.cpu | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@pytest.mark.parametrize("failure", ["weights", "config", "rename_weights", "rename_config"]) | ||
| 21 | +def test_failed_export_never_publishes_completion(tmp_path, monkeypatch, failure): | ||
| 22 | + def interrupted_write(*args, **kwargs): | ||
| 23 | + raise OSError("injected export failure") | ||
| 24 | + | ||
| 25 | + replace = peft.os.replace | ||
| 26 | + failed_destination = "adapter_model.safetensors" if failure == "rename_weights" else "adapter_config.json" | ||
| 27 | + | ||
| 28 | + def interrupted_replace(source, destination): | ||
| 29 | + if Path(destination).name == failed_destination: | ||
| 30 | + interrupted_write() | ||
| 31 | + replace(source, destination) | ||
| 32 | + | ||
| 33 | + finalize = peft.DeepSeekV4PEFTCheckpointManager._finalize_peft_directory | ||
| 34 | + config = {"peft_type": "LORA"} | ||
| 35 | + weights = {"lora_a": torch.ones(2, 3)} | ||
| 36 | + previous = tmp_path / "step-1" | ||
| 37 | + finalize(str(previous), config, weights) | ||
| 38 | + previous_files = {path.name: path.read_bytes() for path in previous.iterdir()} | ||
| 39 | + folder = tmp_path / "step-2" | ||
| 40 | + with monkeypatch.context() as patch: | ||
| 41 | + if failure == "weights": | ||
| 42 | + patch.setattr(peft, "save_file", interrupted_write) | ||
| 43 | + elif failure == "config": | ||
| 44 | + patch.setattr(peft.json, "dump", interrupted_write) | ||
| 45 | + else: | ||
| 46 | + patch.setattr(peft.os, "replace", interrupted_replace) | ||
| 47 | + with pytest.raises(OSError, match="injected export failure"): | ||
| 48 | + finalize(str(folder), config, weights) | ||
| 49 | + assert not (folder / "adapter_config.json").exists() | ||
| 50 | + assert {path.name for path in folder.iterdir()} == ( | ||
| 51 | + {"adapter_model.safetensors"} if failure == "rename_config" else set() | ||
| 52 | + ) | ||
| 53 | + | ||
| 54 | + finalize(str(folder), config, weights) | ||
| 55 | + assert json.loads((folder / "adapter_config.json").read_text()) == config | ||
| 56 | + torch.testing.assert_close(load_file(folder / "adapter_model.safetensors"), weights) | ||
| 57 | + assert {path.name: path.read_bytes() for path in previous.iterdir()} == previous_files | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +@pytest.mark.parametrize("existing_file", [".metadata", "adapter_config.json"], ids=["native", "peft"]) | ||
| 61 | +def test_export_does_not_modify_existing_checkpoint(tmp_path, existing_file): | ||
| 62 | + folder = tmp_path / "step-1" | ||
| 63 | + folder.mkdir() | ||
| 64 | + original = folder / existing_file | ||
| 65 | + original.write_bytes(b"existing checkpoint") | ||
| 66 | + with pytest.raises(FileExistsError, match="already exists"): | ||
| 67 | + peft.DeepSeekV4PEFTCheckpointManager._finalize_peft_directory( | ||
| 68 | + str(folder), {"peft_type": "LORA"}, {"lora_a": torch.ones(2, 3)}, | ||
| 69 | + ) | ||
| 70 | + assert original.read_bytes() == b"existing checkpoint" | ||
| 71 | + assert list(folder.iterdir()) == [original] | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def test_export_publishes_exact_payload_and_preserves_pending_manifest(tmp_path): | ||
| 75 | + folder = tmp_path / "step-1" | ||
| 76 | + folder.mkdir() | ||
| 77 | + pending = folder / "_checkpoint_hash_manifest.pending" | ||
| 78 | + pending.write_text("pending\n") | ||
| 79 | + weights = {"lora_a": torch.arange(6).reshape(2, 3).float()} | ||
| 80 | + config = {"peft_type": "LORA", "r": 2} | ||
| 81 | + peft.DeepSeekV4PEFTCheckpointManager._finalize_peft_directory(str(folder), config, weights) | ||
| 82 | + torch.testing.assert_close(load_file(folder / "adapter_model.safetensors"), weights, rtol=0, atol=0) | ||
| 83 | + assert json.loads((folder / "adapter_config.json").read_text()) == config | ||
| 84 | + assert pending.read_text() == "pending\n" | ||
| 85 | + assert sorted(path.name for path in folder.iterdir()) == [ | ||
| 86 | + "_checkpoint_hash_manifest.pending", "adapter_config.json", "adapter_model.safetensors", | ||
| 87 | + ] | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def test_stacked_shared_adapter_export_writes_independent_safetensors(tmp_path): | ||
| 91 | + from tests.unit_tests.models.deepseek_v4.lora_test_utils import _lora_model_config | ||
| 92 | + from torchtitan_npu.models.deepseek_v4.lora import is_lora_parameter | ||
| 93 | + from torchtitan_npu.models.deepseek_v4.state_dict_adapter import DeepSeekV4StateDictAdapter | ||
| 94 | + | ||
| 95 | + config = _lora_model_config() | ||
| 96 | + model = config.build() | ||
| 97 | + model.init_states(buffer_device=torch.device("cpu")) | ||
| 98 | + state = {name: value for name, value in model.state_dict().items() if is_lora_parameter(name)} | ||
| 99 | + adapter = DeepSeekV4StateDictAdapter(config, hf_assets_path=None) | ||
| 100 | + expected = adapter.to_peft(state) | ||
| 101 | + gate = "base_model.model.model.layers.0.mlp.shared_experts.gate_proj.lora_A.weight" | ||
| 102 | + up = "base_model.model.model.layers.0.mlp.shared_experts.up_proj.lora_A.weight" | ||
| 103 | + assert expected[gate].data_ptr() == expected[up].data_ptr() | ||
| 104 | + manager = object.__new__(peft.DeepSeekV4PEFTCheckpointManager) | ||
| 105 | + manager.sd_adapter = adapter | ||
| 106 | + | ||
| 107 | + folder = tmp_path / "step-4" | ||
| 108 | + manager.finalize_peft_checkpoint(str(folder), adapter.peft_adapter_config(), state) | ||
| 109 | + | ||
| 110 | + restored = load_file(folder / "adapter_model.safetensors") | ||
| 111 | + torch.testing.assert_close(restored, expected, rtol=0, atol=0) | ||
| 112 | + assert restored[gate].data_ptr() != restored[up].data_ptr() | ||
| 113 | + assert json.loads((folder / "adapter_config.json").read_text())["peft_type"] == "LORA" | ||
| @@ -132,29 +132,74 @@ def test_compile_friendly_local_reorder_matches_upstream(): | |||
| 132 | """The compile-time opt-in reorder is the exact upstream permutation.""" | 132 | """The compile-time opt-in reorder is the exact upstream permutation.""" |
| 133 | pytest.importorskip("torch_npu") | 133 | pytest.importorskip("torch_npu") |
| 134 | from torchtitan_npu.override.common.token_dispatcher import ( | 134 | from torchtitan_npu.override.common.token_dispatcher import ( |
| 135 | - apply_compile_friendly_local_reorder, | 135 | + configure_dispatchers_for_compile, |
| 136 | ) | 136 | ) |
| 137 | 137 | ||
| 138 | - fake_self = SimpleNamespace(num_experts=4, top_k=2) | ||
| 139 | x_TD = torch.randn(8, 3) | 138 | x_TD = torch.randn(8, 3) |
| 140 | scores_TK = torch.rand(8, 2) | 139 | scores_TK = torch.rand(8, 2) |
| 141 | expert_ids_TK = torch.tensor([[3, 1], [0, 0], [2, 1], [1, 3], [0, 2], [3, 3], [1, 0], [2, 2]]) | 140 | expert_ids_TK = torch.tensor([[3, 1], [0, 0], [2, 1], [1, 3], [0, 2], [3, 3], [1, 0], [2, 2]]) |
| 142 | 141 | ||
| 143 | - saved = ( | 142 | + for cls in (LocalTokenDispatcher, AllToAllTokenDispatcher): |
| 144 | - LocalTokenDispatcher._local_reorder, | 143 | + config = cls.Config(num_experts=4, top_k=2) |
| 145 | - AllToAllTokenDispatcher._local_reorder, | 144 | + compiled, eager = cls(config), cls(config) |
| 145 | + original = cls._local_reorder | ||
| 146 | + configure_dispatchers_for_compile(compiled, eager_all_to_all=False) | ||
| 147 | + assert cls._local_reorder is original | ||
| 148 | + assert compiled._local_reorder.__func__ is not original | ||
| 149 | + assert eager._local_reorder.__func__ is original | ||
| 150 | + patched = compiled._local_reorder(x_TD, scores_TK, expert_ids_TK) | ||
| 151 | + upstream = eager._local_reorder(x_TD, scores_TK, expert_ids_TK) | ||
| 152 | + for got, want in zip(patched, upstream, strict=True): | ||
| 153 | + torch.testing.assert_close(got, want) | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def test_v41_compile_keeps_variable_splits_eager_and_model_local(monkeypatch): | ||
| 157 | + import torch._inductor.config as inductor_config | ||
| 158 | + | ||
| 159 | + from torchtitan_npu.models.deepseek_v4_1.parallelize import _apply_compile_v4_1 | ||
| 160 | + | ||
| 161 | + class SplitDispatcher(AllToAllTokenDispatcher): | ||
| 162 | + @property | ||
| 163 | + def ep_mesh(self): | ||
| 164 | + return object() | ||
| 165 | + | ||
| 166 | + def dispatch(self, x, count): | ||
| 167 | + assert not torch.compiler.is_compiling() | ||
| 168 | + return x.split((count, x.numel() - count)) | ||
| 169 | + | ||
| 170 | + def combine(self, left, right): | ||
| 171 | + assert not torch.compiler.is_compiling() | ||
| 172 | + return torch.cat((left, right)) | ||
| 173 | + | ||
| 174 | + class Block(torch.nn.Module): | ||
| 175 | + def __init__(self): | ||
| 176 | + super().__init__() | ||
| 177 | + self.dispatcher = SplitDispatcher(SplitDispatcher.Config(num_experts=2, top_k=1)) | ||
| 178 | + | ||
| 179 | + def forward(self, x, count): | ||
| 180 | + left, right = self.dispatcher.dispatch(x, count) | ||
| 181 | + return self.dispatcher.combine(left.square(), right * 3) | ||
| 182 | + | ||
| 183 | + # Run the production compile assembly with AOTAutograd on CPU. | ||
| 184 | + compile_module = torch.nn.Module.compile | ||
| 185 | + monkeypatch.setattr( | ||
| 186 | + torch.nn.Module, "compile", lambda module, **kw: compile_module(module, **(kw | {"backend": "aot_eager"})) | ||
| 146 | ) | 187 | ) |
| 147 | - try: | 188 | + monkeypatch.setattr(inductor_config, "do_not_emit_runtime_assertions", False) |
| 148 | - apply_compile_friendly_local_reorder() | 189 | + for setting in ("capture_scalar_outputs", "skip_fwd_side_effects_in_bwd_under_checkpoint"): |
| 149 | - for cls in (LocalTokenDispatcher, AllToAllTokenDispatcher): | 190 | + monkeypatch.setattr(torch._dynamo.config, setting, False) |
| 150 | - upstream = dispatcher_patch.TorchTitanLocalTokenDispatcher._local_reorder( | 191 | + model = torch.nn.Module() |
| 151 | - fake_self, x_TD, scores_TK, expert_ids_TK | 192 | + compiled, eager = Block(), Block() |
| 152 | - ) | 193 | + model.layers = torch.nn.ModuleList([compiled]) |
| 153 | - patched = cls._local_reorder(fake_self, x_TD, scores_TK, expert_ids_TK) | 194 | + _apply_compile_v4_1(model, compile_config=SimpleNamespace(backend="inductor")) |
| 154 | - for got, want in zip(patched, upstream, strict=True): | 195 | + assert inductor_config.do_not_emit_runtime_assertions is False |
| 155 | - torch.testing.assert_close(got, want) | 196 | + assert eager.dispatcher.dispatch.__func__ is SplitDispatcher.dispatch |
| 156 | - finally: | 197 | + for count in (1, 3): |
| 157 | - LocalTokenDispatcher._local_reorder, AllToAllTokenDispatcher._local_reorder = saved | 198 | + x = torch.arange(4.0, requires_grad=True) |
| 199 | + actual = compiled(x, count) | ||
| 200 | + torch.testing.assert_close(actual, eager(x, count)) | ||
| 201 | + actual.sum().backward() | ||
| 202 | + torch.testing.assert_close(x.grad, torch.cat((2 * x[:count], torch.full_like(x[count:], 3)))) | ||
| 158 | 203 | ||
| 159 | 204 | ||
| 160 | def test_ep_dispatch_transports_scores_in_router_dtype(monkeypatch): | 205 | def test_ep_dispatch_transports_scores_in_router_dtype(monkeypatch): |
| @@ -41,9 +41,8 @@ _DENSE = ( | |||
| 41 | ".attention.wo_a", | 41 | ".attention.wo_a", |
| 42 | ".attention.wo_b", | 42 | ".attention.wo_b", |
| 43 | ".attention.indexer.wq_b", | 43 | ".attention.indexer.wq_b", |
| 44 | - ".moe.shared_experts.w1", | 44 | + ".moe.shared_experts.w13", |
| 45 | ".moe.shared_experts.w2", | 45 | ".moe.shared_experts.w2", |
| 46 | - ".moe.shared_experts.w3", | ||
| 47 | ) | 46 | ) |
| 48 | _ROUTED = (".moe.routed_experts.w13", ".moe.routed_experts.w2") | 47 | _ROUTED = (".moe.routed_experts.w13", ".moe.routed_experts.w2") |
| 49 | 48 | ||
| @@ -55,6 +55,13 @@ def _is_writer_and_reader_rank() -> bool: | |||
| 55 | return not (dist.is_available() and dist.is_initialized()) or dist.get_rank() == 0 | 55 | return not (dist.is_available() and dist.is_initialized()) or dist.get_rank() == 0 |
| 56 | 56 | ||
| 57 | 57 | ||
| 58 | +def is_checkpoint_manifest_complete(directory: str | os.PathLike, *, required: bool) -> bool: | ||
| 59 | + """Inspect completion markers without hashing or entering collectives.""" | ||
| 60 | + return not filesystem.exists(filesystem.join(directory, _PENDING_MANIFEST_FILENAME)) and ( | ||
| 61 | + not required or filesystem.isfile(filesystem.join(directory, _MANIFEST_FILENAME)) | ||
| 62 | + ) | ||
| 63 | + | ||
| 64 | + | ||
| 58 | def _clear_manifest_pending(directory: str | os.PathLike) -> None: | 65 | def _clear_manifest_pending(directory: str | os.PathLike) -> None: |
| 59 | pending_path = filesystem.join(directory, _PENDING_MANIFEST_FILENAME) | 66 | pending_path = filesystem.join(directory, _PENDING_MANIFEST_FILENAME) |
| 60 | if filesystem.exists(pending_path): | 67 | if filesystem.exists(pending_path): |
| @@ -9,6 +9,8 @@ __all__ = ["DeepSeekV4PEFTCheckpointManager", "select_adapter_only_state"] | |||
| 9 | import json | 9 | import json |
| 10 | import logging | 10 | import logging |
| 11 | import os | 11 | import os |
| 12 | +import pickle | ||
| 13 | +import tempfile | ||
| 12 | from dataclasses import dataclass | 14 | from dataclasses import dataclass |
| 13 | from typing import Any | 15 | from typing import Any |
| 14 | 16 | ||
| @@ -16,10 +18,11 @@ import torch.distributed as dist | |||
| 16 | import torch.distributed.checkpoint as dcp | 18 | import torch.distributed.checkpoint as dcp |
| 17 | from safetensors.torch import save_file | 19 | from safetensors.torch import save_file |
| 18 | from torch.distributed.tensor import DTensor | 20 | from torch.distributed.tensor import DTensor |
| 19 | -from torchtitan.components.checkpointer import EMA, MODEL | 21 | +from torchtitan.components.checkpointer import DATALOADER, EMA, LR_SCHEDULER, MODEL, OPTIMIZER, TRAIN_STATE |
| 20 | from torchtitan.components.checkpointer.utils import canonical_fqn | 22 | from torchtitan.components.checkpointer.utils import canonical_fqn |
| 21 | from torchtitan.tools import filesystem | 23 | from torchtitan.tools import filesystem |
| 22 | 24 | ||
| 25 | +from torchtitan_npu.extensions.components.validation import is_checkpoint_manifest_complete | ||
| 23 | from torchtitan_npu.extensions.torchtitan.components import checkpoint as checkpoint_extensions | 26 | from torchtitan_npu.extensions.torchtitan.components import checkpoint as checkpoint_extensions |
| 24 | from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager as NPUCheckpointManager | 27 | from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager as NPUCheckpointManager |
| 25 | 28 | ||
| @@ -71,16 +74,120 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 71 | self.last_save_in_peft = config.last_save_in_peft | 74 | self.last_save_in_peft = config.last_save_in_peft |
| 72 | self.periodic_save_adapter_only = config.periodic_save_adapter_only | 75 | self.periodic_save_adapter_only = config.periodic_save_adapter_only |
| 73 | self.save_training_state = config.save_training_state | 76 | self.save_training_state = config.save_training_state |
| 77 | + self._purge_resume_step = -1 | ||
| 74 | if self.periodic_save_adapter_only and not self.initial_load_path: | 78 | if self.periodic_save_adapter_only and not self.initial_load_path: |
The V4/V4.1 LoRA guides still show --optimizer.name, --checkpoint.* and DeepSeekV4LoRAConverter.Config(...), while the current recipes/scripts use optim.optimizer, checkpointer and deepseek_v4_lora_transform(). Could the documented commands and custom-recipe example be updated to the current API, then copied verbatim into a fresh process for argument parsing and a minimal launch? Please verify the effective optimizer, base path, checkpoint folder and load step, including the documented final-native-save and resume options. This is a dev_0.4.0 documentation/migration follow-up, not a new defect in this PR's four-file diff. ![]() ![]() leedongkun30-arch 25 days ago Comments: 25 days ago Comments: ![]() ![]() leedongkun30-arch 25 days ago Comments: 25 days ago Comments: ![]() ![]() | |||
| 75 | raise ValueError("periodic_save_adapter_only requires a fixed initial_load_path for the frozen base") | 79 | raise ValueError("periodic_save_adapter_only requires a fixed initial_load_path for the frozen base") |
| 76 | 80 | ||
| 81 | + def _is_valid_checkpoint(self, checkpoint_dir: str) -> bool: | ||
| 82 | + # Keep the native retention decision independent of the manifest load policy. | ||
| 83 | + if super()._is_resumable_checkpoint(checkpoint_dir) or super()._is_valid_checkpoint(checkpoint_dir): | ||
| 84 | + return True | ||
| 85 | + return is_checkpoint_manifest_complete(checkpoint_dir, required=False) and all( | ||
| 86 | + self._storage.isfile(filesystem.join(checkpoint_dir, name)) | ||
| 87 | + for name in ("adapter_model.safetensors", "adapter_config.json") | ||
| 88 | + ) | ||
| 89 | + | ||
| 90 | + def _is_resumable_checkpoint(self, checkpoint_dir: str) -> bool: | ||
| 91 | + return super()._is_resumable_checkpoint(checkpoint_dir) and is_checkpoint_manifest_complete( | ||
| 92 | + checkpoint_dir, required=self.verify_hash_manifest | ||
| 93 | + ) | ||
| 94 | + | ||
| 95 | + def _find_load_step(self, folder: str = "", max_step: int | None = None) -> int: | ||
| 96 | + folder = folder or self.folder | ||
| 97 | + if not self._storage.isdir(folder): | ||
| 98 | + return -1 | ||
| 99 | + | ||
| 100 | + steps = [] | ||
| 101 | + for dirname in self._storage.listdir(folder): | ||
| 102 | + step = self._parse_step(dirname) | ||
| 103 | + if step is not None and (max_step is None or step <= max_step): | ||
| 104 | + steps.append(step) | ||
| 105 | + | ||
| 106 | + required = { | ||
| 107 | + name for name in (OPTIMIZER, LR_SCHEDULER, DATALOADER, TRAIN_STATE) if self.states.get(name) is not None | ||
| 108 | + } | ||
| 109 | + latest_native = -1 | ||
| 110 | + first_resume_error: ValueError | None = None | ||
| 111 | + for step in sorted(steps, reverse=True): | ||
| 112 | + directory = filesystem.join(folder, f"step-{step}") | ||
| 113 | + if not self._is_resumable_checkpoint(directory): | ||
| 114 | + continue | ||
| 115 | + try: | ||
| 116 | + metadata = dcp.FileSystemReader(directory).read_metadata() | ||
| 117 | + except FileNotFoundError: | ||
| 118 | + # A preceding retention pass may still be deleting this directory. | ||
| 119 | + continue | ||
| 120 | + saved_keys = set(metadata.state_dict_metadata) | ||
| 121 | + try: | ||
| 122 | + self._validate_native_resume(saved_keys) | ||
| 123 | + except ValueError as error: | ||
| 124 | + if first_resume_error is None: | ||
| 125 | + first_resume_error = error | ||
| 126 | + continue | ||
| 127 | + if step == 0: | ||
| 128 | + # The upstream step-0 seed is also a model-only fallback. | ||
| 129 | + return latest_native if latest_native != -1 else 0 | ||
| 130 | + if latest_native == -1: | ||
| 131 | + latest_native = step | ||
| 132 | + saved_states = {key.partition(".")[0] for key in saved_keys} | ||
| 133 | + if required <= saved_states: | ||
| 134 | + return step | ||
| 135 | + | ||
| 136 | + if latest_native == -1 and first_resume_error is not None: | ||
| 137 | + raise first_resume_error | ||
| 138 | + # Keep weights-only restart available for runs that never saved training state. | ||
| 139 | + return latest_native | ||
| 140 | + | ||
| 141 | + def _purge_stale_checkpoints(self, *, saving_step: int, staging_dir_prefix: str | None = None) -> None: | ||
| 142 | + if not self._should_purge(): | ||
| 143 | + return | ||
| 144 | + # Select once before the background worker can delete entries from this pass. | ||
| 145 | + try: | ||
| 146 | + self._purge_resume_step = self._find_load_step() | ||
| 147 | + except (OSError, EOFError, pickle.UnpicklingError, ValueError) as error: | ||
| 148 | + logger.warning("Skipping checkpoint cleanup because a resume checkpoint could not be selected: %s", error) | ||
| 149 | + return | ||
| 150 | + try: | ||
| 151 | + super()._purge_stale_checkpoints(saving_step=saving_step, staging_dir_prefix=staging_dir_prefix) | ||
| 152 | + finally: | ||
| 153 | + self._purge_resume_step = -1 | ||
| 154 | + | ||
| 155 | + def _is_purge_exempt(self, step: int) -> bool: | ||
| 156 | + # Exports can occupy retention slots without replacing a training resume point. | ||
| 157 | + return super()._is_purge_exempt(step) or step == self._purge_resume_step | ||
| 158 | + | ||
| 159 | + def save(self, curr_step: int, last_step: bool = False) -> bool: | ||
| 160 | + if last_step and self.last_save_in_peft and self._should_save(curr_step, last_step): | ||
| 161 | + distributed = dist.is_available() and dist.is_initialized() | ||
| 162 | + status: list[str | None] = [None] | ||
| 163 | + if not distributed or dist.get_rank() == 0: | ||
| 164 | + try: | ||
| 165 | + checkpoint_id = self._create_checkpoint_id(curr_step) | ||
| 166 | + for name in (".metadata", "adapter_config.json"): | ||
| 167 | + if os.path.exists(os.path.join(checkpoint_id, name)): | ||
| 168 | + raise FileExistsError(f"A checkpoint already exists at {checkpoint_id}") | ||
| 169 | + except Exception as exception: | ||
| 170 | + status[0] = f"{type(exception).__name__}: {exception}" | ||
| 171 | + if distributed: | ||
| 172 | + dist.broadcast_object_list(status, src=0) | ||
| 173 | + if status[0] is not None: | ||
| 174 | + raise RuntimeError(f"PEFT checkpoint preflight failed: {status[0]}") | ||
| 175 | + return super().save(curr_step, last_step) | ||
| 176 | + | ||
| 77 | @staticmethod | 177 | @staticmethod |
| 78 | def _finalize_peft_directory(checkpoint_id: str, adapter_config: dict, state_dict: dict) -> None: | 178 | def _finalize_peft_directory(checkpoint_id: str, adapter_config: dict, state_dict: dict) -> None: |
| 79 | os.makedirs(checkpoint_id, exist_ok=True) | 179 | os.makedirs(checkpoint_id, exist_ok=True) |
| 80 | - save_file(state_dict, os.path.join(checkpoint_id, "adapter_model.safetensors")) | 180 | + if any(os.path.exists(os.path.join(checkpoint_id, name)) for name in (".metadata", "adapter_config.json")): |
| 81 | - with open(os.path.join(checkpoint_id, "adapter_config.json"), "w", encoding="utf-8") as output: | 181 | + raise FileExistsError(f"A checkpoint already exists at {checkpoint_id}") |
| 82 | - json.dump(adapter_config, output, indent=2, sort_keys=True) | 182 | + with tempfile.TemporaryDirectory(prefix=".peft-", dir=checkpoint_id) as staging: |
| 83 | - output.write("\n") | 183 | + weights = os.path.join(staging, "adapter_model.safetensors") |
| 184 | + config = os.path.join(staging, "adapter_config.json") | ||
| 185 | + save_file(state_dict, weights) | ||
| 186 | + with open(config, "w", encoding="utf-8") as output: | ||
| 187 | + json.dump(adapter_config, output, indent=2, sort_keys=True) | ||
| 188 | + output.write("\n") | ||
| 189 | + os.replace(weights, os.path.join(checkpoint_id, "adapter_model.safetensors")) | ||
| 190 | + os.replace(config, os.path.join(checkpoint_id, "adapter_config.json")) | ||
The publication tests inject failures in save_file and json.dump, but do not cover failures in the two os.replace calls at peft.py:127-128. Could failures be injected at each rename, particularly after the weights have been published but before adapter_config.json is published? Please verify that the directory is not classified as a completed export, that retry converges, and that the previous completed checkpoint is unchanged. A failed directory need not always be empty; the completion protocol is what matters. Please also exercise the preflight/finalization failure through a two-rank save path with a timeout, checking consistent failure on all ranks rather than a rank left waiting in a collective. This is additional failure-path coverage, not an already-reproduced publication or hang bug. ![]() ![]() | |||
| 84 | 191 | ||
| 85 | def finalize_peft_checkpoint(self, checkpoint_id: str, adapter_config: dict, state_dict: dict) -> None: | 192 | def finalize_peft_checkpoint(self, checkpoint_id: str, adapter_config: dict, state_dict: dict) -> None: |
| 86 | distributed = dist.is_available() and dist.is_initialized() | 193 | distributed = dist.is_available() and dist.is_initialized() |
| @@ -92,7 +199,16 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 92 | if not isinstance(adapter, DeepSeekPEFTAdapter): | 199 | if not isinstance(adapter, DeepSeekPEFTAdapter): |
| 93 | raise TypeError("DeepSeekV4 PEFT export requires DeepSeekV4StateDictAdapter") | 200 | raise TypeError("DeepSeekV4 PEFT export requires DeepSeekV4StateDictAdapter") |
| 94 | peft_state = adapter.to_peft(state_dict) | 201 | peft_state = adapter.to_peft(state_dict) |
| 95 | - peft_state = {name: value.contiguous() for name, value in peft_state.items()} | 202 | + # Gate/up adapters can share the same A tensor after splitting. |
| 203 | + # Copy only repeated views, leaving independent tensors in place. | ||
| 204 | + seen = set() | ||
| 205 | + for name, value in peft_state.items(): | ||
| 206 | + value = value.contiguous() | ||
| 207 | + address = (value.device, value.data_ptr()) | ||
| 208 | + if value.numel() and address in seen: | ||
| 209 | + value = value.clone() | ||
| 210 | + seen.add(address) | ||
| 211 | + peft_state[name] = value | ||
| 96 | self._finalize_peft_directory(checkpoint_id, adapter_config, peft_state) | 212 | self._finalize_peft_directory(checkpoint_id, adapter_config, peft_state) |
| 97 | except Exception as error: | 213 | except Exception as error: |
| 98 | status[0] = f"{type(error).__name__}: {error}" | 214 | status[0] = f"{type(error).__name__}: {error}" |
| @@ -133,6 +249,13 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 133 | def _validate_native_resume(self, saved_keys: set[str]) -> None: | 249 | def _validate_native_resume(self, saved_keys: set[str]) -> None: |
| 134 | if any(key.endswith(".w13_lora_b") for key in saved_keys): | 250 | if any(key.endswith(".w13_lora_b") for key in saved_keys): |
| 135 | raise ValueError("This checkpoint uses the unsupported historical w13_lora_b adapter format") | 251 | raise ValueError("This checkpoint uses the unsupported historical w13_lora_b adapter format") |
| 252 | + expected_adapters = {key for key in self.states[MODEL].state_dict() if is_lora_parameter(key)} | ||
| 253 | + missing_adapters = expected_adapters - saved_keys | ||
| 254 | + if missing_adapters: | ||
| 255 | + raise ValueError( | ||
| 256 | + "LoRA resume requires adapter tensors; load the base through initial_load_path. " | ||
| 257 | + f"Missing tensors: {sorted(missing_adapters)}" | ||
| 258 | + ) | ||
| 136 | 259 | ||
| 137 | def _load_checkpoint(self, states, checkpoint_id, *, from_hf: bool, from_quantized: bool) -> None: | 260 | def _load_checkpoint(self, states, checkpoint_id, *, from_hf: bool, from_quantized: bool) -> None: |
| 138 | if MODEL not in states: | 261 | if MODEL not in states: |
| @@ -151,11 +274,10 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 151 | self._validate_native_resume(saved_keys) | 274 | self._validate_native_resume(saved_keys) |
| 152 | model_state = states[MODEL].state_dict() | 275 | model_state = states[MODEL].state_dict() |
| 153 | model_buffer_keys = self._model_buffer_keys() | 276 | model_buffer_keys = self._model_buffer_keys() |
| 154 | - has_adapters = any(is_lora_parameter(key) for key in saved_keys) | ||
| 155 | has_base = all( | 277 | has_base = all( |
| 156 | key in saved_keys for key in model_state if not is_lora_parameter(key) and key not in model_buffer_keys | 278 | key in saved_keys for key in model_state if not is_lora_parameter(key) and key not in model_buffer_keys |
| 157 | ) | 279 | ) |
| 158 | - if initial_base or not has_adapters: | 280 | + if initial_base: |
| 159 | flat = { | 281 | flat = { |
| 160 | key: value | 282 | key: value |
| 161 | for key, value in self._flattened_model_states_sd(states).items() | 283 | for key, value in self._flattened_model_states_sd(states).items() |
| @@ -166,9 +288,6 @@ class DeepSeekV4PEFTCheckpointManager(NPUCheckpointManager): | |||
| 166 | else: | 288 | else: |
| 167 | if not self.initial_load_path: | 289 | if not self.initial_load_path: |
| 168 | raise ValueError("Loading an adapter-only DCP requires initial_load_path for the frozen base") | 290 | raise ValueError("Loading an adapter-only DCP requires initial_load_path for the frozen base") |
| 169 | - missing_adapters = {key for key in model_state if is_lora_parameter(key)} - saved_keys | ||
| 170 | - if missing_adapters: | ||
| 171 | - raise ValueError(f"Adapter checkpoint is missing LoRA tensors: {sorted(missing_adapters)}") | ||
| 172 | # Check both sources before either can change live weights. | 291 | # Check both sources before either can change live weights. |
| 173 | self._verify_load_source(self.initial_load_path) | 292 | self._verify_load_source(self.initial_load_path) |
| 174 | if self.initial_load_in_hf: | 293 | if self.initial_load_in_hf: |
| @@ -73,24 +73,20 @@ def _apply_compile_v4_1(model, *, compile_config: CompileConfig) -> None: | |||
| 73 | the graph (fullgraph=False) instead. | 73 | the graph (fullgraph=False) instead. |
| 74 | - The dispatcher reorder opt-in: aten argsort does not survive dynamo | 74 | - The dispatcher reorder opt-in: aten argsort does not survive dynamo |
| 75 | fake-eval under the spmd_types patch stack, so the traceable exact | 75 | fake-eval under the spmd_types patch stack, so the traceable exact |
| 76 | - stable formulation is swapped in for the compiled run only (eager | 76 | + stable formulation is bound to this model's dispatcher instances (eager |
| 77 | - keeps the upstream helper; the permutation is identical). | 77 | + models keep the upstream helper; the permutation is identical). |
| 78 | """ | 78 | """ |
| 79 | import logging | 79 | import logging |
| 80 | 80 | ||
| 81 | - import torch | ||
| 82 | - | ||
| 83 | logger = logging.getLogger(__name__) | 81 | logger = logging.getLogger(__name__) |
| 84 | 82 | ||
| 85 | configure_model_compile() | 83 | configure_model_compile() |
| 86 | 84 | ||
| 87 | # Traceable reorder opt-in for the compiled run (see the override module). | 85 | # Traceable reorder opt-in for the compiled run (see the override module). |
| 88 | from torchtitan_npu.override.common.token_dispatcher import ( | 86 | from torchtitan_npu.override.common.token_dispatcher import ( |
| 89 | - apply_compile_friendly_local_reorder, | 87 | + configure_dispatchers_for_compile, |
| 90 | ) | 88 | ) |
| 91 | 89 | ||
| 92 | - apply_compile_friendly_local_reorder() | ||
| 93 | - | ||
| 94 | # Force-load-balanced MoE routing (round-robin, --debug.moe-force-load-balance) | 90 | # Force-load-balanced MoE routing (round-robin, --debug.moe-force-load-balance) |
| 95 | # keeps the all_to_all split sizes constant (T*K/E per rank on every step), | 91 | # keeps the all_to_all split sizes constant (T*K/E per rank on every step), |
| 96 | # so inductor can trace the whole dispatcher inline with fullgraph=True. | 92 | # so inductor can trace the whole dispatcher inline with fullgraph=True. |
| @@ -102,25 +98,9 @@ def _apply_compile_v4_1(model, *, compile_config: CompileConfig) -> None: | |||
| 102 | routers = [m for m in model.modules() if hasattr(m, "_debug_force_load_balance")] | 98 | routers = [m for m in model.modules() if hasattr(m, "_debug_force_load_balance")] |
| 103 | force_balanced_moe = bool(routers) and all(m._debug_force_load_balance for m in routers) | 99 | force_balanced_moe = bool(routers) and all(m._debug_force_load_balance for m in routers) |
| 104 | fullgraph = compile_config.backend != "inductor" or force_balanced_moe | 100 | fullgraph = compile_config.backend != "inductor" or force_balanced_moe |
| 105 | - if compile_config.backend == "inductor": | 101 | + configure_dispatchers_for_compile( |
| 106 | - import torch._inductor.config | 102 | + model, eager_all_to_all=compile_config.backend == "inductor" and not force_balanced_moe |
| 107 | - | 103 | + ) |
| 108 | - # Skip the unbacked-SymInt runtime assertions (Eq(u32+..., T*K)) | ||
| 109 | - # that inductor derives from the tracing run's expert distribution. | ||
| 110 | - setattr(torch._inductor.config, "do_not_emit_runtime_assertions", True) # noqa: B010 | ||
| 111 | - if not force_balanced_moe: | ||
| 112 | - # The MoE communication (all_to_all_single with data-dependent | ||
| 113 | - # splits) runs eagerly: wrap the NPU dispatcher's dispatch/combine | ||
| 114 | - # so dynamo treats them as opaque and graph-breaks around them. | ||
| 115 | - # aot_eager keeps fullgraph=True and needs no wrapping. | ||
| 116 | - from torchtitan_npu.override.common.token_dispatcher import AscAllToAllTokenDispatcher | ||
| 117 | - | ||
| 118 | - AscAllToAllTokenDispatcher.dispatch = torch._dynamo.disable(recursive=True)( | ||
| 119 | - AscAllToAllTokenDispatcher.dispatch | ||
| 120 | - ) | ||
| 121 | - AscAllToAllTokenDispatcher.combine = torch._dynamo.disable(recursive=True)( | ||
| 122 | - AscAllToAllTokenDispatcher.combine | ||
| 123 | - ) | ||
| 124 | 104 | ||
| 125 | for layer_id, transformer_block in model.layers.named_children(): | 105 | for layer_id, transformer_block in model.layers.named_children(): |
| 126 | transformer_block.compile(backend=compile_config.backend, fullgraph=fullgraph, dynamic=False) | 106 | transformer_block.compile(backend=compile_config.backend, fullgraph=fullgraph, dynamic=False) |
| @@ -41,6 +41,7 @@ fp32-score-multiply + bf16 ``scatter_add``. | |||
| 41 | """ | 41 | """ |
| 42 | 42 | ||
| 43 | from dataclasses import dataclass | 43 | from dataclasses import dataclass |
| 44 | +from types import MethodType | ||
| 44 | from typing import TYPE_CHECKING, ClassVar, cast | 45 | from typing import TYPE_CHECKING, ClassVar, cast |
| 45 | 46 | ||
| 46 | import spmd_types as spmd | 47 | import spmd_types as spmd |
| @@ -114,15 +115,20 @@ def _compile_friendly_local_reorder( | |||
| 114 | ) | 115 | ) |
| 115 | 116 | ||
| 116 | 117 | ||
| 117 | -def apply_compile_friendly_local_reorder() -> None: | 118 | +def configure_dispatchers_for_compile(model: torch.nn.Module, *, eager_all_to_all: bool) -> None: |
| 118 | - """Opt the dispatchers into the traceable stable reorder (compile only). | 119 | + """Opt this model's dispatchers into the compile policy. |
| 119 | 120 | ||
| 120 | Called by the V4.1 compile assembly (models/deepseek_v4_1/parallelize) | 121 | Called by the V4.1 compile assembly (models/deepseek_v4_1/parallelize) |
| 121 | - when torch.compile is enabled; eager runs keep the upstream | 122 | + when torch.compile is enabled; eager models keep the upstream |
| 122 | - ``torch.argsort(stable=True)`` helper. | 123 | + ``torch.argsort(stable=True)`` helper. Data-dependent EP communication |
| 124 | + stays eager when requested. | ||
| 123 | """ | 125 | """ |
| 124 | - LocalTokenDispatcher._local_reorder = _compile_friendly_local_reorder | 126 | + for dispatcher in model.modules(): |
| 125 | - AllToAllTokenDispatcher._local_reorder = _compile_friendly_local_reorder | 127 | + if isinstance(dispatcher, (LocalTokenDispatcher, AllToAllTokenDispatcher)): |
| 128 | + dispatcher._local_reorder = MethodType(_compile_friendly_local_reorder, dispatcher) | ||
| 129 | + if eager_all_to_all and isinstance(dispatcher, AllToAllTokenDispatcher) and dispatcher.ep_mesh is not None: | ||
| 130 | + for name in ("dispatch", "combine"): | ||
| 131 | + setattr(dispatcher, name, torch.compiler.disable(getattr(dispatcher, name))) | ||
| 126 | 132 | ||
| 127 | 133 | ||
| 128 | class AscAllToAllTokenDispatcher(AllToAllTokenDispatcher): | 134 | class AscAllToAllTokenDispatcher(AllToAllTokenDispatcher): |


The current tests/integration_tests/lora_config.py still imports DeepSeekV4LoRAConverter at line 20, while the implementation now exposes deepseek_v4_lora_transform(). The harness also uses config.checkpoint, config.optimizer, self.model_parts, model_spec.model.lora, and the historical inner_experts.w1_lora_b/w3_lora_b layout. v41_lora_config.py imports this LoRATrainer, so it inherits the stale entry dependency.
Could the V4 and V4.1 integration harnesses be migrated to the current engine/optim/checkpointer and grouped-LoRA contracts, then actually execute training, native save, and fresh-process resume? A unit-test pass count alone does not establish that these integration entries work. This is an existing dev_0.4.0 migration issue, not a regression introduced by this PR; please track it as a companion integration fix.