Merged
[feat] adapt to torchtitan commit 'edbfc8' #1171
[feat] adapt to torchtitan commit 'edbfc8' #1171
Merged
1Fire4Add on Nov 3
Total: 299 files changed+9102-9723
@@ -0,0 +1,307 @@
1+# TorchTitan-NPU 升级计划:`dc3985` → `ebdfc8`
2+ 
titan-npu-reviewertitan-npu-reviewer

当前PR改动代码超过1k行,建议拆分PR后合入。

问题编号:R1171-001

审查版本:128a188a285ab15957e7df7ce0dcaee9ac2e19a1

likedislike
1Fire4
1Fire4
Nov 3 Comments:
likedislike

缺少精度验证结果

本 PR 修改了可能影响数值结果的代码路径,但 PR 描述中没有看到精度验证结果及精度是否正常的说明。

请参考 精度对齐开发指南 完成精度验证, 并将验证结果(对齐目标、指标数值、是否满足阈值)写入 PR 描述。

问题编号:R1171-002

审查版本:128a188a285ab15957e7df7ce0dcaee9ac2e19a1

likedislike
3+## 1. 结论与目标
4+ 
5+**这是一次模型接口、训练生命周期和参数布局的整体迁移,不能通过修改依赖 SHA、批量替换 import 完成。**
6+ 
7+已确认的分析基线:
8+ 
9+| 项目 | 版本 |
10+|---|---|
11+| 当前 NPU 插件 | `180c09245c1599802635ccc630175a9b7462406e` |
12+| 当前适配上游 | `dc3985ad4912f67f71d5a125f2fdf40144ec8354` |
13+| 目标上游 | `ebdfc8c2a24d89d89c99c0ef96ed8ac149864175` |
14+| 上游差异 | 215 个提交,764 个文件,新增 66,782 行、删除 36,396 行 |
15+ 
16+静态扫描已发现:插件生产代码有 **98 处 import 引用了目标版本已删除或搬迁的 16 个模块**。这个数字还不包含同模块内的符号删除、参数变化和运行语义变化。
17+ 
18+本计划采用已确认的边界:
19+ 
20+- 仅支持 `ebdfc8`,不保留旧上游兼容分支。
21+- 现有 NPU 模型、训练功能和扩展全部纳入迁移;新增上游功能不自动扩大支持范围。
22+- 按新标准保存和恢复 checkpoint,**不兼容旧原生 DCP、旧 optimizer/EMA 状态或旧内部 LoRA 格式,不提供历史转换工具**。
23+- 保留外部 HF 权重加载、PEFT 导出,以及新格式的保存与续训能力。
24+- 仅修改插件仓,不修改上游 checkout。
25+- 阶段一至三已完成;阶段四、五的本轮范围与验证边界见第 7 节。
26+ 
27+## 2. 上游变化及 NPU 影响
28+ 
29+以下按最终行为归并这 215 个提交,不把文件搬迁和修复提交分别当作独立适配任务。
30+ 
31+| 领域 | 上游主要变化 | NPU 处置 |
32+|---|---|---|
33+| 模型配置与生命周期 | `#4810` 删除 `ModelSpec`,registry 直接返回模型 Config;模型自身负责 parallelize、pipeline、optimizer hooks、state-dict adapter | **必须迁移**所有本地模型 registry、recipe、模型方法和 override FQN |
34+| 训练引擎 | `#4773` 抽出 `TrainingEngine`;Trainer 保留数据、验证和报告职责 | **必须重接** TrainerEx、SDC、anticipatory routing、CPU offload、梯度裁剪、GraphTrainer、TorchFT |
35+| 配置转换 | `#4322/#4648/#4684` 引入统一 `ModelConfigTransform`,CP、LoRA、量化转换调整归属 | 将 NPU 转换接入新模型配置树,明确转换顺序和冲突,不再操作 `model_spec.model` |
36+| 分布式/SPMD | `#4419/#4905/#4960` 删除旧 activation DTensor 路线,改用 `ParallelismContext`、`local_spmd`;mesh 轴与函数签名改变 | **必须重写语义接入**,不能只把 `ParallelDims` 改名 |
37+| Linear/FFN/MoE | `#4535/#4808/#4871/#4872` 默认融合 gate/up;删除 `GroupedExperts`,采用 `Linear/GroupedLinear` 的 `w13/w2` | 影响 NPU GMM、SwiGLU、sharding、Muon、量化、LoRA 和 HF 权重映射,是核心工作量 |
38+| TP 与专家通信 | `#4703/#4704/#4878/#4794` 线性投影显式管理通信;MoE 显式处理 token 布局,废弃纯 TP routed experts | NPU kernel 只替换本地计算,保留外层通信;拒绝不满足新约束的旧配置 |
39+| Router 与辅助损失 | `#4484/#4631/#4594/#3864` 引入 FP32 router backward、迁移分组路由、支持 padding mask、合入 AuxLoss | 迁移 router 配置和继承关系,统一 AuxLoss;计算变化单独做数值验收 |
40+| Attention、CP、MTP | InnerAttention 命名统一;`#4617` 分离输入和 metadata 分片;`#4544/#4451` 支持 MTP+CP/chunked loss | 保留本地文档级 metadata、CP carry、压缩注意力和 LI loss,接入新协议 |
41+| DSV4 上游实现 | `#4855/#4856/#4858` 使用 Attention Gym gather/indexer;`#4879` 拒绝 packed documents;`#4932` 修正 compressed KV 位置 | **不能整体替换本地 DSV4/V4.1 实现**:目标上游尚不等价覆盖本地 packed/CP/indexer 训练能力 |
42+| 优化器、EMA、DistMuon | `#4904` 引入类型化 optimizer 配置;`#3985` 合入 EMA;`#4811/#4840` 调整 Muon 布局;`#4615` 修复 BF16 状态恢复 | 迁移 HostSparse、Virtual/Swap/CPU-offload optimizer、Muon dedup 和新 EMA 接入 |
43+| 数据、SFT、验证 | batch 改为 `TrainingMicrobatch`;padding、长文档拆分和恢复状态变化;新增多轮 SFT;验证增加空数据保护 | 迁移本地 loader、视觉数据、调度缓存;单独检查数据语义变化 |
44+| Checkpoint | `#4190/#4191/#4528` 统一 load 后端、完善 HF consolidation;新 EMA 状态结构 | 迁移 DCP load hook、hash、PEFT、量化读取和导出;默认继续使用 DCP |
45+| AC 与编译 | `#4497` 引入 torch_remat/RegionAC;FullAC 默认 early-stop;`#4895` 删除常规逐 block compile | 保全既有 NPU FullAC/SelectiveAC 和模型编译功能;RegionAC 不纳入默认支持 |
46+| GraphTrainer | `#4666/#4884/#4952` 统一 GraphRuntime,收敛到 AOT tracing,删除 graph-based EP chunking | **必须迁移** NPU auto-overlap、runtime context、全图校准和 CV parallel;使用 eager chunking |
47+| CUDA graphs | 新增梯度累积 capture、graph-owned gradients、独立 optimizer capture、looped PP | 属于 CUDA 能力;NPU 不自动启用,验证不会进入 CUDA 专属执行分支 |
48+| 模型扩展与工程设施 | Qwen3.5 tying/多模态修复;新增 Qwen3.6 registry;Kimi K3 TP/PP/packing;RL 搬迁与扩展;日志和 CI 重组 | Qwen 现有路径回归;公共修复继承;新模型/RL 专属功能另列后续项,不复制 GPU CI/golden |
49+ 
50+关键接口依据见 [模型生命周期](/home/wdy/project/train/tt-lite/adapt_tt_ebdfc8/torchtitan/torchtitan/protocols/model.py:105)、[训练引擎配置](/home/wdy/project/train/tt-lite/adapt_tt_ebdfc8/torchtitan/torchtitan/training_engine.py:110)、[新专家结构](/home/wdy/project/train/tt-lite/adapt_tt_ebdfc8/torchtitan/torchtitan/models/common/moe.py:60)。
51+ 
52+## 3. 实施顺序与具体方案
53+ 
54+### 阶段一:固定依赖与新配置契约
55+ 
56+**目标:建立唯一的新版本配置体系,清除启动阻塞。**
57+ 
58+- 同步更新 `requirements.txt`、`pyproject.toml` 中的完整上游 SHA;沿用现有 CI revision helper,不再增加一套版本来源。
59+- 同步日志、profiler、optimizer、LoRA、quantization、CP、graph 等模块路径;清理对已删除方法和模块的自动导入。
60+- 配置整体迁移:
61+ 
62+| 旧接口 | 新接口 |
63+|---|---|
64+| `model_spec.model` | `model` |
65+| `model_spec.parallelize_fn/pipelining_fn` | 模型方法 |
66+| `model_spec.state_dict_adapter` | `state_dict_adapter_cls` |
67+| `optimizer`、`lr_scheduler` | `optim.optimizer`、`optim.lr_scheduler` |
68+| `training.max_norm` | `optim.max_norm` |
69+| 旧 EMA 配置 | `optim.ema` |
70+| `checkpoint` | `checkpointer`,以 `None` 禁用 |
71+| `parallelism.spmd_backend` | 删除,统一新 SPMD 路线 |
72+| `comm.mode` | `comm.backend` |
73+| `module_fqns_per_model_part` | `pipeline_parallel_module_fqns_per_model_part` |
74+| `compile.enable`、`compile.components=model` | 新的 loss 编译配置与独立 NPU 模型编译配置 |
75+ 
76+- 更新配置 converter,使其能转换嵌套的 `optim` 等组件;保留 recipe 的专用类型和配置值,避免字段筛选时静默丢失。
77+- NPU 配置转换必须在模型构建前完成;所有 override 从 `model_spec.model...` 迁到 `model...`,并验证实际命中对象。
78+- 固定 `torch_remat` 为目标上游指定的 `d302699b1c58f83fa2c7b03bc2593967e9530335`,补齐 `renderers==0.1.11` 等依赖。
79+ 
80+**依赖特例:Attention Gym。** 上游精确要求 `0.0.14`,插件要求 `0.0.16`,这是已有的依赖冲突。计划保留插件当前需要的 `0.0.16`,沿用受控的 `--no-deps` 安装方式,显式安装运行依赖并验证相关 API;同步修正安装文档,不能继续声称普通 pip 解析无冲突。`0.0.16` 与新上游调用的运行兼容性作为第一阶段验收门槛。
81+ 
82+**阶段出口:** 包可导入,全部现有 recipe 和显式 override 可构造;旧配置报出明确错误,不建立旧接口别名层。
83+ 
84+#### 阶段一实施小结(2026-10-31)
85+ 
86+已固定目标上游 `ebdfc8` 并完成新配置契约;按确认后的范围,提前迁移了整包导入、recipe 构造和启动脚本所需的模型接口、递归 `_parallelize`、HF/PEFT 加载及 override。NPU 模型编译配置最终采用 `compile.model`;可选 `compile`、`checkpointer` 保留 `None` 语义,模型单独编译通过显式空 `components` 保持原行为。
87+ 
88+- **配置验收:** 47 个 recipe、1 个模板共 **147/147** 项通过;**35/35** 组实际启动参数通过 CLI、token 预算、模型更新和真实 override 检查。
89+- **局部回归:** 集中测试 **180 项通过,0 失败、0 跳过**;另有真实 HF/PEFT 加载恢复 **15 项**、SwiGLU 与 dispatcher 组合 **14 项**通过。验证在指定容器和 1015 CANN 环境进行,结果不代表 NPU 训练通过。
90+- **Lint 状态:** 完整 pre-commit 尚未通过,共享旧上游路径下有 **278 条类型错误**;显式指向 `ebdfc8` 后有 **25 条错误、1 条警告**,其中环境/API 版本问题 9 条、运行迁移问题 9 条、其他静态解析与类型问题 7 条。其他适用检查通过,OAT 因无暂存文件未实际扫描。
91+- **剩余范围:** CV 配置与注册通过,但目标上游已删除其依赖的 graph chunking,运行入口明确拒绝尚未迁移的路径。Graph、anticipatory routing、TorchFT 恢复、Qwen CP 等运行适配仍需后续完成;本轮未验证 NPU 训练、精度、收敛或性能,不能据此宣布整体升级完成。
92+- **交付状态:** 上游源码未修改,插件改动未提交或推送;临时验证目录已清理,无残留任务进程,持久依赖版本及入口文件哈希未改变。
93+ 
94+完整结果见[阶段一报告](../../../../test_reports/stage1-ebdfc8/REPORT.md),最新证据以[结果索引](../../../../test_reports/stage1-ebdfc8/LATEST.json)为准。上述证据保存在本地,未纳入版本控制。
95+ 
96+### 阶段二:迁移模型结构与 NPU 计算接口
97+ 
98+**目标:采用新参数标准,同时保持 NPU 算子的计算含义。**
99+ 
100+- Dense FFN 采用 `w13:[2,F,D]`;专家采用 `w13:[E,2,F,D]`、`w2:[E,D,F]`。
101+- NPU Linear、LoRA 和量化实现接入 `_linear`;NPU GMM 接入 `_grouped_mm(input_RI, weight_EOI, offsets_E)`。TP/SP 通信由上游外层负责,避免漏通信或重复通信。
102+- SwiGLU/clamp 接入 activation 配置;移除 `GroupedExperts`、`inner_experts` 和旧参数名依赖。
103+- 保留本地 DSV 路由分数在 **W2 前相乘并回到 BF16** 的语义;dispatcher combine 不得再次乘分数。上游 W2 后的 `output_postprocess` 不能替代此行为。
104+- Router 改用类型化 activation 配置;DSV3.2 继承新的分组路由实现,V4/V4.1 删除对通用 router 已移除字段的访问。
105+- 全部 transformer/MTP 路径传递真实 `padding_mask`;padding 不计入负载统计和辅助损失,但不能破坏 dispatch map。
106+- 统一使用上游 AuxLoss,迁移 DSV3.2 indexer loss、metrics 和 anticipatory 快照,避免两套分母与累加器并存。
107+- 更新 HF adapter、Muon 参数筛选、初始化、量化白名单和 LoRA target,确保它们共同使用新 FQN。
108+ 
109+新分组线性层的存储与计算视图见 [GroupedLinear](/home/wdy/project/train/tt-lite/adapt_tt_ebdfc8/torchtitan/torchtitan/models/common/linear.py:232)。
110+ 
111+**阶段出口:** Dense/MoE 局部前反向、参数映射、override 命中及新 HF roundtrip 通过。
112+ 
113+### 阶段三:迁移训练引擎与数据协议
114+ 
115+**目标:让既有 NPU 功能在新的实际执行位置生效。**
116+ 
117+- 通过 `Trainer.engine_cls` 接入 NPU TrainingEngine;Trainer 保留数据调度和报告,Engine 接管模型执行、优化、checkpoint 和清理。
118+- 将 HF32、CPU-offload 初始化、pinned pool、SDC、anticipatory 微批次回调迁到对应生命周期。
119+- 删除对旧 `Trainer.train_step` 的源码字符串注入和函数 globals 替换;梯度裁剪放到 NPU `Optim` 的更新边界,包含 Engram sparse gradient 和 offload 参数。
120+- 本地 loader、视觉 loader 和缓存改为返回 `TrainingMicrobatch/TokenizedTrainingMicrobatch`,维护 labels、positions、padding mask、有效 token 数和 loss 参数。
121+- SFT 的 prompt loss mask 与 padding mask 分开处理,不能把 `labels == IGNORE_INDEX` 当作 padding。
122+- CANNProfiler、metrics、SDC 和 close 路径跟随新状态 owner;正常结束、异常结束和重复构造均释放自身资源。
123+ 
124+当前旧 patch 在导入时直接读取被移除的方法,见 [旧 Trainer 注入](/home/wdy/project/train/tt-lite/adapt_tt_ebdfc8/torchtitan-npu/torchtitan_npu/patches/torchtitan/trainer.py:28)。仅增加属性转发无法修复这类生命周期变化。
125+ 
126+**阶段出口:** 单卡 eager 训练、梯度累积、数据恢复、裁剪与资源清理通过。
127+ 
128+### 阶段四:迁移 SPMD、FSDP、CP 与 PP
129+ 
130+**目标:保留现有受支持并行组合,采用新上游分片规则。**
131+ 
132+- 使用 `ParallelismContext`、`DistributedTopology`、`activate_spmd()`;专用 HCCL EP group wrapper 接受新的 `dense_sp_enabled` 等参数。
133+- 数据与指标使用 `dp` mesh;dense/expert FSDP 分别经上游 mesh resolver 获取。不能机械地把旧 `fsdp` 字符串替换为 `dp_shard`。
134+- `LocalMapConfig` 改为 `local_spmd` 和明确的输入、输出 sharding;验证梯度 placement。
135+- 重建 NPU FSDP 扩展,只保留 Engram `ignored_params`、CPU offload、FP32 policy 等必要差异,避免旧完整实现覆盖新 stacked-weight 和 multimodal 修复。
136+- 纳入目标提交 `#4949`:专家数量足够时保留专家维 `Shard(0)`,其他情况使用正确的矩阵行分片;额外覆盖 EP=1 的 eager/graph 一致性。
137+- CP 改用新 load-balancer 配置、permutation 和 `shard_tensors`;保留 NPU geometry-keyed metadata、doc-chunk、不同压缩比和 carry exchange。
138+- tokens、labels、positions、padding mask、MTP 各深度使用同一文档布局;metadata 只转换一次。
139+- PP 接入模型方法及新 first/last-stage module 配置,保留现有多模态分段和微批次语义。
140+ 
141+**不能直接删除 metadata patch 组。** 插件已回移部分晚于目标提交的 metadata 协议,`ebdfc8` 尚未完整覆盖。此次只删除旧 `cp_shard` 接口包装,保留目标上游缺少的实际能力。
142+ 
143+**阶段出口:** 现有 DP/HSDP、TP/SP、EP、CP、PP 组合通过真实 NPU 测试;原先明确不支持的组合继续明确拒绝。
144+ 
145+### 阶段五:迁移优化器、checkpoint、LoRA 和低精度
146+ 
147+**优化器与 EMA**
148+ 
149+- 用类型化 optimizer configs 替代 `ParamGroupConfig` 和字符串 factory;保证所有可训练参数按 first-match 规则恰好归属一个 optimizer。
150+- 迁移 HostSparse、Virtual、Swap、CPU-offload container,并接受新的构造参数。
151+- DistMuon 使用新的矩阵视图和 `lr_reference_shape`;replica dedup 接入新构造入口,保留 owner-only state 与广播顺序。
152+- 复用上游 EMA,删除整套 EMA Trainer/checkpointer backport;仅保留 NPU stream/event/offload 适配。目标上游 EMA offload 仍直接使用 CUDA,见 [EMA offload](/home/wdy/project/train/tt-lite/adapt_tt_ebdfc8/torchtitan/torchtitan/components/optim/ema.py:326)。
153+ 
154+**Checkpoint**
155+ 
156+- 按新 `_load_checkpoint(states, checkpoint_id, *, from_hf, from_quantized)` 接入 hash、量化 reader 和 PEFT 分层加载,区分 live state 与 flattened state。
157+- 保留默认 DCP、同步写入的 NPU 参数及异步完成后的 hash 发布顺序;导出工具改读新 EMA 状态。
158+- 使用新标准验证 model-only、full resume、EMA、adapter-only 和量化状态;旧内部格式不静默 partial-load。
159+- 不默认切换到 `TorchCheckpointingManager`:目标版本支持 HF 最终导出,但其 HF load 仍有限制。
160+ 
161+**LoRA 与量化**
162+ 
163+- 使用新 `LoRATransform` 和 Linear/GroupedLinear handler,采用新 `w13` 参数化。
164+- 保留插件的 HF base 初始化、adapter-only save/resume 和 PEFT export;上游新 LoRA 仍未完整提供这些功能。
165+- TorchAO-NPU 改接新 Linear/GroupedLinear,逐一保全 MXFP8、HiF8、block-FP8、MXFP4-QAT、FSDP prequantize、KV/LI 量化。
166+- 不将 stack axis 当作矩阵行,也不把 LoRA 参数误纳入原基础权重量化规则。
167+ 
168+**阶段出口:** 新格式保存后重启,下一步权重、optimizer state、LR、EMA 和步数正确;HF/PEFT 导出能够实际重新读取。
169+ 
170+### 阶段六:迁移 AC、模型编译与 GraphTrainer
171+ 
172+**常规训练**
173+ 
174+- 保留 FullAC/SelectiveAC,继承上游 early-stop 和 effect 保护。
175+- 检查重算期间 router counter、AuxLoss、RoPE cache、Engram 状态只更新一次,DeepEP handle 正常释放。
176+- 上游 `CompileConfig` 现在只允许 loss component,仍保留 backend 字段。既有 NPU 模型编译已在阶段一迁到显式 `compile.model` 配方配置,保留现有编译参数和 A3 CP eager 限制,不复活旧上游 `apply_compile`。
177+ 
178+**GraphTrainer**
179+ 
180+- 迁到 `GraphTrainingEngine` 与 GraphRuntime,重新接入 trace/runtime context、全图校准、NPU pass registry。
181+- 删除 graph-based EP chunking,统一 eager chunking;更新 launcher 中旧 strategy 和执行模式配置。
182+- auto-overlap 放在 eager chunk metadata 已产生、FSDP bucketing 完成后的调度位置,不再依赖已删除的 concretization pass。
183+- CV parallel 单独迁到新的 graph builder/runtime 接口;不能只修默认 GraphTrainer 就宣称该能力已保全。
184+- 校准不得改变模型参数、grad、buffer、随机状态或训练进度。
185+- NPU 默认关闭 CUDA graph capture;新增 WGrad fusion、RegionAC 等优化不混入基础兼容性验收。
186+ 
187+**阶段出口:** eager 与 graph 的现有训练组合、梯度累积、EP overlap、校准和 CV parallel 均有独立结果。
188+ 
189+### 阶段七:迁移 TorchFT、多模态并清理补丁
190+ 
191+- TorchFT 接入新的 FaultTolerantTrainingEngine,重建明确的 NPU engine 构造入口;不继续依赖旧 Trainer 多继承关系。
192+- 保留 HCCL 恢复、snapshot/rollback 和事务顺序:跨副本指标 collective 在投票前完成,失败尝试不推进 LR、step 或数据位置。
193+- 保持现有 TorchFT 支持边界,不扩展 TP/CP/PP。
194+- Qwen3.5 继承小模型 embedding tying,验证共享参数身份;检查不同 rank 混合 text/image/video 时的 FSDP collective 顺序。
195+- GDN 覆盖末尾重复 offsets、空 padding segment 和文档边界;不把上游 Ulysses 新增当作 GDN CP 已支持。
196+- 当前名为 Qwen3.6 的 launcher 实际调用 Qwen3.5 recipe:此次保持其实际模型行为并修正文档,不静默切换到新上游 Qwen3.6 registry。
197+ 
198+补丁按以下结果处置:
199+ 
200+| 处置 | 内容 |
201+|---|---|
202+| 删除已吸收实现 | AuxLoss 重复实现、EMA 整类 backport、DistMuon 非 CUDA storage 校验补丁、EP ready-node 去重,以及已吸收的 TorchFT 修复 |
203+| 随旧功能删除 | graph EP chunk concretization、shape-live-out、旧 forward-accumulation 补丁及专属入口 |
204+| 保留并重接 | metadata/decoder/MTP、router score 前置乘法、Muon replica dedup、EP shape-query、recompute functionalization、chunked-loss NPU 差异 |
205+| 不随此次升级删除 | torch_npu runtime patch、针对 PyTorch 的 filesystem mmap patch |
206+| 作为既有债务处理 | Qwen 旧 2D MRoPE patch;目标上游已具有 folded/video 行为,回归通过后退役 |
207+ 
208+## 4. 验证计划
209+ 
210+### 分层验证矩阵
211+ 
212+| 层级 | 必须覆盖 | 通过条件 |
213+|---|---|---|
214+| 安装与配置 | 固定 SHA、运行依赖、默认 import、所有现有 recipe/override、可选组件 | 无过期模块引用;配置字段不丢失;可选组件不阻断默认启动 |
215+| CPU 行为 | 配置转换、参数归属、FQN、HF roundtrip、LoRA trainable 集合、tying、microbatch、metadata permutation | 验证实际行为,不以符号存在或 mock 导入替代 |
216+| NPU 算子 | dense/grouped W13、SwiGLU clamp、pre-W2 score、router、packed attention、GDN | 前向与关键梯度满足相应数值标准 |
217+| 模型训练 | DSV3.2、V4、V4.1 文本/视觉、Qwen3.5 dense/MoE、现有 Qwen3.6 launcher 的实际配方 | 每条既有能力有明确结果;基线未验证项单独标记 |
218+| 并行 | 当前支持的 DP/HSDP、TP/SP、EP、CP、PP 组合,CPU offload、Engram | 无 collective 次序错误;参数与梯度 placement 正确 |
219+| Graph/AC | eager、FullAC、SelectiveAC、GraphTrainer;累积 1/>1、overlap、CV、校准 | 状态更新次数正确,校准无训练副作用,无 handle/显存持续增长 |
220+| 保存与恢复 | 新 DCP 同步/异步、EMA、AdamW/Muon、HostSparse、LoRA、量化、hash | 重启后的下一步与连续运行一致;坏 hash 明确拒绝 |
221+| HF/PEFT 导出 | text-only、多模态、MTP 开关、EP、多 rank、未加载的可选 key | safetensors 实际重开成功,index 与张量集合正确,逐张量比较 |
222+| TorchFT | 成功提交、失败回滚、重试、rank 重入、数据与 checkpoint 步数 | 失败不推进状态,恢复后事务与 collective 顺序正确 |
223+ 
224+### 数值验收规则
225+ 
226+- 使用相同外部 HF 权重、固定随机性和同一保存的 microbatch 输入比较;无需恢复旧 DCP。
227+- 纯接口、metadata 或存储重构:要求未截断的逐步 `loss`、`grad_norm` 比特一致。
228+- fused GEMM、router FP32 backward、embedding tying 等计算变化:与对应参考实现比较,并进行不少于 **100 step** 的代表性训练;不能把变化混入「纯重构」后放宽判据。
229+- 数值近似遵循仓内标准:logits 的 `MEAN_AE/MEAN_RE ≤ 0.02`、`COS ≥ 0.9999`;loss/grad_norm 的 `MEAN_AE ≤ 0.02`、`MAX_RE/MEAN_RE ≤ 0.005`,且无 NaN/Inf。
230+- 不使用 `deterministic_warn_only`;stdout 四舍五入结果不作为比特一致证据。
231+- 数据 packing 行为变化另验,避免把不同输入造成的 loss 差异归因于模型迁移。
232+- 不复制上游 GPU golden 作为 NPU 正确性证据,不把 FakePG 或单卡导出结果外推为多卡训练通过。
233+ 
234+### 本机与服务器执行约束
235+ 
236+- 本机完整 lint 使用约定的 `torchnpu-x86-build` 环境和完整 pre-commit 命令。
237+- 保持约定的 `/tmp/torchtitan` 指向;另对当前目录的 `ebdfc8` 源码执行明确 search-path 的类型检查,报告实际解析的上游 SHA,避免检查到另一份 checkout。
238+- CPU 产品 UT 与 tooling 自测分别报告;完整 lint 只有全部 hook 通过才能标为通过。
239+- 真正执行远程验证前再确认服务器,默认容器按现有约定;先检查 NPU 占用,记录具体命令、环境与代码版本,测试后清理临时资源。
240+ 
241+## 5. 交付与完成标准
242+ 
243+实施按上述七阶段形成可独立审查的提交组,全部完成后再将升级视为可交付。最终交付包括:
244+ 
245+- 统一固定到 `ebdfc8` 的插件代码、依赖、CI、recipe 和 launcher。
246+- 一份上游变化处置表:每项标明「已迁移、直接继承、补丁退役、新增功能暂不支持」。
247+- 新配置和 checkpoint 的升级说明,明确旧内部格式废弃。
248+- 各模型与扩展的实际支持矩阵,区分已验证能力、原有迁移债务和本次新增失败。
249+- CPU、NPU、数值、保存恢复和 TorchFT/Graph 专项记录,注明未执行项与限制。
250+ 
251+**最终验收重点是:按新上游标准恢复现有 NPU 功能,并证明它们在新执行路径上确实生效。仅包能导入、单个 debug 模型跑通或局部测试通过,都不足以宣布升级完成。**
252+ 
253+## 6. 审查后待完成项(2026-11-02)
254+ 
255+以下两项基于插件提交 `4671d46`、`de312d5` 的审查,状态均为「待完成」。本轮仅修正 decoder FSDP 分片规则,不修改量化或 TorchFT 实现;后续适配 v0.4.0 时继续处理。
256+ 
257+### 6.1 Shared-expert W13 量化白名单
258+ 
259+- **现状与影响:** `extensions/adaptor/torchao/configs/deepseek_v4.py` 的 `_DENSE` 仍使用 `shared_experts.w1/w3`,模型已经采用融合的 `shared_experts.w13`。V4.1 复用该白名单,导致两种模型的 shared gate/up 投影被量化 recipe 和默认 FSDP prequantize 白名单遗漏。
260+- **处理方向:** 将目标迁到 `w13/w2`,同时核对实际模型配置树、量化转换器和 prequantize 过滤结果。不得仅更新字符串后就宣称量化路径已验证。
261+- **完成条件:** `all_mxfp8`、`all_hif8`、`mix`、`all_block_fp8` 的转换结果实际包含预期 shared-expert 投影;默认 prequantize 目标与 recipe 一致;融合 W13 的 shape、dtype、前向和反向经过相应 NPU 验证。
262+- **代码依据:** [V4 量化配置](../../../../torchtitan_npu/extensions/adaptor/torchao/configs/deepseek_v4.py)、[V4.1 量化配置](../../../../torchtitan_npu/extensions/adaptor/torchao/configs/deepseek_v4_1.py)。
263+ 
264+### 6.2 TorchFT 训练生命周期迁移
265+ 
266+- **现状与影响:** `FaultTolerantTrainerEx` 仍通过旧多继承结构使用普通 NPU engine,并访问旧 Trainer 的 `ft_manager`、`model_parts`、`lr_schedulers`。本地训练循环仍消费 tuple batch 和旧配置字段,尚未接入 `FaultTolerantTrainingEngine`。配置可构造不代表该路径可运行。
267+- **处理方向:** 在恢复运行支持前增加明确的未迁移入口检查;随后围绕目标版本的 FT engine 接入 NPU/HCCL 恢复,迁移状态 owner 与 `TrainingMicrobatch`,删除旧训练循环。保持跨副本指标 collective 先于提交投票、失败尝试不推进训练状态的原有约束。
268+- **完成条件:** 实际创建 FT engine;正常 step、失败回滚、重试和 rank 重入均进入新路径;验证失败尝试不推进 optimizer、LR、训练步数或数据位置,并验证 checkpoint 恢复。恢复被延期的 TorchFT 测试收集后,执行真实 NPU/HCCL 验证。
269+- **代码依据:** [TorchFT trainer](../../../../torchtitan_npu/extensions/torchtitan/experiments/torchft/trainer.py)、[恢复逻辑](../../../../torchtitan_npu/extensions/torchtitan/experiments/torchft/recovery/step_recovery.py)、[测试延期清单](../../../../tests/unit_tests/conftest.py)。
270+ 
271+ 
272+## 7. 阶段四、五实施范围(2026-11-02)
273+ 
274+本轮继续固定 `ebdfc8`,不切换到 v0.4.0。Checkpoint、LoRA 和低精度由后续专项处理。按本轮确认,NPU 验证只保留 DSV4/V4.1 的基础 eager;EMA、CPU offload、Muon、TP/CP、Host Engram 和 PP 不列入本轮运行验收。阶段四、五原有完整出口仍未达成,不能将基础 eager 冒烟扩大为全部并行和优化器组合已通过。
275+ 
276+### 7.1 已实施的适配
277+ 
278+- **MoE 与 FSDP:** 保留上游分片配置、mesh resolver 和 FSDP 生命周期。`ebdfc8` 的 EP=1 routed experts 未声明权重 SPMD 状态,新的 FSDP `dp_mesh_dims` 入口无法消费普通权重;公共模型配置层仅补充 `w13/w2` 的 dense replicated 声明。上游补齐后可删除该包装。
279+- **多模态 FSDP:** 删除本地视觉 encoder 的重复 helper,调用上游 `apply_fsdp_to_multimodal_encoder`,传递 `dp_mesh_dims`。本轮未验证视觉训练。
280+- **分布式初始化:** 当前 torch_npu 配套 PyTorch 缺少 `pipeline_per_edge_p2p`。由 `extensions/torchtitan/distributed/utils.py` 单独拥有 `init_distributed` 适配,先于 trainer 激活;具备能力的 runtime 直接委托上游,旧 runtime 仅保留 PP=1 初始化并明确拒绝 PP。适配没有创建虚假的 runtime 配置字段。更新配套 runtime 后可删除降级分支。
281+- **类型化优化器:** Virtual/Swap/CPU-offload container 接受原生构造参数;CPU-offload 通过 typed optimizer config 的 `build` 接口接入上游 first-match 参数归属循环,保留 HostSparse 独立 owner。
282+- **DistMuon:** CPU-offload 更新改用 `lr_reference_shape`;两个模型复用公共 expert layout,显式声明 EP 与 EDP 同维分片次序。
283+- **EMA:** 复用上游调度、参数/缓冲区管理和状态结构,仅替换设备 stream/event 与 CPU offload 更新;配置转换按最近注册的 Trainer 基类选择适配器,保留具体 recipe owner。后者修复 NPU recipe 中嵌入原生 EMA.Config 时漏转、落入 CUDA stream 的问题;NPU EMA 不在本轮最终验收范围。
284+ 
285+### 7.2 基础 eager 验证边界
286+ 
287+入口为 `tests/integration_tests/run_tests.py --test_suite deepseek_eager_parallel`。固定 2 个 NPU、3 个 step、每 rank microbatch 256 tokens、每 step 512 tokens,关闭编译、activation checkpoint 和 checkpoint,使用 AdamW 和 reference 算子。DSV4.1 显式关闭 Engram。
288+ 
289+- DSV4 EP1/FSDP2:已完成 3 个 step。
290+- DSV4 EP2/FSDP2:已完成 3 个 step。
291+- DSV4.1 EP1/FSDP2、无 Engram:已完成 3 个 step。
292+ 
293+三个 case 的 runner 均返回 0,并从 TensorBoard 校验恰好包含 step 1、2、3,loss 有限且 step 不重复;另行读取的 grad_norm 也均为有限值。最终执行日志为 `base-eager-final.log`。
294+ 
295+上述冒烟仅证明前向、反向、optimizer step 和训练结束流程可执行,不作为精度或性能结论。详细日志保留在本地 `test_reports/stage45-ebdfc8/`。
296+ 
297+后续对比了插件 `180c092` / 上游 `dc3985` 与当前工作区 / 上游 `ebdfc8`:DSV4 EP1、EP2 和关闭 Engram 的 DSV4.1 EP1 均使用相同初始权重、输入和确定性设置运行 100 步。逐步 `loss`、`grad_norm` 满足仓库数值近似阈值,但不满足比特一致。DSV4 和 DSV4.1 EP1 首步最后一层的分支消融确认:上游 shared/routed expert `w13` 融合改变反向求和顺序;DSV4 四层临时拆分后,两步 loss 与 grad_norm 逐位一致。该定位尚未扩展到 EP2、DSV4.1 全层或完整 100 步。该结果仅覆盖双卡 debug model、序列长度 256、AdamW 和 reference 算子,不代表预训练权重、Flash 全规模或其他功能已通过。数据、权重验证方法及逐步指标见本地 `test_reports/stage45-ebdfc8/precision-report.md`。
298+ 
299+CPU 回归覆盖配置 owner 保留、类型化 optimizer 构造、EMA 更新调度、FSDP expert storage、Muon layout 和分布式初始化:77 项通过,1 项因当前 runtime 不具备 per-edge PP 能力而跳过。SPMD/FSDP 存储测试实际调用模型 `parallelize`,fake process group 仅提供 CPU mesh,不作为 collective 验证。
300+ 
301+完整本地 pre-commit 的格式、架构和其他 hook 通过,Pyrefly 未通过。默认 `/tmp/torchtitan` 按仓库约定指向共享旧基线;显式使用本工作区 `ebdfc8` 后仍有 21 项类型错误,均位于本轮未修改的文件,涉及 GraphTrainer、CP、LoRA、量化和旧 runtime 符号。本轮不将完整 Lint 标为通过。
302+ 
303+### 7.3 后续验收
304+ 
305+恢复扩展验证时,分别检查 HSDP owner-only Muon state 与广播、CPU-offload 的 optimizer 更新和资源释放、EMA 混合 CPU/NPU 参数更新、TP/CP 文档布局与梯度,以及 Host Engram。不能使用 CPU mesh 元数据测试替代真实 NPU collectives。
306+ 
307+旧 integration case 的 `--optimizer.*`、`--checkpoint.*`、旧 dataloader 字段与 `model_spec` 仍需由对应专项迁移。现有 PP runtime 边界和 V4.1 的 TP/PP 显式限制保持可见。Checkpoint、LoRA、低精度及第 6 节的 TorchFT 债务继续延期。
@@ -1,7 +1,6 @@
1{1{
2 "patch_metadata": {2 "patch_metadata": {
3 "missing": [3 "missing": [
4- "torchtitan_npu/patches/torchtitan/distributed/flex_shard/dist_muon.py",
5 "torchtitan_npu/patches/torchtitan/distributed/flex_shard/replica_dedup.py",4 "torchtitan_npu/patches/torchtitan/distributed/flex_shard/replica_dedup.py",
6 "torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py",5 "torchtitan_npu/patches/torchtitan/experiments/graph_trainer/functionalize_recompute_mutations.py",
7 "torchtitan_npu/patches/torchtitan/hf_datasets/text_datasets.py",6 "torchtitan_npu/patches/torchtitan/hf_datasets/text_datasets.py",
@@ -29,6 +28,7 @@
29 ],28 ],
30 "activation_order": {29 "activation_order": {
31 "torchtitan_npu/extensions/__init__.py": [30 "torchtitan_npu/extensions/__init__.py": [
31+ ".torchtitan.distributed",
32 ".torchtitan.ep_process_group",32 ".torchtitan.ep_process_group",
33 ".torchtitan.models.common",33 ".torchtitan.models.common",
34 ".torchtitan.trainer",34 ".torchtitan.trainer",
@@ -39,17 +39,12 @@
39 ".compile.dynamo_config"39 ".compile.dynamo_config"
40 ],40 ],
41 "torchtitan_npu/patches/torchtitan/__init__.py": [41 "torchtitan_npu/patches/torchtitan/__init__.py": [
42- ".components.checkpoint",42+ ".components.checkpointer",
43- ".trainer",
44 ".components.metrics",43 ".components.metrics",
45 ".components.optimizer",44 ".components.optimizer",
46 ".distributed.context_parallel",45 ".distributed.context_parallel",
47- ".distributed.flex_shard.dist_muon",
48 ".experiments.graph_trainer.chunked_loss",46 ".experiments.graph_trainer.chunked_loss",
49- ".experiments.graph_trainer.ep_chunk_concretization",
50 ".experiments.graph_trainer.ep_overlap_shape_queries",47 ".experiments.graph_trainer.ep_overlap_shape_queries",
51- ".experiments.graph_trainer.ep_ready_nodes_dedup",
52- ".experiments.graph_trainer.ep_shape_live_out",
53 ".observability",48 ".observability",
54 ".models.common.attention_metadata",49 ".models.common.attention_metadata",
55 ".models.common.decoder",50 ".models.common.decoder",
@@ -60,20 +60,12 @@ EOF
60chmod +x "${PYTHON_SHIMS}/torchrun"60chmod +x "${PYTHON_SHIMS}/torchrun"
61export PATH="${PYTHON_SHIMS}:${PATH}"61export PATH="${PYTHON_SHIMS}:${PATH}"
62 62 
63-# Clone and install torchtitan.63+# Install the source packages using the dependencies supplied by the CI image.
64_setup_torchtitan "${TORCHTITAN_DIR}"64_setup_torchtitan "${TORCHTITAN_DIR}"
65 65 
66"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}"66"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${TORCHTITAN_DIR}"
67"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}"67"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir -e "${PROJECT_ROOT}"
68 68 
69-# The image predates wheels added to requirements.txt; install only the missing
70-# wheels, never the whole file, whose torch/torch_npu pins differ from the image
71-# build.
72-"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir attn-gym==0.0.16 spmd_types==0.2.5 \
73- 'torch_checkpointing==0.1.1' 'torch_remat>=0.2.0'
74-# Grain needs its data-pipeline dependencies (for example etils and array-record).
75-# Its dependency graph does not include torch or torch_npu.
76-"${PYTHON_BIN}" -m pip install --break-system-packages --no-cache-dir grain==0.2.18
77# The CI image supplies torch 2.14.0.dev; the matching torchvision CPU wheel69# The CI image supplies torch 2.14.0.dev; the matching torchvision CPU wheel
titan-npu-reviewer

一般(S2): 【文档同步】需要补充或更新文档。

本 PR 的文档同步要求: 架构说明三处把“拒绝 CP”的责任归给 pinned decoder,但 ebdfc8 的 Decoder.Config.update_from_config 里没有 CP 分支;实际守卫是 torchtitan/config/validation.py:91 的 validate_context_parallel,由 ConfigManager 校验阶段抛出 ValueError。新增 UT 照抄了这条不准确的描述,导致文档和测试一起偏离真实契约,建议一并更正。

  1. .agents/notes/implemented/architecture/2026-10-14-backend-owned-attention-metadata.md:65:把“pinned decoder 在 CP>1 时于配置阶段报错”改成“配置校验 validate_context_parallel 在 CP>1 时抛 ValueError(must use CPInnerAttention)”,并同步第 114 行和第 145 行的同样表述。

问题编号:R1171-004

审查版本:8ec34d9f4755e88b729eff691b37ff7013e75cd4

likedislike
78# is installed with --no-deps (resolving its torch pin would fight the image).70# is installed with --no-deps (resolving its torch pin would fight the image).
79"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir --index-url https://download.pytorch.org/whl/cpu "torchvision==0.29.0+cpu"71"${PYTHON_BIN}" -m pip install --break-system-packages --no-deps --no-cache-dir --index-url https://download.pytorch.org/whl/cpu "torchvision==0.29.0+cpu"
@@ -38,6 +38,13 @@ _setup_torchtitan() {
38 revision="$(_torchtitan_revision)" || return38 revision="$(_torchtitan_revision)" || return
39 repository="${TORCHTITAN_REPO:-${TORCHTITAN_REPOSITORY}}"39 repository="${TORCHTITAN_REPO:-${TORCHTITAN_REPOSITORY}}"
40 40 
41+ # Workflows may run from the target branch while sourcing this PR's script.
42+ # Let subsequent pip subprocesses fetch the pinned remat SHA from GitCode.
43+ local git_config_index="${GIT_CONFIG_COUNT:-0}"
44+ export "GIT_CONFIG_KEY_${git_config_index}=url.https://gitcode.com/hitwdy/remat.git.insteadOf"
45+ export "GIT_CONFIG_VALUE_${git_config_index}=https://github.com/meta-pytorch/remat.git"
46+ export GIT_CONFIG_COUNT="$((git_config_index + 1))"
47+ 
41 echo "Preparing torchtitan at ${revision}..."48 echo "Preparing torchtitan at ${revision}..."
42 if [[ ! -e "$target_dir" ]]; then49 if [[ ! -e "$target_dir" ]]; then
43 mkdir -p "$(dirname "$target_dir")"50 mkdir -p "$(dirname "$target_dir")"
@@ -47,25 +47,16 @@ pip install -r requirements-dev.txt
47 47 
48_setup_torchtitan "${TORCHTITAN_DIR}"48_setup_torchtitan "${TORCHTITAN_DIR}"
49export TORCHTITAN_DIR49export TORCHTITAN_DIR
50-pip install --no-deps -e "${TORCHTITAN_DIR}"50+# Resolve upstream runtime dependencies using the transport configured above.
51-pip install \51+pip install -e "${TORCHTITAN_DIR}"
52+# The NPU package overrides upstream's attn-gym pin; keep the image's torch stack.
53+pip install --no-deps \
52 --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torchft/index.html \54 --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torchft/index.html \
53- "torch==$(python -c 'import torch; print(torch.__version__.split("+")[0])')" \55+ 'torchft==0.2.0' 'attn-gym==0.0.16'
54- 'torchft==0.2.0'
55pip install --no-deps -e .56pip install --no-deps -e .
56 57 
57-# The image predates wheels added to requirements.txt. Install only those wheels:
58-# the image pins a *different* torch/torch_npu build than requirements.txt does, so
59-# re-running the whole file would upgrade the CANN stack mid-job (it broke the
60-# fused-op smoke tests once). New pure-Python runtime wheels go here by name.
61-pip install --no-deps attn-gym==0.0.16 spmd_types==0.2.5 \
62- 'torch_checkpointing==0.1.1' 'torch_remat>=0.2.0'
63-# Resolve Grain's own data-pipeline dependencies without changing the torch stack.
64-pip install grain==0.2.18
65- 
66pip install --no-deps torchvision==0.29.0+cpu \58pip install --no-deps torchvision==0.29.0+cpu \
67 --index-url https://download.pytorch.org/whl/cpu59 --index-url https://download.pytorch.org/whl/cpu
68-python -c 'import torch, torchvision; print(torch.__version__, torchvision.__version__)'
69 60 
70-python -c 'from torchtitan.distributed.context_parallel.api import cp_shard; print(cp_shard.__module__)'61+python -c 'import grain, renderers, spmd_types, torch_remat, torchtitan, torchtitan_npu'
71python -m pytest -v --tb=short tests/unit_tests62python -m pytest -v --tb=short tests/unit_tests
@@ -64,7 +64,6 @@ pip install -e .
64 64 
65详情参见 [安装教程](https://gitcode.com/cann/torchtitan-npu/tree/master/docs/user-guides/installation.md) 。65详情参见 [安装教程](https://gitcode.com/cann/torchtitan-npu/tree/master/docs/user-guides/installation.md) 。
66 66 
67- 
68# 快速上手67# 快速上手
69快速启动大语言模型的训练任务,参见68快速启动大语言模型的训练任务,参见
70[快速上手文档](https://gitcode.com/cann/torchtitan-npu/tree/master/docs/user-guides/quickstart.md) 。69[快速上手文档](https://gitcode.com/cann/torchtitan-npu/tree/master/docs/user-guides/quickstart.md) 。
@@ -8,6 +8,7 @@ torchtitan-npu 支持 Atlas 800T A3 等昇腾训练硬件。软件版本配套
8|---------------------|-----------------|--------------|----------------|-----------|-------------|---------------|8|---------------------|-----------------|--------------|----------------|-----------|-------------|---------------|
9| master | main | 2.14.0(daily) | 2.14.0(daily) | 9.2.0 | Python 3.12.x | 3.2.1 |9| master | main | 2.14.0(daily) | 2.14.0(daily) | 9.2.0 | Python 3.12.x | 3.2.1 |
10| v0.2.2-dev | v0.2.2 | 2.10.0 | 2.10.0 | 9.0.0 | Python 3.11.x | 3.2.1 |10| v0.2.2-dev | v0.2.2 | 2.10.0 | 2.10.0 | 9.0.0 | Python 3.11.x | 3.2.1 |
11+| dev_0.4.0 | `ebdfc8c2a24d89d89c99c0ef96ed8ac149864175` | 2.14.0(daily) | 2.14.0(daily) | 9.3.0 | Python 3.12.x | 3.2.1 |
11 12 
12> [!NOTE]13> [!NOTE]
13> 安装所需的 Python 包依赖及版本见 [requirements.txt](../../requirements.txt)14> 安装所需的 Python 包依赖及版本见 [requirements.txt](../../requirements.txt)
@@ -18,12 +18,11 @@ WORLD_SIZE="${NGPU}"
18 18 
19# Model19# Model
20MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"20MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
21-CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts}"21+CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts_compiled}"
22 22 
23-# Dataloader & Checkpoint23+# Dataloader
24# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe.24# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe.
25HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path25HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
26-CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path
27 26 
28# Parallelism27# Parallelism
29TP=128TP=1
@@ -32,7 +31,6 @@ EP=8
32CP="${CP:-1}"31CP="${CP:-1}"
33DP_SHARD=832DP_SHARD=8
34DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))33DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
35-SPMD_BACKEND="spmd_types"
36 34 
37# Training35# Training
38SEQ_LEN=409636SEQ_LEN=4096
@@ -54,22 +52,15 @@ HF_ASSETS_ARGS="
54 52 
55# Parallelism53# Parallelism
56PARALLELISM_ARGS="54PARALLELISM_ARGS="
57- --parallelism.spmd-backend ${SPMD_BACKEND}
58 --parallelism.data-parallel-shard-degree ${DP_SHARD}55 --parallelism.data-parallel-shard-degree ${DP_SHARD}
59 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}56 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
60 --parallelism.expert-parallel-degree ${EP}57 --parallelism.expert-parallel-degree ${EP}
61 --parallelism.tensor-parallel-degree ${TP}58 --parallelism.tensor-parallel-degree ${TP}
62 --parallelism.context-parallel-degree ${CP}59 --parallelism.context-parallel-degree ${CP}
63- --parallelism.context-parallel-load-balancer doc_chunk
64 --parallelism.pipeline-parallel-degree ${PP}60 --parallelism.pipeline-parallel-degree ${PP}
65"61"
66 62 
67-# Compile63+# Compilation policy is declared by the selected Python recipe.
68-COMPILE_ARGS="
69- --compile.enable
70- --compile.components model
71- --compile.backend inductor
72-"
73 64 
74# Training65# Training
75TRAINING_ARGS="66TRAINING_ARGS="
@@ -80,15 +71,8 @@ TRAINING_ARGS="
80 --training.disable-cuda-graphs71 --training.disable-cuda-graphs
81"72"
82 73 
83-# Checkpoint74+# Checkpoint policy is declared by the selected Python recipe.
84-# `checkpoint.folder` is the save/load root (`CKPT_SAVE_LOAD_PATH`). If it75+CHECKPOINT_ARGS=""
85-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
86-# it; use a new/empty folder when starting a fresh run.
87-CHECKPOINT_ARGS="
88- --checkpoint.no-enable
89- --checkpoint.load-only
90- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}
91-"
92 76 
93# Profiler77# Profiler
94PROFILER_ARGS="78PROFILER_ARGS="
@@ -108,16 +92,16 @@ COMM_ARGS="
108 92 
109# Optimizer93# Optimizer
110OPTIMIZER_ARGS="94OPTIMIZER_ARGS="
111- --optimizer.name Muon95+ --optim.optimizer.name Muon
112- --optimizer.lr 1.0e-596+ --optim.optimizer.lr 1.0e-5
113- --optimizer.beta1 0.997+ --optim.optimizer.beta1 0.9
114- --optimizer.beta2 0.9598+ --optim.optimizer.beta2 0.95
115- --optimizer.eps 1.0e-899+ --optim.optimizer.eps 1.0e-8
116- --optimizer.weight_decay 1.0e-1100+ --optim.optimizer.weight_decay 1.0e-1
117- --optimizer.muon_momentum 0.95101+ --optim.optimizer.muon_momentum 0.95
118- --optimizer.muon_enable_nesterov102+ --optim.optimizer.muon_enable_nesterov
119- --optimizer.muon_ns_steps 10103+ --optim.optimizer.muon_ns_steps 10
120- --optimizer.muon_adjust_lr_fn match_rms_adamw104+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
121"105"
122OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"106OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
123 107 
@@ -152,7 +136,6 @@ CONFIG="${CONFIG}" \
152NGPU="${NGPU}" \136NGPU="${NGPU}" \
153LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \137LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
154bash scripts/run_train.sh \138bash scripts/run_train.sh \
155- $COMPILE_ARGS \
156 $HF_ASSETS_ARGS \139 $HF_ASSETS_ARGS \
157 $PARALLELISM_ARGS \140 $PARALLELISM_ARGS \
158 $TRAINING_ARGS \141 $TRAINING_ARGS \
@@ -17,13 +17,11 @@ export TORCH_NPU_USE_COMPATIBLE_IMPL=1
17EP_OVERLAP_ARGS=(17EP_OVERLAP_ARGS=(
18 --compile.ep_overlap.enabled18 --compile.ep_overlap.enabled
19 --compile.ep_overlap.chunk_dim seq19 --compile.ep_overlap.chunk_dim seq
20- --compile.ep_overlap.strategy graph
21 --compile.ep_overlap.module_fqn "layers.*.moe"20 --compile.ep_overlap.module_fqn "layers.*.moe"
22 --compile.pass_pipeline mutation-functionalization+npu_auto_overlap21 --compile.pass_pipeline mutation-functionalization+npu_auto_overlap
23)22)
24 23 
25exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \24exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
26 --debug.moe-force-load-balance \25 --debug.moe-force-load-balance \
27- --parallelism.spmd-backend spmd_types \
28 "${EP_OVERLAP_ARGS[@]}" \26 "${EP_OVERLAP_ARGS[@]}" \
29 "$@"27 "$@"
@@ -38,7 +38,7 @@ fi
38# narrow the whitelist by appending the default patterns minus the offending38# narrow the whitelist by appending the default patterns minus the offending
39# one, e.g. excluding wkv (comma-separated in a single argument, matching the39# one, e.g. excluding wkv (comma-separated in a single argument, matching the
40# 4K entry):40# 4K entry):
41-# --extension.quantization.fsdp-prequantize-fqns .attention.wq_a,.attention.wq_b,.attention.wo_a,.attention.wo_b,.attention.indexer.wq_b,.moe.shared_experts.w1,.moe.shared_experts.w2,.moe.shared_experts.w3,.moe.routed_experts.inner_experts41+# --extension.quantization.fsdp-prequantize-fqns .attention.wq_a,.attention.wq_b,.attention.wo_a,.attention.wo_b,.attention.indexer.wq_b,.moe.shared_experts.w13,.moe.shared_experts.w2,.moe.routed_experts.w13,.moe.routed_experts.w2
42# A user whitelist fails fast on any pattern absent from the model, so drop42# A user whitelist fails fast on any pattern absent from the model, so drop
43# the .moe.shared_experts.* entries on a model without shared experts.43# the .moe.shared_experts.* entries on a model without shared experts.
44QUANTIZATION_ARGS=(44QUANTIZATION_ARGS=(
@@ -14,11 +14,9 @@ export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash_43layers_16experts}"
14export NGPU="${NGPU:-8}"14export NGPU="${NGPU:-8}"
15 15 
16bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5.sh \16bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5.sh \
17- --parallelism.spmd-backend partial_dtensor \
18 --parallelism.data-parallel-shard-degree "${NGPU}" \17 --parallelism.data-parallel-shard-degree "${NGPU}" \
19 --parallelism.data-parallel-replicate-degree 1 \18 --parallelism.data-parallel-replicate-degree 1 \
20 --parallelism.expert-parallel-degree "${NGPU}" \19 --parallelism.expert-parallel-degree "${NGPU}" \
21- --compile.mode aot_fx_trace \
22 --compile.enable-passes \20 --compile.enable-passes \
23 --compile.backend aot_eager \21 --compile.backend aot_eager \
24 --compile.inductor-compilation regional \22 --compile.inductor-compilation regional \
@@ -26,7 +24,6 @@ bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5.sh \
26 --compile.memory-policy full \24 --compile.memory-policy full \
27 --compile.ep-overlap.enabled \25 --compile.ep-overlap.enabled \
28 --compile.ep-overlap.chunk-dim batch \26 --compile.ep-overlap.chunk-dim batch \
29- --compile.ep-overlap.strategy graph \
30 --compile.ep-overlap.module-fqn "layers.*" \27 --compile.ep-overlap.module-fqn "layers.*" \
31 --compile.no-enable-autoparallel \28 --compile.no-enable-autoparallel \
32 --compile.no-enable-fsdp-ag-rs-overlap \29 --compile.no-enable-fsdp-ag-rs-overlap \
@@ -21,14 +21,12 @@ STEPS="${STEPS:-20}"
21EP_OVERLAP_ARGS=(21EP_OVERLAP_ARGS=(
22 --compile.ep_overlap.enabled22 --compile.ep_overlap.enabled
23 --compile.ep_overlap.chunk_dim seq23 --compile.ep_overlap.chunk_dim seq
24- --compile.ep_overlap.strategy graph
25 --compile.ep_overlap.module_fqn "layers.*.moe"24 --compile.ep_overlap.module_fqn "layers.*.moe"
26 --compile.pass_pipeline mutation-functionalization+npu_auto_overlap25 --compile.pass_pipeline mutation-functionalization+npu_auto_overlap
27)26)
28 27 
29exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \28exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \
30 --debug.moe-force-load-balance \29 --debug.moe-force-load-balance \
31- --parallelism.spmd-backend spmd_types \
32 --compile.memory-policy dsv4-mhc-moe-save \30 --compile.memory-policy dsv4-mhc-moe-save \
33 --training.steps "${STEPS}" \31 --training.steps "${STEPS}" \
34 "${EP_OVERLAP_ARGS[@]}" \32 "${EP_OVERLAP_ARGS[@]}" \
@@ -12,9 +12,8 @@ set -euo pipefail
12SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"12SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
13DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}"13DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}"
14 14 
15-CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts_sft}" \15+CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts_sft_compiled}" \
16DSV4_SFT_DATASET="${DATASET_PATH}" \16DSV4_SFT_DATASET="${DATASET_PATH}" \
17exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \17exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
18- --checkpoint.enable \18+ --checkpointer.no-load-only \
19- --checkpoint.no-load-only \
20 "$@"19 "$@"
@@ -20,10 +20,9 @@ WORLD_SIZE="${NGPU}"
20MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"20MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
21CONFIG="${CONFIG:-deepseek_v4_debugmodel}"21CONFIG="${CONFIG:-deepseek_v4_debugmodel}"
22 22 
23-# Dataloader & Checkpoint23+# Dataloader
24# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe.24# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe.
25HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path25HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
26-CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path
27 26 
28# Parallelism27# Parallelism
29TP=128TP=1
@@ -32,7 +31,6 @@ EP=1
32CP="${CP:-1}"31CP="${CP:-1}"
33DP_SHARD=132DP_SHARD=1
34DP_REPLICATE=133DP_REPLICATE=1
35-SPMD_BACKEND="spmd_types"
36 34 
37# Training35# Training
38SEQ_LEN=204836SEQ_LEN=2048
@@ -53,13 +51,11 @@ HF_ASSETS_ARGS="
53 51 
54# Parallelism52# Parallelism
55PARALLELISM_ARGS="53PARALLELISM_ARGS="
56- --parallelism.spmd-backend ${SPMD_BACKEND}
57 --parallelism.data-parallel-shard-degree ${DP_SHARD}54 --parallelism.data-parallel-shard-degree ${DP_SHARD}
58 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}55 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
59 --parallelism.expert-parallel-degree ${EP}56 --parallelism.expert-parallel-degree ${EP}
60 --parallelism.tensor-parallel-degree ${TP}57 --parallelism.tensor-parallel-degree ${TP}
61 --parallelism.context-parallel-degree ${CP}58 --parallelism.context-parallel-degree ${CP}
62- --parallelism.context-parallel-load-balancer doc_chunk
63 --parallelism.pipeline-parallel-degree ${PP}59 --parallelism.pipeline-parallel-degree ${PP}
64"60"
65 61 
@@ -72,15 +68,8 @@ TRAINING_ARGS="
72 --training.disable-cuda-graphs68 --training.disable-cuda-graphs
73"69"
74 70 
75-# Checkpoint71+# Checkpoint policy is declared by the selected Python recipe.
76-# `checkpoint.folder` is the save/load root (`CKPT_SAVE_LOAD_PATH`). If it72+CHECKPOINT_ARGS=""
77-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
78-# it; use a new/empty folder when starting a fresh run.
79-CHECKPOINT_ARGS="
80- --checkpoint.no-enable
81- --checkpoint.load-only
82- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}
83-"
84 73 
85# Profiler74# Profiler
86PROFILER_ARGS="75PROFILER_ARGS="
@@ -100,23 +89,23 @@ COMM_ARGS="
100 89 
101# Optimizer90# Optimizer
102OPTIMIZER_ARGS="91OPTIMIZER_ARGS="
103- --optimizer.name Muon92+ --optim.optimizer.name Muon
104- --optimizer.lr 1.0e-593+ --optim.optimizer.lr 1.0e-5
105- --optimizer.beta1 0.994+ --optim.optimizer.beta1 0.9
106- --optimizer.beta2 0.9595+ --optim.optimizer.beta2 0.95
107- --optimizer.eps 1.0e-896+ --optim.optimizer.eps 1.0e-8
108- --optimizer.weight_decay 1.0e-197+ --optim.optimizer.weight_decay 1.0e-1
109- --optimizer.muon_momentum 0.9598+ --optim.optimizer.muon_momentum 0.95
110- --optimizer.muon_enable_nesterov99+ --optim.optimizer.muon_enable_nesterov
111- --optimizer.muon_ns_steps 10100+ --optim.optimizer.muon_ns_steps 10
112- --optimizer.muon_adjust_lr_fn match_rms_adamw101+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
113"102"
114OPTIMIZER_OVERRIDES="103OPTIMIZER_OVERRIDES="
115 torchtitan_npu.override.common.optimizer.swap_optimizer104 torchtitan_npu.override.common.optimizer.swap_optimizer
116"105"
117 106 
118if [[ "${USE_GOLDEN}" == "1" ]]; then107if [[ "${USE_GOLDEN}" == "1" ]]; then
119- OPTIMIZER_ARGS="--optimizer.name AdamW --optimizer.lr 1.0e-5"108+ OPTIMIZER_ARGS="--optim.optimizer.name AdamW --optim.optimizer.lr 1.0e-5"
120 OPTIMIZER_OVERRIDES=""109 OPTIMIZER_OVERRIDES=""
121 NPU_OPS_OVERRIDES=(110 NPU_OPS_OVERRIDES=(
122 torchtitan_npu.override.common.rope.workaround111 torchtitan_npu.override.common.rope.workaround
@@ -8,7 +8,7 @@
8# Append CLI arguments to override the defaults below:8# Append CLI arguments to override the defaults below:
9# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13 \9# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13 \
10# ./examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \10# ./examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
11-# --checkpoint.initial-load-path /path/to/model_ckpt --training.steps 511+# --checkpointer.initial-load-path /path/to/model_ckpt --training.steps 5
12# USE_GOLDEN=1 selects the reference combination (the model's default attention).12# USE_GOLDEN=1 selects the reference combination (the model's default attention).
13# For deterministic execution, append13# For deterministic execution, append
14# --debug.seed 42 --debug.deterministic to the command line.14# --debug.seed 42 --debug.deterministic to the command line.
@@ -31,7 +31,7 @@ WORLD_SIZE=$((NGPU * NNODES))
31 31 
32# Model32# Model
33MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"33MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
34-CONFIG="${CONFIG:-deepseek_v4_pro_61layers_32experts}"34+CONFIG="${CONFIG:-deepseek_v4_pro_61layers_32experts_cpt}"
35 35 
36# Dataloader & Checkpoint36# Dataloader & Checkpoint
37HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path37HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
@@ -45,7 +45,6 @@ EP="${EP:-32}"
45CP="${CP:-1}"45CP="${CP:-1}"
46DP_SHARD="${DP_SHARD:-32}"46DP_SHARD="${DP_SHARD:-32}"
47DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))47DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
48-SPMD_BACKEND="spmd_types"
49 48 
50# Training49# Training
51SEQ_LEN=409650SEQ_LEN=4096
@@ -74,13 +73,11 @@ HF_ASSETS_ARGS="
74 73 
75# Parallelism74# Parallelism
76PARALLELISM_ARGS="75PARALLELISM_ARGS="
77- --parallelism.spmd-backend ${SPMD_BACKEND}
78 --parallelism.data-parallel-shard-degree ${DP_SHARD}76 --parallelism.data-parallel-shard-degree ${DP_SHARD}
79 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}77 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
80 --parallelism.expert-parallel-degree ${EP}78 --parallelism.expert-parallel-degree ${EP}
81 --parallelism.tensor-parallel-degree ${TP}79 --parallelism.tensor-parallel-degree ${TP}
82 --parallelism.context-parallel-degree ${CP}80 --parallelism.context-parallel-degree ${CP}
83- --parallelism.context-parallel-load-balancer doc_chunk
84 --parallelism.pipeline-parallel-degree ${PP}81 --parallelism.pipeline-parallel-degree ${PP}
85"82"
86 83 
@@ -94,16 +91,15 @@ TRAINING_ARGS="
94"91"
95 92 
96# Checkpoint93# Checkpoint
97-# `checkpoint.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it94+# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
98# already contains a valid step-* checkpoint, upstream TorchTitan resumes from95# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
99# it and ignores `initial-load-path`; use a new/empty folder when cold-starting96# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
100# from `CKPT_INIT_LOAD_PATH`.97# from `CKPT_INIT_LOAD_PATH`.
101CHECKPOINT_ARGS="98CHECKPOINT_ARGS="
102- --checkpoint.enable99+ --checkpointer.load-only
103- --checkpoint.load-only100+ --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
104- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}101+ --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
105- --checkpoint.initial-load-path ${CKPT_INIT_LOAD_PATH}102+ --checkpointer.initial-load-in-hf
106- --checkpoint.initial-load-in-hf
107"103"
108 104 
109# Profiler105# Profiler
@@ -124,16 +120,16 @@ COMM_ARGS="
124 120 
125# Optimizer121# Optimizer
126OPTIMIZER_ARGS="122OPTIMIZER_ARGS="
127- --optimizer.name Muon123+ --optim.optimizer.name Muon
128- --optimizer.lr 1.0e-5124+ --optim.optimizer.lr 1.0e-5
129- --optimizer.beta1 0.9125+ --optim.optimizer.beta1 0.9
130- --optimizer.beta2 0.95126+ --optim.optimizer.beta2 0.95
131- --optimizer.eps 1.0e-8127+ --optim.optimizer.eps 1.0e-8
132- --optimizer.weight_decay 1.0e-1128+ --optim.optimizer.weight_decay 1.0e-1
133- --optimizer.muon_momentum 0.95129+ --optim.optimizer.muon_momentum 0.95
134- --optimizer.muon_enable_nesterov130+ --optim.optimizer.muon_enable_nesterov
135- --optimizer.muon_ns_steps 10131+ --optim.optimizer.muon_ns_steps 10
136- --optimizer.muon_adjust_lr_fn match_rms_adamw132+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
137"133"
138OPTIMIZER_OVERRIDES="134OPTIMIZER_OVERRIDES="
139 torchtitan_npu.override.common.optimizer.swap_optimizer135 torchtitan_npu.override.common.optimizer.swap_optimizer
@@ -21,7 +21,7 @@ WORLD_SIZE="${NGPU}"
21 21 
22# Model22# Model
23MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"23MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
24-CONFIG="${CONFIG:-deepseek_v4_pro_61layers_12experts}"24+CONFIG="${CONFIG:-deepseek_v4_pro_61layers_12experts_cpt}"
25 25 
26# Dataloader & Checkpoint26# Dataloader & Checkpoint
27HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path27HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
@@ -35,7 +35,6 @@ EP="${EP:-4}"
35CP="${CP:-1}"35CP="${CP:-1}"
36DP_SHARD="${DP_SHARD:-8}"36DP_SHARD="${DP_SHARD:-8}"
37DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))37DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
38-SPMD_BACKEND="spmd_types"
39 38 
40# Training39# Training
41SEQ_LEN=409640SEQ_LEN=4096
@@ -57,13 +56,11 @@ HF_ASSETS_ARGS="
57 56 
58# Parallelism57# Parallelism
59PARALLELISM_ARGS="58PARALLELISM_ARGS="
60- --parallelism.spmd-backend ${SPMD_BACKEND}
61 --parallelism.data-parallel-shard-degree ${DP_SHARD}59 --parallelism.data-parallel-shard-degree ${DP_SHARD}
62 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}60 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
63 --parallelism.expert-parallel-degree ${EP}61 --parallelism.expert-parallel-degree ${EP}
64 --parallelism.tensor-parallel-degree ${TP}62 --parallelism.tensor-parallel-degree ${TP}
65 --parallelism.context-parallel-degree ${CP}63 --parallelism.context-parallel-degree ${CP}
66- --parallelism.context-parallel-load-balancer doc_chunk
67 --parallelism.pipeline-parallel-degree ${PP}64 --parallelism.pipeline-parallel-degree ${PP}
68"65"
69 66 
@@ -78,16 +75,15 @@ TRAINING_ARGS="
78"75"
79 76 
80# Checkpoint77# Checkpoint
81-# `checkpoint.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it78+# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
82# already contains a valid step-* checkpoint, upstream TorchTitan resumes from79# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
83# it and ignores `initial-load-path`; use a new/empty folder when cold-starting80# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
84# from `CKPT_INIT_LOAD_PATH`.81# from `CKPT_INIT_LOAD_PATH`.
85CHECKPOINT_ARGS="82CHECKPOINT_ARGS="
86- --checkpoint.enable83+ --checkpointer.load-only
87- --checkpoint.load-only84+ --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
88- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}85+ --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
89- --checkpoint.initial-load-path ${CKPT_INIT_LOAD_PATH}86+ --checkpointer.initial-load-in-hf
90- --checkpoint.initial-load-in-hf
91"87"
92 88 
93# Profiler89# Profiler
@@ -108,16 +104,16 @@ COMM_ARGS="
108 104 
109# Optimizer105# Optimizer
110OPTIMIZER_ARGS="106OPTIMIZER_ARGS="
111- --optimizer.name Muon107+ --optim.optimizer.name Muon
112- --optimizer.lr 1.0e-5108+ --optim.optimizer.lr 1.0e-5
113- --optimizer.beta1 0.9109+ --optim.optimizer.beta1 0.9
114- --optimizer.beta2 0.95110+ --optim.optimizer.beta2 0.95
115- --optimizer.eps 1.0e-8111+ --optim.optimizer.eps 1.0e-8
116- --optimizer.weight_decay 1.0e-1112+ --optim.optimizer.weight_decay 1.0e-1
117- --optimizer.muon_momentum 0.95113+ --optim.optimizer.muon_momentum 0.95
118- --optimizer.muon_enable_nesterov114+ --optim.optimizer.muon_enable_nesterov
119- --optimizer.muon_ns_steps 10115+ --optim.optimizer.muon_ns_steps 10
120- --optimizer.muon_adjust_lr_fn match_rms_adamw116+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
121"117"
122OPTIMIZER_OVERRIDES="118OPTIMIZER_OVERRIDES="
123 torchtitan_npu.override.common.optimizer.swap_optimizer119 torchtitan_npu.override.common.optimizer.swap_optimizer
@@ -14,13 +14,13 @@ set -euo pipefail
14 14 
15SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"15SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
16 16 
17+CONFIG="${CONFIG:-deepseek_v4_flash_cp_cpt}" \
17DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-16384}" \18DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-16384}" \
18exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \19exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \
19 --training.max-context-length 1048576 \20 --training.max-context-length 1048576 \
20 --training.num-tokens-per-microbatch-per-dp-rank 1048576 \21 --training.num-tokens-per-microbatch-per-dp-rank 1048576 \
21 --training.num-tokens-per-train-step 8388608 \22 --training.num-tokens-per-train-step 8388608 \
22 --parallelism.context-parallel-degree 128 \23 --parallelism.context-parallel-degree 128 \
23- --parallelism.context-parallel-load-balancer doc_chunk \
24 --parallelism.data-parallel-shard-degree 1 \24 --parallelism.data-parallel-shard-degree 1 \
25 --parallelism.data-parallel-replicate-degree 1 \25 --parallelism.data-parallel-replicate-degree 1 \
26 "$@"26 "$@"
@@ -8,7 +8,7 @@
8# Append CLI arguments to override the defaults below:8# Append CLI arguments to override the defaults below:
9# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13,192.168.1.14,192.168.1.15,192.168.1.16,192.168.1.17 \9# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13,192.168.1.14,192.168.1.15,192.168.1.16,192.168.1.17 \
10# ./examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \10# ./examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
11-# --checkpoint.initial-load-path /path/to/model_ckpt --training.steps 511+# --checkpointer.initial-load-path /path/to/model_ckpt --training.steps 5
12# USE_GOLDEN=1 selects the reference combination (the model's default attention).12# USE_GOLDEN=1 selects the reference combination (the model's default attention).
13# For deterministic execution, append13# For deterministic execution, append
14# --debug.seed 42 --debug.deterministic to the command line.14# --debug.seed 42 --debug.deterministic to the command line.
@@ -23,7 +23,7 @@ WORLD_SIZE=$((NGPU * NNODES))
23 23 
24# Model24# Model
25MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"25MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
26-CONFIG="${CONFIG:-deepseek_v4_flash}"26+CONFIG="${CONFIG:-deepseek_v4_flash_cpt}"
27 27 
28# Dataloader & Checkpoint28# Dataloader & Checkpoint
29HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path29HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
@@ -37,7 +37,6 @@ EP=128
37CP="${CP:-1}"37CP="${CP:-1}"
38DP_SHARD=12838DP_SHARD=128
39DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))39DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
40-SPMD_BACKEND="spmd_types"
41 40 
42# Training41# Training
43SEQ_LEN=409642SEQ_LEN=4096
@@ -61,22 +60,15 @@ HF_ASSETS_ARGS="
61 60 
62# Parallelism61# Parallelism
63PARALLELISM_ARGS="62PARALLELISM_ARGS="
64- --parallelism.spmd-backend ${SPMD_BACKEND}
65 --parallelism.data-parallel-shard-degree ${DP_SHARD}63 --parallelism.data-parallel-shard-degree ${DP_SHARD}
66 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}64 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
67 --parallelism.expert-parallel-degree ${EP}65 --parallelism.expert-parallel-degree ${EP}
68 --parallelism.tensor-parallel-degree ${TP}66 --parallelism.tensor-parallel-degree ${TP}
69 --parallelism.context-parallel-degree ${CP}67 --parallelism.context-parallel-degree ${CP}
70- --parallelism.context-parallel-load-balancer doc_chunk
71 --parallelism.pipeline-parallel-degree ${PP}68 --parallelism.pipeline-parallel-degree ${PP}
72"69"
73 70 
74-# Compile71+# Compilation policy is declared by the selected Python recipe.
75-COMPILE_ARGS="
76- --compile.enable
77- --compile.components model
78- --compile.backend inductor
79-"
80 72 
81# Training73# Training
82TRAINING_ARGS="74TRAINING_ARGS="
@@ -88,16 +80,15 @@ TRAINING_ARGS="
88"80"
89 81 
90# Checkpoint82# Checkpoint
91-# `checkpoint.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it83+# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
92# already contains a valid step-* checkpoint, upstream TorchTitan resumes from84# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
93# it and ignores `initial-load-path`; use a new/empty folder when cold-starting85# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
94# from `CKPT_INIT_LOAD_PATH`.86# from `CKPT_INIT_LOAD_PATH`.
95CHECKPOINT_ARGS="87CHECKPOINT_ARGS="
96- --checkpoint.enable88+ --checkpointer.load-only
97- --checkpoint.load-only89+ --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
98- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}90+ --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
99- --checkpoint.initial-load-path ${CKPT_INIT_LOAD_PATH}91+ --checkpointer.initial-load-in-hf
100- --checkpoint.initial-load-in-hf
101"92"
102 93 
103# Profiler94# Profiler
@@ -118,16 +109,16 @@ COMM_ARGS="
118 109 
119# Optimizer110# Optimizer
120OPTIMIZER_ARGS="111OPTIMIZER_ARGS="
121- --optimizer.name Muon112+ --optim.optimizer.name Muon
122- --optimizer.lr 1.0e-5113+ --optim.optimizer.lr 1.0e-5
123- --optimizer.beta1 0.9114+ --optim.optimizer.beta1 0.9
124- --optimizer.beta2 0.95115+ --optim.optimizer.beta2 0.95
125- --optimizer.eps 1.0e-8116+ --optim.optimizer.eps 1.0e-8
126- --optimizer.weight_decay 1.0e-1117+ --optim.optimizer.weight_decay 1.0e-1
127- --optimizer.muon_momentum 0.95118+ --optim.optimizer.muon_momentum 0.95
128- --optimizer.muon_enable_nesterov119+ --optim.optimizer.muon_enable_nesterov
129- --optimizer.muon_ns_steps 10120+ --optim.optimizer.muon_ns_steps 10
130- --optimizer.muon_adjust_lr_fn match_rms_adamw121+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
131"122"
132OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"123OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
133 124 
@@ -163,7 +154,6 @@ NODE_IPS="${NODE_IPS}" \
163NGPU="${NGPU}" \154NGPU="${NGPU}" \
164LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \155LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
165bash scripts/run_train_multinodes.sh \156bash scripts/run_train_multinodes.sh \
166- $COMPILE_ARGS \
167 $HF_ASSETS_ARGS \157 $HF_ASSETS_ARGS \
168 $PARALLELISM_ARGS \158 $PARALLELISM_ARGS \
169 $TRAINING_ARGS \159 $TRAINING_ARGS \
@@ -53,7 +53,7 @@ QUANTIZATION_ARGS=(
53 --extension.quantization.enable-quantized-training53 --extension.quantization.enable-quantized-training
54 --extension.quantization.recipe all_block_fp854 --extension.quantization.recipe all_block_fp8
55 --extension.quantization.enable-fsdp-prequantize55 --extension.quantization.enable-fsdp-prequantize
56- --extension.quantization.fsdp-prequantize-fqns .attention.wq_b,.attention.wo_a,.attention.indexer.wq_b,.moe.routed_experts.inner_experts56+ --extension.quantization.fsdp-prequantize-fqns .attention.wq_b,.attention.wo_a,.attention.indexer.wq_b,.moe.routed_experts.w13,.moe.routed_experts.w2
57 --extension.quantization.li-quantization fp857 --extension.quantization.li-quantization fp8
58 --extension.quantization.kv-norm-quantization.format mxfp858 --extension.quantization.kv-norm-quantization.format mxfp8
59 --extension.quantization.kv-norm-quantization.fqns .attention.kv_norm,.attention.compressor.norm59 --extension.quantization.kv-norm-quantization.fqns .attention.kv_norm,.attention.compressor.norm
@@ -11,7 +11,7 @@ set -euo pipefail
11 11 
12SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"12SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
13 13 
14-export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash}"14+export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash_cpt}"
15export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=115export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=1
16export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=016export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=0
17export TORCH_NPU_USE_COMPATIBLE_IMPL=117export TORCH_NPU_USE_COMPATIBLE_IMPL=1
@@ -21,14 +21,12 @@ STEPS="${STEPS:-20}"
21EP_OVERLAP_ARGS=(21EP_OVERLAP_ARGS=(
22 --compile.ep_overlap.enabled22 --compile.ep_overlap.enabled
23 --compile.ep_overlap.chunk_dim seq23 --compile.ep_overlap.chunk_dim seq
24- --compile.ep_overlap.strategy graph
25 --compile.ep_overlap.module_fqn "layers.*.moe"24 --compile.ep_overlap.module_fqn "layers.*.moe"
26 --compile.pass_pipeline mutation-functionalization+npu_auto_overlap25 --compile.pass_pipeline mutation-functionalization+npu_auto_overlap
27)26)
28 27 
29exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \28exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \
30 --training.num-tokens-per-train-step 2097152 \29 --training.num-tokens-per-train-step 2097152 \
31- --parallelism.spmd-backend spmd_types \
32 --training.steps "${STEPS}" \30 --training.steps "${STEPS}" \
33 --debug.moe-force-load-balance \31 --debug.moe-force-load-balance \
34 "${EP_OVERLAP_ARGS[@]}" \32 "${EP_OVERLAP_ARGS[@]}" \
@@ -12,10 +12,10 @@ set -euo pipefail
12 12 
13SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"13SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
14 14 
15-export CONFIG="${CONFIG:-deepseek_v4_flash_lora}"15+export CONFIG="${CONFIG:-deepseek_v4_flash_lora_compiled}"
16 16 
17# LoRA uses periodic native adapter checkpoints and final PEFT export.17# LoRA uses periodic native adapter checkpoints and final PEFT export.
18exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \18exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \
19- --checkpoint.no-load-only \19+ --checkpointer.no-load-only \
20- --checkpoint.save-training-state \20+ --checkpointer.save-training-state \
21 "$@"21 "$@"
@@ -13,9 +13,8 @@ SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
13CPT_SCRIPT="${CPT_SCRIPT:-${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh}"13CPT_SCRIPT="${CPT_SCRIPT:-${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh}"
14DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}"14DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}"
15 15 
16-CONFIG="${CONFIG:-deepseek_v4_flash_sft}" \16+CONFIG="${CONFIG:-deepseek_v4_flash_sft_compiled}" \
17DSV4_SFT_DATASET="${DATASET_PATH}" \17DSV4_SFT_DATASET="${DATASET_PATH}" \
18exec bash "${CPT_SCRIPT}" \18exec bash "${CPT_SCRIPT}" \
19- --checkpoint.enable \19+ --checkpointer.no-load-only \
20- --checkpoint.no-load-only \
21 "$@"20 "$@"
@@ -12,16 +12,37 @@ deepseek_v4_flash_cpt_4k_a3.sh
12 └── deepseek_v4_flash_cpt_1024k_a5.sh12 └── deepseek_v4_flash_cpt_1024k_a5.sh
13```13```
14 14 
15-- `deepseek_v4_flash_cpt_4k_a3.sh`:公共训练参数、override、checkpoint、optimizer 等基线配置,默认通过 CLI 启用 model 编译,backend 为 `inductor`。15+- `deepseek_v4_flash_cpt_4k_a3.sh`:公共训练参数、override、checkpoint、optimizer 等基线配置,默认选择 `deepseek_v4_flash_cpt` recipe,显式启用 model 编译和 checkpoint,backend 为 `inductor`。
16- `deepseek_v4_flash_cpt_4k_a5.sh`:增加 A5 运行环境和默认 block-FP8 量化,其他配置复用 A3 基线。16- `deepseek_v4_flash_cpt_4k_a5.sh`:增加 A5 运行环境和默认 block-FP8 量化,其他配置复用 A3 基线。
17- `deepseek_v4_flash_cpt_1024k_a5.sh`:继续复用 A5 4K 入口,只通过 CLI 覆盖 1M 所需的 CP、DP、序列长度和 global batch size,量化默认随 A5 4K 入口继承。17- `deepseek_v4_flash_cpt_1024k_a5.sh`:继续复用 A5 4K 入口,只通过 CLI 覆盖 1M 所需的 CP、DP、序列长度和 global batch size,量化默认随 A5 4K 入口继承。
18- 用户普通 CLI 参数位于默认选项之后,因此可以覆盖默认值(A5 的 activation-checkpoint 子命令仍在末尾),包括使用 `--extension.quantization.no-enable-quantized-training` 切换到 BF16。18- 用户普通 CLI 参数位于默认选项之后,因此可以覆盖默认值(A5 的 activation-checkpoint 子命令仍在末尾),包括使用 `--extension.quantization.no-enable-quantized-training` 切换到 BF16。
19 19 
20## 编译配置20## 编译配置
21 21 
22-编译通过 CLI 配置。Flash A3/A5 默认使用 `inductor`,只编译 `model`。在示例命令末尾追加22+编译和 checkpoint 的启用状态在 Python recipe 中定义。Flash A3/A5 默认选择
23-`--compile.backend inductor` 可显式指定 backend,追加 `--compile.no-enable` 可关闭编译。23+`deepseek_v4_flash_cpt`,8P debug 默认选择 `deepseek_v4_flash_43layers_16experts_compiled`;
24-独立入口若未默认启用编译,需同时传入 `--compile.enable --compile.components model`。24+二者均使用 `CompileConfig(components=[], model=ModelCompileConfig())`,只编译 model。
25+当前固定上游仍允许对已存在的配置传入 `--compile.model.backend aot_eager` 等普通字段。
26+从 `None` 启用组件、关闭组件或设置空列表时,直接修改 recipe;CLI 不再自动创建这些对象。
27+ 
28+例如将以下函数保存为仓库根目录的 `my_recipes.py`,再通过 `MODULE=my_recipes CONFIG=my_run` 选择:
29+ 
30+```python
31+from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash_cpt
32+ 
33+ 
34+def my_run():
35+ config = deepseek_v4_flash_cpt()
36+ config.compile = None
37+ config.checkpointer = None
38+ return config
39+```
40+ 
41+自定义 recipe 关闭 checkpoint 时,应选用未附加 checkpoint 字段的 debug launcher,
42+或直接使用 `scripts/run_train.sh` 并在 recipe 中配置训练参数。Pro、CP 等其他入口需要
43+编译时,也在对应 recipe 中显式设置 `CompileConfig`,再通过 `MODULE` / `CONFIG` 选择。
44+ 
45+CV Parallel 调试入口在当前固定 TorchTitan 版本中仅完成配置与注册适配。上游已删除其依赖的 Graph EP 分块机制,CV 运行迁移尚未完成,入口会明确报错;详见 [CV 迁移状态](../../torchtitan_npu/extensions/experiment/cv_parallel/README.md)。
25 46 
26## 常用环境变量47## 常用环境变量
27 48 
@@ -94,9 +115,6 @@ Pro 32-expert 是独立的裁剪模型 debug/performance 入口,不与 8P Flas
94```sh115```sh
95NODE_IPS="${NODE_IPS}" \116NODE_IPS="${NODE_IPS}" \
96bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \117bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
97- --compile.enable \
98- --compile.components model \
99- --compile.backend inductor \
100 --debug.moe-force-load-balance \118 --debug.moe-force-load-balance \
101 --training.steps 20119 --training.steps 20
102```120```
@@ -106,9 +124,6 @@ bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
106```sh124```sh
107CP=32 NODE_IPS="${NODE_IPS}" \125CP=32 NODE_IPS="${NODE_IPS}" \
108bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \126bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
109- --compile.enable \
110- --compile.components model \
111- --compile.backend inductor \
112 --parallelism.data-parallel-shard-degree 1 \127 --parallelism.data-parallel-shard-degree 1 \
113 --parallelism.data-parallel-replicate-degree 1 \128 --parallelism.data-parallel-replicate-degree 1 \
114 --training.max-context-length 131072 \129 --training.max-context-length 131072 \
@@ -122,27 +137,40 @@ A5 脚本默认启用 block-FP8;如需 BF16,请在命令末尾追加后文
122 137 
123### 导出和加载 Debug Hugging Face checkpoint138### 导出和加载 Debug Hugging Face checkpoint
124 139 
140+debug 默认关闭 checkpoint。先在 `my_recipes.py` 中定义需要 checkpoint 的配置:
141+ 
142+```python
143+from torchtitan.components.checkpointer import CheckpointManager
144+from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash_43layers_16experts_compiled
145+ 
146+ 
147+def debug_checkpoint():
148+ config = deepseek_v4_flash_43layers_16experts_compiled()
149+ config.checkpointer = CheckpointManager.Config(load_only=True)
150+ return config
151+```
152+ 
125导出 checkpoint:153导出 checkpoint:
126 154 
127```sh155```sh
156+MODULE=my_recipes CONFIG=debug_checkpoint \
128bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \157bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \
129- --checkpoint.folder ./export_ckpt \158+ --checkpointer.folder ./export_ckpt \
130- --checkpoint.enable \159+ --checkpointer.no-load-only \
131- --checkpoint.no-load-only \160+ --checkpointer.last-save-in-hf \
132- --checkpoint.last-save-in-hf \
133 --training.steps 1 \161 --training.steps 1 \
134 --debug.seed 42 \162 --debug.seed 42 \
135 --debug.deterministic163 --debug.deterministic
136```164```
137 165 
138-从导出的 HF checkpoint 冷启动时,使用新的或空的 `checkpoint.folder`,避免已有 step checkpoint 优先触发 resume:166+从导出的 HF checkpoint 冷启动时,使用新的或空的 `checkpointer.folder`,避免已有 step checkpoint 优先触发 resume:
139 167 
140```sh168```sh
169+MODULE=my_recipes CONFIG=debug_checkpoint \
141bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \170bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \
142- --checkpoint.folder ./load_ckpt \171+ --checkpointer.folder ./load_ckpt \
143- --checkpoint.enable \172+ --checkpointer.initial-load-path ./export_ckpt/checkpoint/step-1 \
144- --checkpoint.initial-load-path ./export_ckpt/checkpoint/step-1 \173+ --checkpointer.initial-load-in-hf \
145- --checkpoint.initial-load-in-hf \
146 --training.steps 1 \174 --training.steps 1 \
147 --debug.seed 42 \175 --debug.seed 42 \
148 --debug.deterministic176 --debug.deterministic
@@ -163,9 +191,6 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
163```sh191```sh
164NODE_IPS="${NODE_IPS}" \192NODE_IPS="${NODE_IPS}" \
165bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \193bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
166- --compile.enable \
167- --compile.components model \
168- --compile.backend inductor \
169 --debug.moe-force-load-balance \194 --debug.moe-force-load-balance \
170 --training.steps 20195 --training.steps 20
171```196```
@@ -177,9 +202,6 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
177```sh202```sh
178CP=8 NODE_IPS="${NODE_IPS}" \203CP=8 NODE_IPS="${NODE_IPS}" \
179bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \204bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
180- --compile.enable \
181- --compile.components model \
182- --compile.backend inductor \
183 --parallelism.data-parallel-shard-degree 16 \205 --parallelism.data-parallel-shard-degree 16 \
184 --parallelism.data-parallel-replicate-degree 1 \206 --parallelism.data-parallel-replicate-degree 1 \
185 --training.max-context-length 65536 \207 --training.max-context-length 65536 \
@@ -196,9 +218,6 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
196```sh218```sh
197NODE_IPS="${NODE_IPS}" \219NODE_IPS="${NODE_IPS}" \
198bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \220bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \
199- --compile.enable \
200- --compile.components model \
201- --compile.backend inductor \
202 --debug.moe-force-load-balance \221 --debug.moe-force-load-balance \
203 --training.steps 20222 --training.steps 20
204```223```
@@ -264,13 +283,13 @@ A3 脚本不默认启用量化;如需 A3 量化训练,请显式传入上面
264 283 
265## Checkpoint 说明284## Checkpoint 说明
266 285 
267-Flash 多机 CPT 基线默认启用 `--checkpoint.load-only`,即只负责加载,不会保存新的训练 checkpoint。需要保存时必须显式覆盖:286+Flash 多机 CPT 基线默认启用 `--checkpointer.load-only`,即只负责加载,不会保存新的训练 checkpoint。需要保存时必须显式覆盖:
268 287 
269```sh288```sh
270---checkpoint.no-load-only289+--checkpointer.no-load-only
271```290```
272 291 
273-当 `checkpoint.folder` 已存在有效的 `step-*` checkpoint 时,TorchTitan 会优先 resume,该情况下 `checkpoint.initial-load-path` 不作为冷启动来源;要从 `initial-load-path` 冷启动,请使用新的或空的 `checkpoint.folder`。292+当 `checkpointer.folder` 已存在有效的 `step-*` checkpoint 时,TorchTitan 会优先 resume,该情况下 `checkpointer.initial-load-path` 不作为冷启动来源;要从 `initial-load-path` 冷启动,请使用新的或空的 `checkpointer.folder`。
274 293 
275## LoRA 微调294## LoRA 微调
276 295 
@@ -279,11 +298,11 @@ Flash 多机 CPT 基线默认启用 `--checkpoint.load-only`,即只负责加
279```sh298```sh
280NODE_IPS="${NODE_IPS}" \299NODE_IPS="${NODE_IPS}" \
281bash examples/deepseek_v4/deepseek_v4_flash_lora_4k_a3.sh \300bash examples/deepseek_v4/deepseek_v4_flash_lora_4k_a3.sh \
282- --optimizer.name AdamW \301+ --optim.optimizer.name AdamW \
283 --training.steps 500 \302 --training.steps 500 \
284- --checkpoint.interval 100303+ --checkpointer.interval 100
285```304```
286 305 
287-该入口使用 `deepseek_v4_flash_lora` recipe(dense/expert rank 16、alpha 32),并开启 checkpoint 保存。优化器沿用 CPT 默认值,传入 `--optimizer.name` 可覆盖。周期 checkpoint 用于续跑,最后一步导出 PEFT adapter。模型规模、并行配置和其余默认参数继承 A3 公共入口,命令末尾的 CLI 参数仍可覆盖默认值。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 默认配置。306+该入口使用 `deepseek_v4_flash_lora_compiled` recipe(dense/expert rank 16、alpha 32),并开启 checkpoint 保存。优化器沿用 CPT 默认值,传入 `--optim.optimizer.name` 可覆盖。周期 checkpoint 用于续跑,最后一步导出 PEFT adapter。模型规模、并行配置和其余默认参数继承 A3 公共入口,命令末尾的 CLI 参数仍可覆盖默认值。A5 使用 `CONFIG=deepseek_v4_flash_lora_compiled bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh --checkpointer.no-load-only --checkpointer.save-training-state`,继承 A5 CPT 的 block-FP8 默认配置。
288 307 
289配置、部分参数训练、native checkpoint 恢复、PEFT 导出和离线合并见 [LoRA 功能指南](../../docs/feature_guides/deepseek_v4_lora.md)。308配置、部分参数训练、native checkpoint 恢复、PEFT 导出和离线合并见 [LoRA 功能指南](../../docs/feature_guides/deepseek_v4_lora.md)。
@@ -18,13 +18,12 @@ WORLD_SIZE="${NGPU}"
18 18 
19# Model19# Model
20MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"20MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"
21-CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal}"21+CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal_compiled}"
22 22 
23-# Dataloader & Checkpoint23+# Dataloader
24DATASET="${DATASET:-cc12m-test}"24DATASET="${DATASET:-cc12m-test}"
25DATASET_PATH="${DATASET_PATH:-}" # optional; unset keeps the upstream dataset source25DATASET_PATH="${DATASET_PATH:-}" # optional; unset keeps the upstream dataset source
26HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV41_tokenizer}" # your tokenizer path26HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV41_tokenizer}" # your tokenizer path
27-CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path
28 27 
29# Parallelism28# Parallelism
30TP=129TP=1
@@ -33,7 +32,6 @@ EP=8
33CP=132CP=1
34DP_SHARD=833DP_SHARD=8
35DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))34DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
36-SPMD_BACKEND="spmd_types"
37 35 
38# Training36# Training
39# Retain the validated eager / Muon / FullAC resource crop.37# Retain the validated eager / Muon / FullAC resource crop.
@@ -60,7 +58,6 @@ export PACKING_BUFFER_SIZE="${PACKING_BUFFER_SIZE:-0}"
60 58 
61# Parallelism59# Parallelism
62PARALLELISM_ARGS="60PARALLELISM_ARGS="
63- --parallelism.spmd-backend ${SPMD_BACKEND}
64 --parallelism.data-parallel-shard-degree ${DP_SHARD}61 --parallelism.data-parallel-shard-degree ${DP_SHARD}
65 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}62 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
66 --parallelism.expert-parallel-degree ${EP}63 --parallelism.expert-parallel-degree ${EP}
@@ -68,16 +65,10 @@ PARALLELISM_ARGS="
68 --parallelism.context-parallel-degree ${CP}65 --parallelism.context-parallel-degree ${CP}
69 --parallelism.pipeline-parallel-degree ${PP}66 --parallelism.pipeline-parallel-degree ${PP}
70 --parallelism.fsdp-reshard-after-forward always67 --parallelism.fsdp-reshard-after-forward always
71- --parallelism.context-parallel-load-balancer doc_chunk
72 --parallelism.enable-sequence-parallel68 --parallelism.enable-sequence-parallel
73"69"
74 70 
75-# Compile71+# Compilation policy is declared by the selected Python recipe.
76-COMPILE_ARGS="
77- --compile.enable
78- --compile.components model
79- --compile.backend inductor
80-"
81 72 
82# Training73# Training
83TRAINING_ARGS="74TRAINING_ARGS="
@@ -91,23 +82,15 @@ TRAINING_ARGS="
91 82 
92# LR scheduler83# LR scheduler
93LR_SCHEDULER_ARGS="84LR_SCHEDULER_ARGS="
94- --lr-scheduler.warmup-steps 285+ --optim.lr-scheduler.warmup-steps 2
95- --lr-scheduler.total-steps ${STEPS}86+ --optim.lr-scheduler.total-steps ${STEPS}
96- --lr-scheduler.decay-ratio 1.087+ --optim.lr-scheduler.decay-ratio 1.0
97- --lr-scheduler.decay-type cosine88+ --optim.lr-scheduler.decay-type cosine
98- --lr-scheduler.min-lr-factor 0.0189+ --optim.lr-scheduler.min-lr-factor 0.01
99"90"
100 91 
101-# Checkpoint92+# Checkpoint policy is declared by the selected Python recipe.
102-# `checkpoint.folder` is the save/load root (`CKPT_SAVE_LOAD_PATH`). If it93+CHECKPOINT_ARGS=""
103-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
104-# it; use a new/empty folder when starting a fresh run.
105-CHECKPOINT_ARGS="
106- --checkpoint.no-enable
107- --checkpoint.load-only
108- --checkpoint.interval 10
109- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}
110-"
111 94 
112# Profiler95# Profiler
113PROFILER_ARGS="96PROFILER_ARGS="
@@ -126,16 +109,16 @@ COMM_ARGS="
126# Optimizer109# Optimizer
127# AdamW hyperparameters come from the recipe, not from CLI flags.110# AdamW hyperparameters come from the recipe, not from CLI flags.
128OPTIMIZER_ARGS="111OPTIMIZER_ARGS="
129- --optimizer.name Muon112+ --optim.optimizer.name Muon
130- --optimizer.lr 1.0e-5113+ --optim.optimizer.lr 1.0e-5
131- --optimizer.beta1 0.9114+ --optim.optimizer.beta1 0.9
132- --optimizer.beta2 0.95115+ --optim.optimizer.beta2 0.95
133- --optimizer.eps 1.0e-8116+ --optim.optimizer.eps 1.0e-8
134- --optimizer.weight-decay 1.0e-1117+ --optim.optimizer.weight-decay 1.0e-1
135- --optimizer.muon_momentum 0.95118+ --optim.optimizer.muon_momentum 0.95
136- --optimizer.muon_enable_nesterov119+ --optim.optimizer.muon_enable_nesterov
137- --optimizer.muon_ns_steps 10120+ --optim.optimizer.muon_ns_steps 10
138- --optimizer.muon_adjust_lr_fn match_rms_adamw121+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
139"122"
140OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"123OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
141 124 
@@ -168,7 +151,6 @@ CONFIG="${CONFIG}" \
168NGPU="${NGPU}" \151NGPU="${NGPU}" \
169LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \152LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
170bash scripts/run_train.sh \153bash scripts/run_train.sh \
171- $COMPILE_ARGS \
172 $HF_ASSETS_ARGS \154 $HF_ASSETS_ARGS \
173 $PARALLELISM_ARGS \155 $PARALLELISM_ARGS \
174 $TRAINING_ARGS \156 $TRAINING_ARGS \
@@ -179,5 +161,5 @@ bash scripts/run_train.sh \
179 $COMM_ARGS \161 $COMM_ARGS \
180 $CHECKPOINT_ARGS \162 $CHECKPOINT_ARGS \
181 --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \163 --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
182- $CLI_OVERRIDES \164+ $CLI_OVERRIDES ${DATALOADER_OVERRIDES:-} \
183 "$@"165 "$@"
@@ -14,7 +14,7 @@ set -euo pipefail
14 14 
15SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"15SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
16 16 
17-export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_24experts_multimodal}"17+export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_24experts_multimodal_compiled}"
18 18 
19# Use the command line `npu-smi info -t topo` to query the CPU affinity of the19# Use the command line `npu-smi info -t topo` to query the CPU affinity of the
20# NPU cards for configuration.20# NPU cards for configuration.
@@ -9,6 +9,6 @@ set -euo pipefail
9 9 
10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"
12-export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal_sft}"12+export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal_sft_compiled}"
13 13 
14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" "$@"14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" "$@"
@@ -9,6 +9,6 @@ set -euo pipefail
9 9 
10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"
12-export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_24experts_multimodal_sft}"12+export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_24experts_multimodal_sft_compiled}"
13 13 
14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a5.sh" "$@"14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a5.sh" "$@"
@@ -66,8 +66,6 @@ exec bash scripts/run_train.sh \
66 --parallelism.tensor-parallel-degree 1 \66 --parallelism.tensor-parallel-degree 1 \
67 --parallelism.pipeline-parallel-degree 1 \67 --parallelism.pipeline-parallel-degree 1 \
68 --parallelism.context-parallel-degree 1 \68 --parallelism.context-parallel-degree 1 \
69- --compile.no-enable \
70- --checkpoint.no-enable \
71 --metrics.log-freq 1 \69 --metrics.log-freq 1 \
72 --override.imports ${CLI_OVERRIDES} \70 --override.imports ${CLI_OVERRIDES} \
73 "${QUANTIZATION_ARGS[@]}" \71 "${QUANTIZATION_ARGS[@]}" \
@@ -5,30 +5,27 @@
5# LICENSE file in the root directory of this source tree.5# LICENSE file in the root directory of this source tree.
6 6 
7# Run this script on each participating node; NODE_IPS lists all node addresses.7# Run this script on each participating node; NODE_IPS lists all node addresses.
8-# Append CLI arguments to override the defaults below:8+# CP=EP=128 requires at least 128 ranks with eight devices per node.
9-# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13,192.168.1.14,192.168.1.15,192.168.1.16,192.168.1.17 \9+# Append CLI arguments to override the defaults below.
10-# ./examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_4k_a3.sh \10+# For deterministic execution, append --debug.seed 42 --debug.deterministic.
11-# --checkpoint.initial-load-path /path/to/model_ckpt --training.steps 5
12-# For deterministic execution, append --debug.seed 42 --debug.deterministic to the command line.
13 11 
14set -euo pipefail12set -euo pipefail
15 13 
16-NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \14+NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \
17- xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}"15+ xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}"
18NGPU="${NGPU:-8}"16NGPU="${NGPU:-8}"
19NNODES=$(awk -F, '{print NF}' <<< "${NODE_IPS}")17NNODES=$(awk -F, '{print NF}' <<< "${NODE_IPS}")
20WORLD_SIZE=$((NGPU * NNODES))18WORLD_SIZE=$((NGPU * NNODES))
21 19 
22# Model20# Model
23MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"21MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"
24-CONFIG="${CONFIG:-deepseek_v4_1_flash_text}"22+CONFIG="${CONFIG:-deepseek_v4_1_flash_text_cp}"
25 23 
26-# Dataloader & Checkpoint24+# Dataloader
27-DATASET="${DATASET:-c4_test}"25+DATASET_PATH="${DATASET_PATH:-}" # optional JSON/JSONL file for the text source
28-DATASET_PATH="${DATASET_PATH:-}" # optional; unset keeps the upstream dataset source26+export DATA_FILES="${DATA_FILES:-${DATASET_PATH:-tests/assets/c4_test/data.json}}"
27+export DSV41_PER_DOC_ALIGNMENT="${DSV41_PER_DOC_ALIGNMENT:-256}"
29HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV41_tokenizer}" # your tokenizer path28HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV41_tokenizer}" # your tokenizer path
30-CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path
31-CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path
32 29 
33# Parallelism30# Parallelism
34TP=131TP=1
@@ -41,7 +38,6 @@ if (( WORLD_SIZE <= 0 || DP_SHARD <= 0 || EP <= 0 || WORLD_SIZE % DP_SHARD != 0
41 exit 138 exit 1
42fi39fi
43DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))40DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
44-SPMD_BACKEND="spmd_types"
45 41 
46# Training42# Training
47# Full Flash uses eager execution and the recipe-owned FullAC policy.43# Full Flash uses eager execution and the recipe-owned FullAC policy.
@@ -62,20 +58,10 @@ HF_ASSETS_ARGS="
62 --hf-assets-path ${HF_ASSETS_PATH}58 --hf-assets-path ${HF_ASSETS_PATH}
63"59"
64 60 
65-# Dataloader61+# The recipe owns the typed Grain dataset graph; DATA_FILES selects its JSON source.
66-DATALOADER_ARGS="
67- --dataloader.dataset ${DATASET}
68- --dataloader.per_doc_alignment 256
69-"
70-if [[ -n "${DATASET_PATH}" ]]; then
71- DATALOADER_ARGS+="
72- --dataloader.dataset-path ${DATASET_PATH}
73-"
74-fi
75 62 
76# Parallelism63# Parallelism
77PARALLELISM_ARGS="64PARALLELISM_ARGS="
78- --parallelism.spmd-backend ${SPMD_BACKEND}
79 --parallelism.data-parallel-shard-degree ${DP_SHARD}65 --parallelism.data-parallel-shard-degree ${DP_SHARD}
80 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}66 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
81 --parallelism.expert-parallel-degree ${EP}67 --parallelism.expert-parallel-degree ${EP}
@@ -83,16 +69,11 @@ PARALLELISM_ARGS="
83 --parallelism.context-parallel-degree ${CP}69 --parallelism.context-parallel-degree ${CP}
84 --parallelism.pipeline-parallel-degree ${PP}70 --parallelism.pipeline-parallel-degree ${PP}
85 --parallelism.fsdp-reshard-after-forward always71 --parallelism.fsdp-reshard-after-forward always
86- --parallelism.context-parallel-load-balancer doc_chunk
87 --parallelism.enable-sequence-parallel72 --parallelism.enable-sequence-parallel
88"73"
89 74 
90# Compile75# Compile
91-COMPILE_ARGS="76+COMPILE_ARGS=""
92- --compile.no-enable
93- --compile.components model
94- --compile.backend inductor
95-"
96 77 
97# Training78# Training
98TRAINING_ARGS="79TRAINING_ARGS="
@@ -106,25 +87,15 @@ TRAINING_ARGS="
106 87 
107# LR scheduler88# LR scheduler
108LR_SCHEDULER_ARGS="89LR_SCHEDULER_ARGS="
109- --lr-scheduler.warmup-steps 290+ --optim.lr-scheduler.warmup-steps 2
110- --lr-scheduler.total-steps ${STEPS}91+ --optim.lr-scheduler.total-steps ${STEPS}
111- --lr-scheduler.decay-ratio 1.092+ --optim.lr-scheduler.decay-ratio 1.0
112- --lr-scheduler.decay-type cosine93+ --optim.lr-scheduler.decay-type cosine
113- --lr-scheduler.min-lr-factor 0.0194+ --optim.lr-scheduler.min-lr-factor 0.01
114"95"
115 96 
116-# Checkpoint97+# Checkpoint policy is declared by the selected Python recipe.
117-# `checkpoint.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it98+CHECKPOINT_ARGS=""
118-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
119-# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
120-# from `CKPT_INIT_LOAD_PATH`.
121-CHECKPOINT_ARGS="
122- --checkpoint.no-enable
123- --checkpoint.load-only
124- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}
125- --checkpoint.initial-load-path ${CKPT_INIT_LOAD_PATH}
126- --checkpoint.initial-load-in-hf
127-"
128 99 
129# Profiler100# Profiler
130PROFILER_ARGS="101PROFILER_ARGS="
@@ -144,16 +115,16 @@ COMM_ARGS="
144 115 
145# Optimizer116# Optimizer
146OPTIMIZER_ARGS="117OPTIMIZER_ARGS="
147- --optimizer.name Muon118+ --optim.optimizer.name Muon
148- --optimizer.lr 1.0e-5119+ --optim.optimizer.lr 1.0e-5
149- --optimizer.beta1 0.9120+ --optim.optimizer.beta1 0.9
150- --optimizer.beta2 0.95121+ --optim.optimizer.beta2 0.95
151- --optimizer.eps 1.0e-8122+ --optim.optimizer.eps 1.0e-8
152- --optimizer.weight-decay 1.0e-1123+ --optim.optimizer.weight-decay 1.0e-1
153- --optimizer.muon_momentum 0.95124+ --optim.optimizer.muon_momentum 0.95
154- --optimizer.muon_enable_nesterov125+ --optim.optimizer.muon_enable_nesterov
155- --optimizer.muon_ns_steps 10126+ --optim.optimizer.muon_ns_steps 10
156- --optimizer.muon_adjust_lr_fn match_rms_adamw127+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
157"128"
158OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"129OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
159 130 
@@ -180,7 +151,6 @@ LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
180bash scripts/run_train_multinodes.sh \151bash scripts/run_train_multinodes.sh \
181 $COMPILE_ARGS \152 $COMPILE_ARGS \
182 $HF_ASSETS_ARGS \153 $HF_ASSETS_ARGS \
183- $DATALOADER_ARGS \
184 $PARALLELISM_ARGS \154 $PARALLELISM_ARGS \
185 $TRAINING_ARGS \155 $TRAINING_ARGS \
186 $DEBUG_ARGS \156 $DEBUG_ARGS \
@@ -8,7 +8,7 @@
8# Append CLI arguments to override the defaults below:8# Append CLI arguments to override the defaults below:
9# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13,192.168.1.14,192.168.1.15,192.168.1.16,192.168.1.17 \9# NODE_IPS=192.168.1.10,192.168.1.11,192.168.1.12,192.168.1.13,192.168.1.14,192.168.1.15,192.168.1.16,192.168.1.17 \
10# ./examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_4k_a3.sh \10# ./examples/deepseek_v4_1/deepseek_v4_1_flash_cpt_4k_a3.sh \
11-# --checkpoint.initial-load-path /path/to/model_ckpt --training.steps 511+# --checkpointer.initial-load-path /path/to/model_ckpt --training.steps 5
12# USE_GOLDEN=1 selects Golden. For deterministic execution, append12# USE_GOLDEN=1 selects Golden. For deterministic execution, append
13# --debug.seed 42 --debug.deterministic to the command line.13# --debug.seed 42 --debug.deterministic to the command line.
14 14 
@@ -22,7 +22,7 @@ WORLD_SIZE=$((NGPU * NNODES))
22 22 
23# Model23# Model
24MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"24MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"
25-CONFIG="${CONFIG:-deepseek_v4_1_flash}"25+CONFIG="${CONFIG:-deepseek_v4_1_flash_cpt}"
26 26 
27# Dataloader & Checkpoint27# Dataloader & Checkpoint
28DATASET="${DATASET:-cc12m-test}"28DATASET="${DATASET:-cc12m-test}"
@@ -42,7 +42,6 @@ if (( WORLD_SIZE <= 0 || DP_SHARD <= 0 || EP <= 0 || WORLD_SIZE % DP_SHARD != 0
42 exit 142 exit 1
43fi43fi
44DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))44DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
45-SPMD_BACKEND="spmd_types"
46 45 
47# Training46# Training
48# Full Flash uses eager execution and the recipe-owned FullAC policy.47# Full Flash uses eager execution and the recipe-owned FullAC policy.
@@ -69,7 +68,6 @@ export PACKING_BUFFER_SIZE="${PACKING_BUFFER_SIZE:-0}"
69 68 
70# Parallelism69# Parallelism
71PARALLELISM_ARGS="70PARALLELISM_ARGS="
72- --parallelism.spmd-backend ${SPMD_BACKEND}
73 --parallelism.data-parallel-shard-degree ${DP_SHARD}71 --parallelism.data-parallel-shard-degree ${DP_SHARD}
74 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}72 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
75 --parallelism.expert-parallel-degree ${EP}73 --parallelism.expert-parallel-degree ${EP}
@@ -77,16 +75,10 @@ PARALLELISM_ARGS="
77 --parallelism.context-parallel-degree ${CP}75 --parallelism.context-parallel-degree ${CP}
78 --parallelism.pipeline-parallel-degree ${PP}76 --parallelism.pipeline-parallel-degree ${PP}
79 --parallelism.fsdp-reshard-after-forward always77 --parallelism.fsdp-reshard-after-forward always
80- --parallelism.context-parallel-load-balancer doc_chunk
81 --parallelism.enable-sequence-parallel78 --parallelism.enable-sequence-parallel
82"79"
83 80 
84-# Compile81+# Compilation policy is declared by the selected Python recipe.
85-COMPILE_ARGS="
86- --compile.enable
87- --compile.components model
88- --compile.backend inductor
89-"
90 82 
91# Training83# Training
92TRAINING_ARGS="84TRAINING_ARGS="
@@ -100,24 +92,23 @@ TRAINING_ARGS="
100 92 
101# LR scheduler93# LR scheduler
102LR_SCHEDULER_ARGS="94LR_SCHEDULER_ARGS="
103- --lr-scheduler.warmup-steps 295+ --optim.lr-scheduler.warmup-steps 2
104- --lr-scheduler.total-steps ${STEPS}96+ --optim.lr-scheduler.total-steps ${STEPS}
105- --lr-scheduler.decay-ratio 1.097+ --optim.lr-scheduler.decay-ratio 1.0
106- --lr-scheduler.decay-type cosine98+ --optim.lr-scheduler.decay-type cosine
107- --lr-scheduler.min-lr-factor 0.0199+ --optim.lr-scheduler.min-lr-factor 0.01
108"100"
109 101 
110# Checkpoint102# Checkpoint
111-# `checkpoint.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it103+# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
112# already contains a valid step-* checkpoint, upstream TorchTitan resumes from104# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
113# it and ignores `initial-load-path`; use a new/empty folder when cold-starting105# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
114# from `CKPT_INIT_LOAD_PATH`.106# from `CKPT_INIT_LOAD_PATH`.
115CHECKPOINT_ARGS="107CHECKPOINT_ARGS="
116- --checkpoint.enable108+ --checkpointer.load-only
117- --checkpoint.load-only109+ --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
118- --checkpoint.folder ${CKPT_SAVE_LOAD_PATH}110+ --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
119- --checkpoint.initial-load-path ${CKPT_INIT_LOAD_PATH}111+ --checkpointer.initial-load-in-hf
120- --checkpoint.initial-load-in-hf
121"112"
122 113 
123# Profiler114# Profiler
@@ -138,16 +129,16 @@ COMM_ARGS="
138 129 
139# Optimizer130# Optimizer
140OPTIMIZER_ARGS="131OPTIMIZER_ARGS="
141- --optimizer.name Muon132+ --optim.optimizer.name Muon
142- --optimizer.lr 1.0e-5133+ --optim.optimizer.lr 1.0e-5
143- --optimizer.beta1 0.9134+ --optim.optimizer.beta1 0.9
144- --optimizer.beta2 0.95135+ --optim.optimizer.beta2 0.95
145- --optimizer.eps 1.0e-8136+ --optim.optimizer.eps 1.0e-8
146- --optimizer.weight-decay 1.0e-1137+ --optim.optimizer.weight-decay 1.0e-1
147- --optimizer.muon_momentum 0.95138+ --optim.optimizer.muon_momentum 0.95
148- --optimizer.muon_enable_nesterov139+ --optim.optimizer.muon_enable_nesterov
149- --optimizer.muon_ns_steps 10140+ --optim.optimizer.muon_ns_steps 10
150- --optimizer.muon_adjust_lr_fn match_rms_adamw141+ --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
151"142"
152OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"143OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
153 144 
@@ -180,7 +171,6 @@ NODE_IPS="${NODE_IPS}" \
180NGPU="${NGPU}" \171NGPU="${NGPU}" \
181LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \172LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
182bash scripts/run_train_multinodes.sh \173bash scripts/run_train_multinodes.sh \
183- $COMPILE_ARGS \
184 $HF_ASSETS_ARGS \174 $HF_ASSETS_ARGS \
185 $PARALLELISM_ARGS \175 $PARALLELISM_ARGS \
186 $TRAINING_ARGS \176 $TRAINING_ARGS \
@@ -191,5 +181,5 @@ bash scripts/run_train_multinodes.sh \
191 $COMM_ARGS \181 $COMM_ARGS \
192 $CHECKPOINT_ARGS \182 $CHECKPOINT_ARGS \
193 --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \183 --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
194- $CLI_OVERRIDES \184+ $CLI_OVERRIDES ${DATALOADER_OVERRIDES:-} \
195 "$@"185 "$@"
@@ -13,12 +13,7 @@ export CONFIG="${CONFIG:-deepseek_v4_1_flash_lora}"
13# Match the documented reference-operator LoRA path by default.13# Match the documented reference-operator LoRA path by default.
14export USE_GOLDEN="${USE_GOLDEN:-1}"14export USE_GOLDEN="${USE_GOLDEN:-1}"
15export OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-}"15export OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-}"
16-if [[ "${CONFIG}" == "deepseek_v4_1_flash_text_lora" ]]; then
17- export DATASET="${DATASET:-c4_test}"
18-fi
19- 
20exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_cpt_4k_a3.sh" \16exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_cpt_4k_a3.sh" \
21- --compile.no-enable \17+ --checkpointer.no-load-only \
22- --checkpoint.no-load-only \18+ --checkpointer.save-training-state \
23- --checkpoint.save-training-state \
24 "$@"19 "$@"
@@ -9,6 +9,6 @@ set -euo pipefail
9 9 
10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"
12-export CONFIG="${CONFIG:-deepseek_v4_1_flash_sft}"12+export CONFIG="${CONFIG:-deepseek_v4_1_flash_sft_compiled}"
13 13 
14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_cpt_4k_a3.sh" "$@"14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_cpt_4k_a3.sh" "$@"
@@ -9,6 +9,6 @@ set -euo pipefail
9 9 
10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"11export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"
12-export CONFIG="${CONFIG:-deepseek_v4_1_flash_sft}"12+export CONFIG="${CONFIG:-deepseek_v4_1_flash_sft_compiled}"
13 13 
14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_cpt_4k_a5.sh" "$@"14exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_cpt_4k_a5.sh" "$@"
@@ -8,16 +8,19 @@ V4.1 的模型、图像路由、压缩 attention、metadata 和并行化均由 `
8 8 
9既有配方覆盖 **FSDP + EP、TP1 / CP1 / PP1、eager 执行与 torch.compile**,包含 FullAC 与图文输入;迁移验收范围见开头说明。A3 脚本组织公共实验参数与融合列表,A5 调用 A3 并追加 CPU 亲和性、partial 文本 RoPE、两项 SwiGLUGroup、sparse attention 与 mHC Sinkhorn;两种入口均通过 `USE_GOLDEN=1` 选择 reference。A3 默认融合包含 RMSNorm、文本(`asc_complex`)与视觉 RoPE、MoE token dispatcher 和 mHC post;A5 将文本 RoPE 换为 `asc_partial` 并追加 routed/shared SwiGLUGroup、sparse 与 Sinkhorn。routed experts 的 grouped GEMM 是 reference 与融合共用的公共路径,不再作为独立融合开关。已接入量化入口及 Host Engram;不支持 MTP、DSpark、GraphTrainer;不支持的 TP、CP、PP 和 compile 配置在入口拒绝。9既有配方覆盖 **FSDP + EP、TP1 / CP1 / PP1、eager 执行与 torch.compile**,包含 FullAC 与图文输入;迁移验收范围见开头说明。A3 脚本组织公共实验参数与融合列表,A5 调用 A3 并追加 CPU 亲和性、partial 文本 RoPE、两项 SwiGLUGroup、sparse attention 与 mHC Sinkhorn;两种入口均通过 `USE_GOLDEN=1` 选择 reference。A3 默认融合包含 RMSNorm、文本(`asc_complex`)与视觉 RoPE、MoE token dispatcher 和 mHC post;A5 将文本 RoPE 换为 `asc_partial` 并追加 routed/shared SwiGLUGroup、sparse 与 Sinkhorn。routed experts 的 grouped GEMM 是 reference 与融合共用的公共路径,不再作为独立融合开关。已接入量化入口及 Host Engram;不支持 MTP、DSpark、GraphTrainer;不支持的 TP、CP、PP 和 compile 配置在入口拒绝。
10 10 
11-**torch.compile 已支持**(每个 TransformerBlock 整图编译,跨层状态为显式前向参数),通过脚本 `"$@"` 透传超参开启:11+编译和 checkpoint 的启用状态由 Python recipe 明确配置。8P debug 默认选择对应的
12+`*_multimodal_compiled` recipe,多机入口默认选择 `deepseek_v4_1_flash_cpt`;它们显式设置
13+`CompileConfig(components=[], model=ModelCompileConfig())`。当前上游仍支持覆盖已存在的
14+配置字段,例如以下 backend 参数;编译运行是否可用仍受本轮迁移范围限制:
12 15 
13```sh16```sh
14# aot_eager 整图(fullgraph=True)17# aot_eager 整图(fullgraph=True)
15bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \18bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
16- --compile.enable --compile.components model --compile.backend aot_eager19+ --compile.model.backend aot_eager
17 20 
18# inductor21# inductor
19bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \22bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
20- --compile.enable --compile.components model --compile.backend inductor23+ --compile.model.backend inductor
21```24```
22 25 
23编译态按 MoE 路由形态二分:负载均衡路由(A3/A5 脚本默认)下 inductor 保持整图(含 MoE 通信);数据依赖路由(显式 `--debug.no-moe-force-load-balance`)时 MoE 通信在编译图外执行。26编译态按 MoE 路由形态二分:负载均衡路由(A3/A5 脚本默认)下 inductor 保持整图(含 MoE 通信);数据依赖路由(显式 `--debug.no-moe-force-load-balance`)时 MoE 通信在编译图外执行。
@@ -41,22 +44,22 @@ USE_GOLDEN=1 \
41# 短跑(如 3 步):显式同步步数与 LR 调度44# 短跑(如 3 步):显式同步步数与 LR 调度
42bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \45bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
43 --hf-assets-path <v41_tokenizer_dir> \46 --hf-assets-path <v41_tokenizer_dir> \
44- --training.steps 3 --lr-scheduler.total-steps 3 --lr-scheduler.warmup-steps 247+ --training.steps 3 --optim.lr-scheduler.total-steps 3 --optim.lr-scheduler.warmup-steps 2
45```48```
46 49 
47单机 8 卡默认使用 40 层模型,A3 为 16 个路由专家,A5 为 24 个路由专家;上下文上限均为 4096,每 rank microbatch 为 4096 tokens,每步全局为 32768 tokens,使用 FSDP8/EP8、Muon(NS steps=10)、eager 和 FullAC,训练与调度均为 40 步。Python 配方保留模型结构、数据协议和优化器参数布局;实验参数由脚本组织,末尾 CLI 参数覆盖脚本默认值。`CONFIG` 可选择 `deepseek_v4_1_debugmodel_multimodal` 调试宽度,硬件选择仍由脚本负责。50单机 8 卡默认使用 40 层模型,A3 为 16 个路由专家,A5 为 24 个路由专家;上下文上限均为 4096,每 rank microbatch 为 4096 tokens,每步全局为 32768 tokens,使用 FSDP8/EP8、Muon(NS steps=10)、eager 和 FullAC,训练与调度均为 40 步。Python 配方保留模型结构、数据协议和优化器参数布局;实验参数由脚本组织,末尾 CLI 参数覆盖脚本默认值。`CONFIG` 可选择 `deepseek_v4_1_debugmodel_multimodal` 调试宽度,硬件选择仍由脚本负责。
48 51 
49-关闭 Engram 使用 `--no-engram-enabled`;优化器由脚本显式选择,末尾 `--optimizer.name AdamW` 仍可覆盖。A3 单机可通过末尾 CLI 参数调整上下文、microbatch 和每步 token 预算;默认每步预算为 32768 tokens。A5 多机保留与单机一致的 swap override;可通过 `OPTIMIZER_OVERRIDES` 显式覆盖。52+关闭 Engram 使用 `--no-engram-enabled`;优化器由脚本显式选择,末尾 `--optim.optimizer.name AdamW` 仍可覆盖。A3 单机可通过末尾 CLI 参数调整上下文、microbatch 和每步 token 预算;默认每步预算为 32768 tokens。A5 多机保留与单机一致的 swap override;可通过 `OPTIMIZER_OVERRIDES` 显式覆盖。
50 53 
51A5 的 `CPU_AFFINITY_CONF` 应按主机拓扑覆盖。通过 `CLI_OVERRIDES` 扩展融合列表:A3 基础列表之外,文本 RoPE 经该通道按硬件选择(A3 默认 `asc_complex`,A5 换为 `asc_partial`),A5 默认追加 SwiGLUGroup、sparse attention、融合 LI 选分与 Sinkhorn,不重复传入 `--override.imports`。显式传 `--override.imports` 会替换整个集合,需自行包含所需的 RoPE 与 swap optimizer。最终选择随 Trainer Config 打印。54A5 的 `CPU_AFFINITY_CONF` 应按主机拓扑覆盖。通过 `CLI_OVERRIDES` 扩展融合列表:A3 基础列表之外,文本 RoPE 经该通道按硬件选择(A3 默认 `asc_complex`,A5 换为 `asc_partial`),A5 默认追加 SwiGLUGroup、sparse attention、融合 LI 选分与 Sinkhorn,不重复传入 `--override.imports`。显式传 `--override.imports` 会替换整个集合,需自行包含所需的 RoPE 与 swap optimizer。最终选择随 Trainer Config 打印。
52 55 
53-普通运行不强制随机种子和确定性;精度对照须在双方命令中追加 `--debug.seed 42 --debug.deterministic`。默认关闭 checkpoint 且设置 `load_only=True`;保存时同时传 `--checkpoint.enable --checkpoint.no-load-only`。`load_only` 表示禁止保存,与 model-only 加载不同。tokenizer 统一经 `--hf-assets-path` 提供(测试可用仓内 `tests/assets/deepseek_v3` mini tokenizer),该参数本身不加载模型权重。56+普通运行不强制随机种子和确定性;精度对照须在双方命令中追加 `--debug.seed 42 --debug.deterministic`。debug recipe 默认使用 `checkpointer=None`,不加载或保存 checkpoint;需要加载或保存时,在 Python recipe 中显式设置 checkpointer 后,再通过 CLI 覆盖其普通字段。`load_only` 表示禁止保存,与 model-only 加载不同。tokenizer 统一经 `--hf-assets-path` 提供(测试可用仓内 `tests/assets/deepseek_v3` mini tokenizer),该参数本身不加载模型权重。
54 57 
55indexer 的训练目标没有独立的损失项,它只走 A5 两个融合算子的反向夹具:`sparse_attn.asc` 的 SMLAG 反向按每个选中条目产出该层 attention 自身完整 softmax(窗口 + 压缩条目 + sink)的边际质量 `p`,写在 `topk_scores` 的梯度上;`lightning_indexer.asc` 的 SLIKG 反向把它当作教师,由 kernel 施加 `dI = Z·Y - p` 并产出 indexer 的 `q`/`k`/`w` 梯度。`topk_scores` 不参与任务损失,除这条边之外没有消费者,因此**A5 的两个 override 必须同开**:模型构造时按配置类标记检查这一对,只开一个直接报 `ValueError`,不会进入训练。单开 LI 时该梯度为 `None`、SLIKG 反向返回零梯度,indexer 全程不更新;单开 sparse attention 时 reference selector 会把 attention 级别的边际质量加到按 head 求和的 logits 上,训练信号是错的(该组合不做修复,仅由构造期检查拦住)。未使用的 top-k 槽位(`-1`)在教师上被置零。完整契约与 CPU 验证范围见 [override 说明](../../torchtitan_npu/override/README.md#deepseek-v41)。58indexer 的训练目标没有独立的损失项,它只走 A5 两个融合算子的反向夹具:`sparse_attn.asc` 的 SMLAG 反向按每个选中条目产出该层 attention 自身完整 softmax(窗口 + 压缩条目 + sink)的边际质量 `p`,写在 `topk_scores` 的梯度上;`lightning_indexer.asc` 的 SLIKG 反向把它当作教师,由 kernel 施加 `dI = Z·Y - p` 并产出 indexer 的 `q`/`k`/`w` 梯度。`topk_scores` 不参与任务损失,除这条边之外没有消费者,因此**A5 的两个 override 必须同开**:模型构造时按配置类标记检查这一对,只开一个直接报 `ValueError`,不会进入训练。单开 LI 时该梯度为 `None`、SLIKG 反向返回零梯度,indexer 全程不更新;单开 sparse attention 时 reference selector 会把 attention 级别的边际质量加到按 head 求和的 logits 上,训练信号是错的(该组合不做修复,仅由构造期检查拦住)。未使用的 top-k 槽位(`-1`)在教师上被置零。完整契约与 CPU 验证范围见 [override 说明](../../torchtitan_npu/override/README.md#deepseek-v41)。
56 59 
57### Flash 完整主干多机训练60### Flash 完整主干多机训练
58 61 
59-`CONFIG=deepseek_v4_1_flash`,参数对齐 [HF 官方配置](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/main/config.json):40 层、隐藏维度 5120、384 个路由专家、1 个共享专家、top-6、MoE 中间维度 2304;attention 64 heads × 512、Q/O LoRA 1280/1024;ViT 32 层、维度 1024、16 heads、MLP 2816。Engram 位于第 1/14 层,逻辑表行数 384006168/384016682,沿用仓内 Host 存储和 2048 行对齐。训练长度默认为 4096;模型配置保留官方的最大位置范围 1048576,运行时按训练长度准备 RoPE。62+`CONFIG=deepseek_v4_1_flash_cpt`,参数对齐 [HF 官方配置](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash/blob/main/config.json):40 层、隐藏维度 5120、384 个路由专家、1 个共享专家、top-6、MoE 中间维度 2304;attention 64 heads × 512、Q/O LoRA 1280/1024;ViT 32 层、维度 1024、16 heads、MLP 2816。Engram 位于第 1/14 层,逻辑表行数 384006168/384016682,沿用仓内 Host 存储和 2048 行对齐。训练长度默认为 4096;模型配置保留官方的最大位置范围 1048576,运行时按训练长度准备 RoPE。
60 63 
61这里的“完整”指非裁剪的文本主干、ViT 和 Engram。HF 额外的 3 层 MTP 和 DSpark 尚未实现,本入口不代表完整 HF 训练目标均已支持;HF 的 FP8/FP4 权重发布格式也不等于本入口的训练量化配方。64这里的“完整”指非裁剪的文本主干、ViT 和 Engram。HF 额外的 3 层 MTP 和 DSpark 尚未实现,本入口不代表完整 HF 训练目标均已支持;HF 的 FP8/FP4 权重发布格式也不等于本入口的训练量化配方。
62 65 
@@ -73,15 +76,15 @@ A5 默认每机 8 卡、EP128/FSDP128、TP1/CP1/PP1、每 rank microbatch 4096 t
73 76 
74`NGPU`、`EP`、`DP_SHARD`、`STEPS` 可通过环境变量设置;`NODE_IPS` 必填。总卡数须能被 EP 和 DP_SHARD 整除,EP 须兼容 384 专家。CLI 参数放在最后,可覆盖训练配置;修改拓扑请优先使用上述环境变量,保证派生的 DP_REPLICATE 一致。Host Engram 需要正确的 tokenizer 压缩映射与足够主机内存。77`NGPU`、`EP`、`DP_SHARD`、`STEPS` 可通过环境变量设置;`NODE_IPS` 必填。总卡数须能被 EP 和 DP_SHARD 整除,EP 须兼容 384 专家。CLI 参数放在最后,可覆盖训练配置;修改拓扑请优先使用上述环境变量,保证派生的 DP_REPLICATE 一致。Host Engram 需要正确的 tokenizer 压缩映射与足够主机内存。
75 78 
76-初始权重不会因设置 `HF_ASSETS_PATH` 自动加载:需要时设置 `CKPT_INIT_LOAD_PATH` 指向 HF checkpoint;保存 checkpoint 另加 `--checkpoint.no-load-only`。默认不启用参数/梯度 CPU offload,保留 `swap_optimizer` 对 Engram 的适配。`USE_GOLDEN=1` 切换 reference override;A5 若还要关闭量化,追加 `--extension.quantization.no-enable-quantized-training`。79+初始权重不会因设置 `HF_ASSETS_PATH` 自动加载:需要时设置 `CKPT_INIT_LOAD_PATH` 指向 HF checkpoint;保存 checkpoint 另加 `--checkpointer.no-load-only`。默认不启用参数/梯度 CPU offload,保留 `swap_optimizer` 对 Engram 的适配。`USE_GOLDEN=1` 切换 reference override;A5 若还要关闭量化,追加 `--extension.quantization.no-enable-quantized-training`。
77 80 
78### Checkpoint 加载范围81### Checkpoint 加载范围
79 82 
80以下为追加到训练命令末尾的标准 CLI 参数:83以下为追加到训练命令末尾的标准 CLI 参数:
81 84 
82-- 原生 DCP 完整续训:`--checkpoint.enable --checkpoint.initial-load-path /path/to/dcp/step-N --checkpoint.no-initial-load-in-hf --checkpoint.no-initial-load-in-hf-quantized --checkpoint.no-initial-load-model-only`。恢复模型、优化器和训练状态;并行布局与原 checkpoint 保持兼容。85+- 原生 DCP 完整续训:`--checkpointer.initial-load-path /path/to/dcp/step-N --checkpointer.no-initial-load-in-hf --checkpointer.no-initial-load-in-hf-quantized --checkpointer.no-initial-load-model-only`。恢复模型、优化器和训练状态;并行布局与原 checkpoint 保持兼容。
83-- 普通 HF 权重初始化:`--checkpoint.enable --checkpoint.initial-load-path /path/to/hf --checkpoint.initial-load-in-hf --checkpoint.no-initial-load-in-hf-quantized --checkpoint.initial-load-model-only`。只加载模型权重,优化器重新初始化。86+- 普通 HF 权重初始化:`--checkpointer.initial-load-path /path/to/hf --checkpointer.initial-load-in-hf --checkpointer.no-initial-load-in-hf-quantized --checkpointer.initial-load-model-only`。只加载模型权重,优化器重新初始化。
84-- 输入包含官方格式的 Engram MXFP8 权重时,在 HF 初始化参数上追加 `--checkpoint.initial-load-in-hf-quantized`,按 row/block scale 反量化到训练参数。该选项描述输入 checkpoint 格式,与训练时是否启用 Engram MXFP8 算子相互独立。87+- 输入包含官方格式的 Engram MXFP8 权重时,在 HF 初始化参数上追加 `--checkpointer.initial-load-in-hf-quantized`,按 row/block scale 反量化到训练参数。该选项描述输入 checkpoint 格式,与训练时是否启用 Engram MXFP8 算子相互独立。
85 88 
86Engram HF 表以全局逻辑行保存,不包含本地 padding,支持 EP 分片和 EP × EFSDP 联合分片的权重导入导出;离线 DCP 转 HF 同样支持这两种表布局。这不包含原生优化器状态在不同分片布局之间的自动迁移。89Engram HF 表以全局逻辑行保存,不包含本地 padding,支持 EP 分片和 EP × EFSDP 联合分片的权重导入导出;离线 DCP 转 HF 同样支持这两种表布局。这不包含原生优化器状态在不同分片布局之间的自动迁移。
87 90 
@@ -177,25 +180,41 @@ encoder 只调用模型目录 `encoding/encoding.py` 的 `encode_messages` 公
177 180 
178### 相同初始权重(生成与加载)181### 相同初始权重(生成与加载)
179 182 
180-baseline 与融合组要从同一份显式权重出发时,先生成再加载(dcp 格式,model-only):183+baseline 与融合组要从同一份显式权重出发时,先在仓库根目录的 `my_recipes.py` 中启用 checkpoint:
184+ 
185+```python
186+from torchtitan.components.checkpointer import CheckpointManager
187+from torchtitan_npu.models.deepseek_v4_1.config_registry import (
188+ deepseek_v4_1_flash_40layers_16experts_multimodal_compiled,
189+)
190+ 
191+ 
192+def debug_checkpoint():
193+ config = deepseek_v4_1_flash_40layers_16experts_multimodal_compiled()
194+ config.checkpointer = CheckpointManager.Config(load_only=True)
195+ return config
196+```
197+ 
198+然后先生成再加载(DCP 格式,model-only):
181 199 
182```sh200```sh
183# 生成:跑 3 步保存训练 checkpoint(后续仅加载其中的模型权重)201# 生成:跑 3 步保存训练 checkpoint(后续仅加载其中的模型权重)
202+MODULE=my_recipes CONFIG=debug_checkpoint \
184bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \203bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
185 --hf-assets-path <v41_tokenizer_dir> \204 --hf-assets-path <v41_tokenizer_dir> \
186- --training.steps 3 --lr-scheduler.total-steps 3 --lr-scheduler.warmup-steps 2 \205+ --training.steps 3 --optim.lr-scheduler.total-steps 3 --optim.lr-scheduler.warmup-steps 2 \
187- --checkpoint.enable --checkpoint.no-load-only \206+ --checkpointer.no-load-only \
188- --checkpoint.folder <ckpt_dir>207+ --checkpointer.folder <ckpt_dir>
189 208 
190-# 加载同一份权重起跑(--checkpoint.load-only 禁用后续保存)209+# 加载同一份权重起跑(--checkpointer.load-only 禁用后续保存)
210+MODULE=my_recipes CONFIG=debug_checkpoint \
191bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \211bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
192 --hf-assets-path <v41_tokenizer_dir> \212 --hf-assets-path <v41_tokenizer_dir> \
193- --checkpoint.enable \213+ --checkpointer.initial-load-path <ckpt_dir>/step-3 \
194- --checkpoint.initial-load-path <ckpt_dir>/step-3 \214+ --checkpointer.initial-load-model-only
195- --checkpoint.initial-load-model-only
196```215```
197 216 
198-两个要点:`--checkpoint.enable` 是加载生效的前提(不传时 CheckpointManager 未激活,会静默 fresh start,日志中只有一条 warning);`initial-load-path` 指向 `step-N` 子目录。输出 `checkpoint.folder` 中已有有效 checkpoint 时会优先恢复它;从 `initial-load-path` 起跑应使用新的输出目录。加载后应核对 checkpoint 日志与实际数据配置,再比较训练轨迹;单凭首步 loss 接近不能证明权重和数据一致。217+`checkpointer=None` 表示关闭;启用或关闭均在 recipe 中设置。嵌套 CLI 参数只覆盖已存在的配置,不再从 `None` 自动创建组件。编译的 `components=[]` 也在 recipe 中设置。`initial-load-path` 指向 `step-N` 子目录。输出 `checkpointer.folder` 中已有有效 checkpoint 时会优先恢复它;从 `initial-load-path` 起跑应使用新的输出目录。加载后应核对 checkpoint 日志与实际数据配置,再比较训练轨迹;单凭首步 loss 接近不能证明权重和数据一致。
199 218 
200### 融合算子逐项说明219### 融合算子逐项说明
201 220 
@@ -209,7 +228,7 @@ bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
209| `common.rope.asc_half_rotation` | 视觉塔 2D 位置表的 half 旋转(半宽 cos/sin,融合前复制为全宽表,逐 batch 折叠保位置) | 同上 |228| `common.rope.asc_half_rotation` | 视觉塔 2D 位置表的 half 旋转(半宽 cos/sin,融合前复制为全宽表,逐 batch 折叠保位置) | 同上 |
210| `sparse_attn.asc`(仅 A5,须与下一行同开) | 替换完整 attention forward;反向除自身梯度外还在 `topk_scores` 梯度上产出 indexer 教师。该 config 按**自己的几何**(每个 `(端口, compress_ratio)` 一个 map entry)每微批预计算 SMLA 与 indexer 元数据(`sparse_flash_mla_metadata` / `sparse_flash_mla_grad_metadata` / `lightning_indexer_metadata` / `sparse_lightning_indexer_kl_loss_grad_metadata`),随 entry 的 `aicpu_metadata` 字段下发,前向/重算/反向直接读字段(没有查表)。几何即该 config 自己的必填字段(无默认值),由该入口的五个参数一次写入,默认值即 V4.1-Flash 的发布形状;记录是内核 metadata 的唯一来源:拿着没经过端口构建的 metadata 前向会直接失败,不会在层里补一次算子调用(没有 inline 回退) | Ascend sparse flash MLA + CANN `*_metadata` |229| `sparse_attn.asc`(仅 A5,须与下一行同开) | 替换完整 attention forward;反向除自身梯度外还在 `topk_scores` 梯度上产出 indexer 教师。该 config 按**自己的几何**(每个 `(端口, compress_ratio)` 一个 map entry)每微批预计算 SMLA 与 indexer 元数据(`sparse_flash_mla_metadata` / `sparse_flash_mla_grad_metadata` / `lightning_indexer_metadata` / `sparse_lightning_indexer_kl_loss_grad_metadata`),随 entry 的 `aicpu_metadata` 字段下发,前向/重算/反向直接读字段(没有查表)。几何即该 config 自己的必填字段(无默认值),由该入口的五个参数一次写入,默认值即 V4.1-Flash 的发布形状;记录是内核 metadata 的唯一来源:拿着没经过端口构建的 metadata 前向会直接失败,不会在层里补一次算子调用(没有 inline 回退) | Ascend sparse flash MLA + CANN `*_metadata` |
211| `lightning_indexer.asc`(仅 A5,须与上一行同开) | 替换 selector 节点 | CANN `lightning_indexer` + `sparse_lightning_indexer_kl_loss_grad` |230| `lightning_indexer.asc`(仅 A5,须与上一行同开) | 替换 selector 节点 | CANN `lightning_indexer` + `sparse_lightning_indexer_kl_loss_grad` |
212-| `common.swiglu_group.asc`(仅 A5) | `*.moe.routed_experts.inner_experts` 的 grouped SwiGLU(FQN 限定) | cann_ops_nn.swiglu_group |231+| `common.swiglu_group.asc`(仅 A5) | `*.moe.routed_experts.activation_fn` 的 SwiGLU | cann_ops_nn.swiglu_group |
213| `common.swiglu_group.asc_shared_experts`(仅 A5) | `*.moe.shared_experts` 的 SwiGLU(FQN 限定,不替换视觉 MLP) | 同上 |232| `common.swiglu_group.asc_shared_experts`(仅 A5) | `*.moe.shared_experts` 的 SwiGLU(FQN 限定,不替换视觉 MLP) | 同上 |
214| `common.token_dispatcher.asc` | 公共 MoE 的 permute / re-routing / unpermute;reference 不启用 | Ascend token dispatcher |233| `common.token_dispatcher.asc` | 公共 MoE 的 permute / re-routing / unpermute;reference 不启用 | Ascend token dispatcher |
215| `mhc.asc_hc_post` | mHC post 变换 | Ascend mHC post |234| `mhc.asc_hc_post` | mHC post 变换 | Ascend mHC post |
@@ -217,7 +236,7 @@ bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
217 236 
218量化路径不是这两个 override 的包装,而是另一个 backend:开启 `--extension.quantization.enable-sparse-attention-quantization` 后,量化后的 sparse attention(`torchao_npu` 里 fused attention 的拷贝)由 converter 安装,它自己构建 entry 的四份 metadata(含量化 selector 的两条 schedule),因此 `sparse_attn.asc` 在该路径上不生效;`--extension.quantization.li-quantization mxfp4` 必须与该开关同时开启,否则非量化 attention 的 BF16 schedule 会被量化 kernel 读到(垃圾索引,kernel 可能崩),converter 会直接报错。非量化路径的 `lightning_indexer.fwd_sparse` / `.sparse_length` 当前留空,等带 candidate 的非量化算子落地后由 port 填。237量化路径不是这两个 override 的包装,而是另一个 backend:开启 `--extension.quantization.enable-sparse-attention-quantization` 后,量化后的 sparse attention(`torchao_npu` 里 fused attention 的拷贝)由 converter 安装,它自己构建 entry 的四份 metadata(含量化 selector 的两条 schedule),因此 `sparse_attn.asc` 在该路径上不生效;`--extension.quantization.li-quantization mxfp4` 必须与该开关同时开启,否则非量化 attention 的 BF16 schedule 会被量化 kernel 读到(垃圾索引,kernel 可能崩),converter 会直接报错。非量化路径的 `lightning_indexer.fwd_sparse` / `.sparse_length` 当前留空,等带 candidate 的非量化算子落地后由 port 填。
219 238 
220-routed experts 已走公共 grouped GEMM(`_ClampGroupedExperts` → 仓内 NPU `_grouped_mm`),reference 与融合共用,不改变模型参数名称、FSDP/EP 或 checkpoint 格式。融合输出、输入/权重梯度与训练轨迹的误差需与迁移后同配置 reference 对照验收;仅运行成功不代表数值或性能验收完成。239+routed experts 使用独立的 `GroupedLinear.Config`:`w13` 保存 gate/up 投影,`w2` 保存 down 投影。融合 override 仅替换 `activation_fn`,保留分组矩阵乘和 dispatcher;路由分数在激活后、`w2` 前单独乘入。参数名现为 `routed_experts.w13.weight` 和 `routed_experts.w2.weight`。融合输出、输入/权重梯度与训练轨迹的误差需与迁移后同配置 reference 对照验收;仅运行成功不代表数值或性能验收完成。
221 240 
222### RoPE seam 说明241### RoPE seam 说明
223 242 
@@ -227,7 +246,7 @@ CPU 测试覆盖两类 seam 的输出/梯度、partial 非连续输入、逐 bat
227 246 
228### Muon 优化器注意事项247### Muon 优化器注意事项
229 248 
230-`--optimizer.name Muon` 启用 DistMuon 时,`materialize()` 会整体替换 `param_groups` 为 `[DistMuon(pattern), AdamW(.*)]`,launcher 传入的 `--optimizer.param-groups.0.*` 参数静默失效。学习率等超参请使用顶层字段:`--optimizer.lr`、`--optimizer.weight-decay`、`--optimizer.muon-momentum` 等。indexer 参数在 LI 下有梯度,但仍留在 AdamW fallback 组,不因迁移改变参数策略。249+`--optim.optimizer.name Muon` 启用 DistMuon 时,`materialize()` 会整体替换 `optimizers` 为 `[DistMuon(pattern), AdamW(.*)]`,launcher 传入的 `--optim.optimizer.optimizers.0.*` 参数静默失效。学习率等超参请使用顶层字段:`--optim.optimizer.lr`、`--optim.optimizer.weight-decay`、`--optim.optimizer.muon-momentum` 等。indexer 参数在 LI 下有梯度,但仍留在 AdamW fallback 组,不因迁移改变参数策略。
231 250 
232### 验证范围251### 验证范围
233 252 
@@ -22,16 +22,15 @@ CONFIG="${CONFIG:-qwen35_debugmodel}"
22# TORCHTITAN_DIR (exported by .ci/smoke_test.sh) or a sibling checkout22# TORCHTITAN_DIR (exported by .ci/smoke_test.sh) or a sibling checkout
23# provides the tokenizer and cc12m-test data.23# provides the tokenizer and cc12m-test data.
24TORCHTITAN_REPO="${TORCHTITAN_REPO:-${TORCHTITAN_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/../torchtitan}}"24TORCHTITAN_REPO="${TORCHTITAN_REPO:-${TORCHTITAN_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/../torchtitan}}"
25-DATASET="${DATASET:-cc12m-test}"
26DATASET_PATH="${DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test}" # your data path25DATASET_PATH="${DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test}" # your data path
27HF_ASSETS_PATH="${HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer}" # your tokenizer path26HF_ASSETS_PATH="${HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer}" # your tokenizer path
27+export QWEN_DATASET_PATH="${DATASET_PATH}"
28 28 
29# Training (smoke-sized defaults)29# Training (smoke-sized defaults)
30SEQ_LEN=51230SEQ_LEN=512
31MBS=131MBS=1
32GBS=132GBS=1
33STEPS=1033STEPS=10
34-SPMD_BACKEND="spmd_types"
35 34 
36# NPU overrides: the Triton GDN kernel is always imported; the MoE token35# NPU overrides: the Triton GDN kernel is always imported; the MoE token
37# dispatcher is a performance option enabled via ENABLE_NPU_MOE_DISPATCHER=1.36# dispatcher is a performance option enabled via ENABLE_NPU_MOE_DISPATCHER=1.
@@ -59,15 +58,10 @@ export DATASET DATASET_PATH
59 58 
60# Parallelism59# Parallelism
61PARALLELISM_ARGS="60PARALLELISM_ARGS="
62- --parallelism.spmd-backend ${SPMD_BACKEND}
63"61"
64 62 
65# Compile63# Compile
66-COMPILE_ARGS="64+COMPILE_ARGS=""
67- --compile.no_enable
68- --compile.components model
69- --compile.backend aot_eager
70-"
71 65 
72# Training66# Training
73TRAINING_ARGS="67TRAINING_ARGS="
@@ -23,9 +23,9 @@ CONFIG="${CONFIG:-qwen35_debugmodel_moe}"
23# TORCHTITAN_DIR (exported by .ci/smoke_test.sh) or a sibling checkout23# TORCHTITAN_DIR (exported by .ci/smoke_test.sh) or a sibling checkout
24# provides the tokenizer and cc12m-test data.24# provides the tokenizer and cc12m-test data.
25TORCHTITAN_REPO="${TORCHTITAN_REPO:-${TORCHTITAN_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/../torchtitan}}"25TORCHTITAN_REPO="${TORCHTITAN_REPO:-${TORCHTITAN_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)/../torchtitan}}"
26-DATASET="${DATASET:-cc12m-test}"
27DATASET_PATH="${DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test}" # your data path26DATASET_PATH="${DATASET_PATH:-${TORCHTITAN_REPO}/tests/assets/cc12m_test}" # your data path
28HF_ASSETS_PATH="${HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer}" # your tokenizer path27HF_ASSETS_PATH="${HF_ASSETS_PATH:-${TORCHTITAN_REPO}/tests/assets/tokenizer}" # your tokenizer path
28+export QWEN_DATASET_PATH="${DATASET_PATH}"
29 29 
30# Parallelism30# Parallelism
31TP=131TP=1
@@ -34,7 +34,6 @@ EP=8
34CP=134CP=1
35DP_SHARD=835DP_SHARD=8
36DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))36DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
37-SPMD_BACKEND="spmd_types"
38 37 
39# Training (smoke-sized defaults)38# Training (smoke-sized defaults)
40SEQ_LEN=51239SEQ_LEN=512
@@ -68,7 +67,6 @@ export DATASET DATASET_PATH
68 67 
69# Parallelism68# Parallelism
70PARALLELISM_ARGS="69PARALLELISM_ARGS="
71- --parallelism.spmd-backend ${SPMD_BACKEND}
72 --parallelism.data-parallel-shard-degree ${DP_SHARD}70 --parallelism.data-parallel-shard-degree ${DP_SHARD}
73 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}71 --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
74 --parallelism.expert-parallel-degree ${EP}72 --parallelism.expert-parallel-degree ${EP}
@@ -78,11 +76,7 @@ PARALLELISM_ARGS="
78"76"
79 77 
80# Compile78# Compile
81-COMPILE_ARGS="79+COMPILE_ARGS=""
82- --compile.no_enable
83- --compile.components model
84- --compile.backend aot_eager
85-"
86 80 
87# Training81# Training
88TRAINING_ARGS="82TRAINING_ARGS="
@@ -65,8 +65,10 @@ override,用于消融或定位问题。
65 65 
66数据和路径也可以覆盖:`HF_ASSETS_PATH` 默认为66数据和路径也可以覆盖:`HF_ASSETS_PATH` 默认为
67`${TORCHTITAN_REPO}/tests/assets/tokenizer`,`DATASET_PATH` 默认为67`${TORCHTITAN_REPO}/tests/assets/tokenizer`,`DATASET_PATH` 默认为
68-`${TORCHTITAN_REPO}/tests/assets/cc12m_test`。如需使用 torch.compile,可在68+`${TORCHTITAN_REPO}/tests/assets/cc12m_test`。如需使用 torch.compile,在 Python recipe 中显式设置
69-脚本中修改 `COMPILE_ARGS` 或通过 `COMPILE_BACKEND` 环境变量控制。69+`config.compile = CompileConfig(components=[], model=ModelCompileConfig())`,其中类型从
70+`torchtitan_npu.config` 导入;关闭编译设置 `config.compile = None`。通过 `MODULE` / `CONFIG`
71+选择该 recipe,CLI 不再从 `None` 自动创建组件。
70 72 
71示例(单机 8 卡 MoE):73示例(单机 8 卡 MoE):
72 74 
@@ -95,11 +97,10 @@ qwen3_5_debugmodel_1p_cpt_512.sh
95 └─ 进程组销毁97 └─ 进程组销毁
96```98```
97 99 
98-`spmd_types` 使用 TorchTitan v0.3 的 `resolve_fsdp_mesh`/100+固定的 TorchTitan 版本仅使用 `spmd_types`,launcher 不再接受 backend 选择。
99-`resolve_sparse_fsdp_mesh`,而旧 backend 保留 `fsdp/efsdp` 名称;因此同一套101+Qwen3.5 的长文本 CP 配方保留 CP=4 及 typed Ulysses 变换配置;当前固定上游的 Ulysses
100-parallelizer 可兼容当前主线和旧 NPU 运行环境。当前 Qwen3.5-VL 多模态视觉 mask102+实现要求 CUDA,NPU runtime 仍不受支持,启动时会明确拒绝。多模态 CP 的视觉元数据适配
101-尚未完成 CP 序列元数据适配;VL 配置启用 CP 时会在并行化入口明确失败,避免103+也尚未完成。配方构造和 CLI 解析通过不代表这些 CP 训练路径可运行。
102-运行到错误的 dict-mask 路径。纯文本长上下文配置仍可使用专用 CP recipe。
103 104 
104集成测试通过以下命令运行 Qwen3.5 的 1-rank 冒烟用例:105集成测试通过以下命令运行 Qwen3.5 的 1-rank 冒烟用例:
105 106 
@@ -6,7 +6,9 @@
6 6 
7set -euo pipefail7set -euo pipefail
8 8 
9-if [[ -f /usr/local/Ascend/cann/set_env.sh ]]; then9+if [[ -n "${ASCEND_SET_ENV_PATH:-}" ]]; then
10+ source "${ASCEND_SET_ENV_PATH}"
11+elif [[ -f /usr/local/Ascend/cann/set_env.sh ]]; then
10 source /usr/local/Ascend/cann/set_env.sh12 source /usr/local/Ascend/cann/set_env.sh
11elif [[ -f /usr/local/Ascend/ascend-toolkit/set_env.sh ]]; then13elif [[ -f /usr/local/Ascend/ascend-toolkit/set_env.sh ]]; then
12 source /usr/local/Ascend/ascend-toolkit/set_env.sh14 source /usr/local/Ascend/ascend-toolkit/set_env.sh
@@ -32,10 +34,9 @@ ARGS=(
32 --config qwen35_27b_4k_sft34 --config qwen35_27b_4k_sft
33 --hf-assets-path "${HF_ASSETS_PATH}"35 --hf-assets-path "${HF_ASSETS_PATH}"
34 --override.imports torchtitan_npu.override.qwen3_5.gated_delta.triton36 --override.imports torchtitan_npu.override.qwen3_5.gated_delta.triton
35- --checkpoint.enable37+ --checkpointer.initial-load-path "${CHECKPOINT_INITIAL_LOAD_PATH:-${HF_ASSETS_PATH}}"
36- --checkpoint.initial-load-path "${CHECKPOINT_INITIAL_LOAD_PATH:-${HF_ASSETS_PATH}}"38+ --checkpointer.initial-load-in-hf
37- --checkpoint.initial-load-in-hf39+ --checkpointer.initial-load-model-only
38- --checkpoint.initial-load-model-only
39 --dump-folder "${DUMP_FOLDER:-./outputs/qwen3_6_4k_sft}"40 --dump-folder "${DUMP_FOLDER:-./outputs/qwen3_6_4k_sft}"
40 --training.max-context-length "${SEQ_LEN}"41 --training.max-context-length "${SEQ_LEN}"
41 --training.num-tokens-per-microbatch-per-dp-rank "${SEQ_LEN}"42 --training.num-tokens-per-microbatch-per-dp-rank "${SEQ_LEN}"
@@ -8,10 +8,14 @@ version = "0.1.0"
8description = "Huawei Ascend NPU overrides for torchtitan"8description = "Huawei Ascend NPU overrides for torchtitan"
9requires-python = ">=3.12"9requires-python = ">=3.12"
10dependencies = [10dependencies = [
11- "torchtitan @ git+https://gitcode.com/GitHub_Trending/to/torchtitan.git@dc3985ad4912f67f71d5a125f2fdf40144ec8354",11+ "torchtitan @ git+https://gitcode.com/GitHub_Trending/to/torchtitan.git@ebdfc8c2a24d89d89c99c0ef96ed8ac149864175",
12 "torch-npu",12 "torch-npu",
13 "attn-gym==0.0.16",13 "attn-gym==0.0.16",
14 "torchvision",14 "torchvision",
15+ "grain==0.2.18",
16+ "renderers==0.1.11",
17+ "spmd_types==0.2.5",
18+ "torch_remat @ git+https://github.com/meta-pytorch/remat.git@d302699b1c58f83fa2c7b03bc2593967e9530335",
15]19]
16 20 
17[project.optional-dependencies]21[project.optional-dependencies]
@@ -30,6 +34,7 @@ include = ["torchtitan_npu*"]
30exclude = ["tests*", "CI*", "third_party*"]34exclude = ["tests*", "CI*", "third_party*"]
31 35 
32[tool.pytest.ini_options]36[tool.pytest.ini_options]
37+addopts = "--import-mode=importlib"
33pythonpath = ["."]38pythonpath = ["."]
34markers = [39markers = [
35 "cpu: CPU-only unit test",40 "cpu: CPU-only unit test",
@@ -6,8 +6,13 @@ pytest==8.3.2
6pytest-cov6pytest-cov
7pre-commit7pre-commit
8pyrefly==0.45.18pyrefly==0.45.1
9-transformers==4.57.69+# Match the DeepSeek-V4 reference used by the PEFT round-trip tests.
10+transformers==5.13.0
11+peft==0.21.2
10# Test dependencies12# Test dependencies
11einops13einops
12expecttest14expecttest
13tomli_w15tomli_w
16+# TorchFT 0.2.0 imports its OpenTelemetry logger at package import time.
17+opentelemetry-sdk
18+opentelemetry-exporter-otlp-proto-http
@@ -7,17 +7,19 @@ torch==2.14.0
7torchvision==0.29.07torchvision==0.29.0
8--find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torch-npu/index.html8--find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torch-npu/index.html
9torch_npu==2.14.0.dev202609189torch_npu==2.14.0.dev20260918
10-torchtitan @ git+https://gitcode.com/GitHub_Trending/to/torchtitan.git@dc3985ad4912f67f71d5a125f2fdf40144ec835410+torchtitan @ git+https://gitcode.com/GitHub_Trending/to/torchtitan.git@ebdfc8c2a24d89d89c99c0ef96ed8ac149864175
11+--extra-index-url https://triton-ascend.osinfra.cn/pypi/simple
12+triton-ascend==3.2.1
11attn-gym==0.0.1613attn-gym==0.0.16
12grain==0.2.1814grain==0.2.18
13pybind11==3.0.415pybind11==3.0.4
14numpy16numpy
15PyYAML17PyYAML
16ninja18ninja
17---extra-index-url https://triton-ascend.osinfra.cn/pypi/simple
18-triton-ascend==3.2.1
19scipy==1.13.119scipy==1.13.1
20safetensors==0.8.020safetensors==0.8.0
21-# Engram builds its token map at runtime; pin the normalizer semantics.
22tokenizers==0.23.221tokenizers==0.23.2
23torchao==0.17.022torchao==0.17.0
23+torch_checkpointing==0.1.1
24+ 
25+tyro>=1.0.5
@@ -97,13 +97,35 @@ HF 与 DCP 必须来自同一份权重。两种 attention 模式都要求 batch
97 97 
98```bash98```bash
99export HF_ASSETS_PATH=/path/to/tokenizer99export HF_ASSETS_PATH=/path/to/tokenizer
100-export CKPT_SAVE_LOAD_PATH=checkpoint
101-export USE_GOLDEN=1
102 100 
103# 比特一致对比:前后两个提交101# 比特一致对比:前后两个提交
104python scripts/numerical_alignment/loss_compare.py HEAD~1 HEAD102python scripts/numerical_alignment/loss_compare.py HEAD~1 HEAD
105```103```
106 104 
105+#### 比较上游适配前后的版本
106+ 
107+`93f956c` 依赖 TorchTitan `dc3985ad`,使用旧的 `checkpoint`、`optimizer` 配置;当前版本依赖 `ebdfc8c`,使用可选的 `checkpointer` 和嵌套 `optim`。通过 `--baseline-config-api legacy` 选择旧接口,test 侧默认使用 `native`。两侧均已使用 token 训练 API,无需设置 `--baseline-training-api legacy`。
108+ 
109+准备两个分别固定到上述 commit 的 TorchTitan 源码目录,使用同一套 CANN、PyTorch、torch-npu 与输入数据,从仓库根目录执行:
110+ 
111+```bash
112+export HF_ASSETS_PATH=/path/to/tokenizer
113+export OLD_TORCHTITAN=/path/to/torchtitan-dc3985ad
114+export NEW_TORCHTITAN=/path/to/torchtitan-ebdfc8c
115+export RUNNER=examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh
116+ 
117+python scripts/numerical_alignment/loss_compare.py 93f956c HEAD \
118+ --runner "$RUNNER" --steps 100 --seq-len 4096 \
119+ --baseline-config-api legacy --test-config-api native \
120+ --baseline-upstream "$OLD_TORCHTITAN" --test-upstream "$NEW_TORCHTITAN"
121+```
122+ 
123+DeepSeek-V4.1 使用 `examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh`。在 A5 上使用对应的 `_a5.sh` runner;两侧分别读取各自 commit 中的脚本。运行前按实际设备配置 `ASCEND_RT_VISIBLE_DEVICES` 和编译缓存路径。
124+ 
125+脚本从旧侧生成一份 FP32、仅模型的 seed DCP,两侧从该文件加载权重,并使用各自的空 checkpoint 输出目录,避免恢复其他训练状态。默认清理 seed DCP 和临时 worktree,保留 `seed.log`、两侧训练日志、TensorBoard 事件及 `comparison.json`。native 侧使用本工具的训练入口设置可选 checkpointer,不能同时指定自定义 `TRAIN_FILE`。
126+ 
127+短训练只能验证启动、前反向、更新和比较流程;精度验收仍需完整运行 100 步。指标不一致时返回 `1`,以报告中的逐项结果判定,不把「两侧训练完成」作为精度通过。
128+ 
107#### 数值近似对比129#### 数值近似对比
108 130 
109同一提交下比较 Golden 实现与融合算子,只需覆盖 test 的环境变量:131同一提交下比较 Golden 实现与融合算子,只需覆盖 test 的环境变量:
@@ -26,6 +26,10 @@ TensorBoard 读取每个 step 的 loss 和 grad_norm → 按 bitwise 或 close
26`--no-seed-checkpoint` 可跳过共享 checkpoint。26`--no-seed-checkpoint` 可跳过共享 checkpoint。
27旧版本可使用 `--baseline-training-api legacy`,将 baseline 的长度参数改为 `--training.seq-len`。27旧版本可使用 `--baseline-training-api legacy`,将 baseline 的长度参数改为 `--training.seq-len`。
28`--baseline-upstream` / `--test-upstream` 分别指定独立的 TorchTitan 源码目录。28`--baseline-upstream` / `--test-upstream` 分别指定独立的 TorchTitan 源码目录。
29+checkpoint 配置接口通过 `--baseline-config-api` / `--test-config-api` 独立选择:
30+默认 `native` 对应可选 checkpointer 与嵌套 optim;`legacy` 对应旧 checkpoint 与 optimizer。
31+对比 `93f956c HEAD` 时使用 `--baseline-config-api legacy`,两侧训练长度 API 均保持默认 tokens。
32+native 侧由本工具的训练入口构造 DCP checkpointer,不修改模型 recipe;不支持自定义 TRAIN_FILE。
29 33 
30用法示例:34用法示例:
31 35 
@@ -329,6 +333,7 @@ def build_seed_command(
329 deterministic: bool = True,333 deterministic: bool = True,
330 seq_len: int = DEFAULT_SEQ_LEN,334 seq_len: int = DEFAULT_SEQ_LEN,
331 training_api: str = "tokens",335 training_api: str = "tokens",
336+ config_api: str = "native",
332) -> list[str]:337) -> list[str]:
333 # Seed creation skips parallelize_fn but still builds an optimizer. Use338 # Seed creation skips parallelize_fn but still builds an optimizer. Use
334 # AdamW here because DistMuon requires DTensor parameters. Only model339 # AdamW here because DistMuon requires DTensor parameters. Only model
@@ -336,12 +341,23 @@ def build_seed_command(
336 return [341 return [
337 str(runner),342 str(runner),
338 f"--dump_folder={dump_folder}",343 f"--dump_folder={dump_folder}",
339- "--checkpoint.create_seed_checkpoint",344+ *(
340- "--checkpoint.enable",345+ [
341- "--checkpoint.no-load-only",346+ "--comparison-create-seed-checkpoint",
342- f"--checkpoint.folder={dump_folder / 'checkpoint'}",347+ f"--comparison-checkpoint-folder={dump_folder / 'checkpoint'}",
343- "--checkpoint.last-save-model-only",348+ "--optim.optimizer.name=AdamW",
344- "--optimizer.name=AdamW",349+ ]
350+ if config_api == "native"
351+ else [
352+ "--checkpoint.create_seed_checkpoint",
353+ "--checkpoint.enable",
354+ "--checkpoint.no-load-only",
355+ f"--checkpoint.folder={dump_folder / 'checkpoint'}",
356+ "--checkpoint.last-save-model-only",
357+ "--checkpoint.export-dtype=float32",
358+ "--optimizer.name=AdamW",
359+ ]
360+ ),
345 "--parallelism.data-parallel-replicate-degree=1",361 "--parallelism.data-parallel-replicate-degree=1",
346 "--parallelism.data-parallel-shard-degree=1",362 "--parallelism.data-parallel-shard-degree=1",
347 "--parallelism.tensor-parallel-degree=1",363 "--parallelism.tensor-parallel-degree=1",
@@ -362,6 +378,7 @@ def build_training_command(
362 deterministic: bool = True,378 deterministic: bool = True,
363 seq_len: int = DEFAULT_SEQ_LEN,379 seq_len: int = DEFAULT_SEQ_LEN,
364 training_api: str = "tokens",380 training_api: str = "tokens",
381+ config_api: str = "native",
365) -> list[str]:382) -> list[str]:
366 command = [383 command = [
367 str(runner),384 str(runner),
@@ -373,10 +390,13 @@ def build_training_command(
373 ]390 ]
374 if seed_checkpoint is not None:391 if seed_checkpoint is not None:
375 command.extend(392 command.extend(
376- [393+ [f"--comparison-initial-load-path={seed_checkpoint}"]
394+ if config_api == "native"
395+ else [
377 "--checkpoint.enable",396 "--checkpoint.enable",
378 "--checkpoint.load_only",397 "--checkpoint.load_only",
379- "--checkpoint.export_dtype=bfloat16",398+ "--checkpoint.initial-load-model-only",
399+ f"--checkpoint.folder={dump_folder / 'checkpoint'}",
380 f"--checkpoint.initial_load_path={seed_checkpoint}",400 f"--checkpoint.initial_load_path={seed_checkpoint}",
381 ]401 ]
382 )402 )
@@ -459,16 +479,31 @@ def run_with_realtime_output(
459 479 
460 480 
461def training_env(481def training_env(
462- ngpus: int | None, extra_env: Mapping[str, str] | None = None, *, upstream: Path | None = None482+ ngpus: int | None,
483+ extra_env: Mapping[str, str] | None = None,
484+ *,
485+ upstream: Path | None = None,
486+ repo_root: Path | None = None,
487+ config_api: str | None = None,
463) -> dict[str, str]:488) -> dict[str, str]:
489+ if upstream is not None and not (upstream / "torchtitan" / "__init__.py").is_file():
490+ raise ValueError(f"TorchTitan source root does not contain torchtitan/__init__.py: {upstream}")
464 env = os.environ.copy()491 env = os.environ.copy()
465 env["PYTHONUNBUFFERED"] = "1"492 env["PYTHONUNBUFFERED"] = "1"
466 if extra_env:493 if extra_env:
467 env.update(extra_env)494 env.update(extra_env)
468 if ngpus is not None:495 if ngpus is not None:
469 env["NGPU"] = str(ngpus)496 env["NGPU"] = str(ngpus)
470- if upstream is not None:497+ roots = [str(root.resolve()) for root in (repo_root, upstream) if root is not None]
471- env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(upstream.resolve()), env.get("PYTHONPATH", ""))))498+ if roots:
499+ env["PYTHONPATH"] = os.pathsep.join(filter(None, (*roots, env.get("PYTHONPATH", ""))))
500+ if config_api == "native":
501+ if env.get("TRAIN_FILE") not in (None, "torchtitan_npu.train", "scripts.numerical_alignment.train"):
502+ raise ValueError(
503+ "native comparison requires TRAIN_FILE=scripts.numerical_alignment.train; "
504+ "unset the custom TRAIN_FILE or select the legacy config API"
505+ )
506+ env["TRAIN_FILE"] = "scripts.numerical_alignment.train"
472 return env507 return env
473 508 
474 509 
@@ -808,6 +843,13 @@ def parse_args() -> argparse.Namespace:
808 "(default: enabled; --no-cleanup-after-test keeps all artifacts)",843 "(default: enabled; --no-cleanup-after-test keeps all artifacts)",
809 )844 )
810 for side in ("baseline", "test"):845 for side in ("baseline", "test"):
846+ parser.add_argument(
847+ f"--{side}-config-api",
848+ choices=("legacy", "native"),
849+ default="native",
850+ help="trainer control API: legacy checkpoint/optimizer (dc3985ad), or native "
851+ "optional checkpointer/optim (ebdfc8c, default); independent of the sequence-length API",
852+ )
811 parser.add_argument(853 parser.add_argument(
812 f"--{side}-training-api",854 f"--{side}-training-api",
813 choices=("legacy", "tokens"),855 choices=("legacy", "tokens"),
@@ -930,6 +972,20 @@ def main() -> None:
930 add_worktree(repo_root, test_worktree, test_commit)972 add_worktree(repo_root, test_worktree, test_commit)
931 added_worktrees.append(test_worktree)973 added_worktrees.append(test_worktree)
932 log_success("Git worktrees are ready")974 log_success("Git worktrees are ready")
975+ baseline_env = training_env(
976+ base_n,
977+ _merged_env(args.baseline_env),
978+ upstream=args.baseline_upstream,
979+ repo_root=baseline_worktree,
980+ config_api=args.baseline_config_api,
981+ )
982+ test_env = training_env(
983+ test_n,
984+ _merged_env(args.test_env),
985+ upstream=args.test_upstream,
986+ repo_root=test_worktree,
987+ config_api=args.test_config_api,
988+ )
933 baseline_runner = resolve_runner(989 baseline_runner = resolve_runner(
934 repo_root if args.baseline_runner is not None else baseline_worktree,990 repo_root if args.baseline_runner is not None else baseline_worktree,
935 args.baseline_runner or args.runner,991 args.baseline_runner or args.runner,
@@ -973,10 +1029,17 @@ def main() -> None:
973 deterministic=not args.no_deterministic,1029 deterministic=not args.no_deterministic,
974 seq_len=args.seq_len,1030 seq_len=args.seq_len,
975 training_api=args.baseline_training_api,1031 training_api=args.baseline_training_api,
1032+ config_api=args.baseline_config_api,
976 ),1033 ),
977 cwd=baseline_worktree,1034 cwd=baseline_worktree,
978- env=training_env(1, _merged_env(args.baseline_env), upstream=args.baseline_upstream),1035+ env=training_env(
979- log_file=seed_dump / "training.log",1036+ 1,
1037+ _merged_env(args.baseline_env),
1038+ upstream=args.baseline_upstream,
1039+ repo_root=baseline_worktree,
1040+ config_api=args.baseline_config_api,
1041+ ),
1042+ log_file=output_dir / "seed.log",
980 )1043 )
981 seed_checkpoint = seed_dump / "checkpoint" / "step-0"1044 seed_checkpoint = seed_dump / "checkpoint" / "step-0"
982 if not seed_checkpoint.is_dir():1045 if not seed_checkpoint.is_dir():
@@ -994,6 +1057,7 @@ def main() -> None:
994 steps=args.steps,1057 steps=args.steps,
995 options=args.baseline_options,1058 options=args.baseline_options,
996 training_api=args.baseline_training_api,1059 training_api=args.baseline_training_api,
1060+ config_api=args.baseline_config_api,
997 seed_checkpoint=seed_checkpoint,1061 seed_checkpoint=seed_checkpoint,
998 deterministic=not args.no_deterministic,1062 deterministic=not args.no_deterministic,
999 seq_len=args.seq_len,1063 seq_len=args.seq_len,
@@ -1020,6 +1084,7 @@ def main() -> None:
1020 steps=args.steps,1084 steps=args.steps,
1021 options=args.test_options,1085 options=args.test_options,
1022 training_api=args.test_training_api,1086 training_api=args.test_training_api,
1087+ config_api=args.test_config_api,
1023 seed_checkpoint=seed_checkpoint,1088 seed_checkpoint=seed_checkpoint,
1024 deterministic=not args.no_deterministic,1089 deterministic=not args.no_deterministic,
1025 seq_len=args.seq_len,1090 seq_len=args.seq_len,
@@ -1065,6 +1130,7 @@ def main() -> None:
1065 runtime_options={1130 runtime_options={
1066 side: {1131 side: {
1067 "training_api": getattr(args, f"{side}_training_api"),1132 "training_api": getattr(args, f"{side}_training_api"),
1133+ "config_api": getattr(args, f"{side}_config_api"),
1068 "upstream": str(getattr(args, f"{side}_upstream")) if getattr(args, f"{side}_upstream") else None,1134 "upstream": str(getattr(args, f"{side}_upstream")) if getattr(args, f"{side}_upstream") else None,
1069 "options": getattr(args, f"{side}_options"),1135 "options": getattr(args, f"{side}_options"),
1070 }1136 }
@@ -0,0 +1,107 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+# SPDX-License-Identifier: BSD-3-Clause
3+ 
4+"""Native Trainer entry point for shared DCP seed creation and loading.
5+ 
6+Selected by loss_compare via TRAIN_FILE. The ordinary example runner still
7+selects the model, optimizer, overrides, parallelism and training configuration.
8+Optional checkpointers and the suppressed seed field are set after CLI parsing.
9+"""
10+ 
11+from __future__ import annotations
12+ 
13+import argparse
14+import logging
15+import os
16+from dataclasses import replace
17+from pathlib import Path
18+ 
19+ 
20+def main() -> None:
21+ if Path(__file__).resolve().parents[2] != Path.cwd().resolve():
22+ raise ValueError("comparison entry point must run from its own selected repository root")
23+ parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False)
24+ parser.add_argument("--comparison-create-seed-checkpoint", action="store_true")
25+ parser.add_argument("--comparison-checkpoint-folder", type=Path)
26+ parser.add_argument("--comparison-initial-load-path", type=Path)
27+ controls, training_args = parser.parse_known_args()
28+ if controls.comparison_create_seed_checkpoint and controls.comparison_initial_load_path:
29+ parser.error("seed creation and initial checkpoint loading are mutually exclusive")
30+ 
31+ import torch.distributed as dist
32+ from torchtitan.config import ConfigManager
33+ from torchtitan.observability import structured_logger as sl
34+ from torchtitan.observability.logging import init_logger
35+ 
36+ import torchtitan_npu
37+ 
38+ init_logger()
39+ logger = logging.getLogger(__name__)
40+ config = ConfigManager().parse_args(training_args)
41+ if controls.comparison_create_seed_checkpoint or controls.comparison_initial_load_path:
42+ from torchtitan.components.checkpointer import CheckpointManager
43+ 
44+ checkpointer = config.checkpointer or CheckpointManager.Config()
45+ if not isinstance(checkpointer, CheckpointManager.Config):
46+ raise ValueError("shared comparison checkpoints require a DCP checkpointer")
47+ folder = controls.comparison_checkpoint_folder or Path(config.dump_folder) / "checkpoint"
48+ folder = folder.resolve()
49+ if folder.exists() and any(folder.iterdir()):
50+ raise ValueError(f"comparison checkpoint folder must be empty: {folder}")
51+ if controls.comparison_create_seed_checkpoint:
52+ if int(os.environ["WORLD_SIZE"]) != 1:
53+ raise ValueError("seed creation requires one process")
54+ if controls.comparison_checkpoint_folder is None:
55+ parser.error("seed creation requires --comparison-checkpoint-folder")
56+ config.create_seed_checkpoint = True
57+ config.checkpointer = replace(
58+ checkpointer,
59+ folder=str(folder),
60+ load_only=False,
61+ last_save_model_only=True,
62+ last_save_in_hf=False,
63+ export_dtype="float32",
64+ initial_load_path=None,
65+ )
66+ else:
67+ checkpoint = controls.comparison_initial_load_path.resolve()
68+ if not checkpoint.is_dir():
69+ raise ValueError(f"initial checkpoint does not exist: {checkpoint}")
70+ config.checkpointer = replace(
71+ checkpointer,
72+ folder=str(folder),
73+ load_only=True,
74+ initial_load_path=str(checkpoint),
75+ initial_load_model_only=True,
76+ initial_load_in_hf=False,
77+ )
78+ logger.info("Comparison loads shared model-only checkpoint: %s", checkpoint)
79+ 
80+ import torchtitan
81+ 
82+ logger.info("Comparison code: torchtitan=%s; torchtitan_npu=%s", torchtitan.__file__, torchtitan_npu.__file__)
83+ sl.init_structured_logger(
84+ source="training",
85+ output_dir=config.dump_folder,
86+ enable=config.debug.enable_structured_logging,
87+ )
88+ trainer = None
89+ try:
90+ trainer = config.build()
91+ if config.create_seed_checkpoint:
92+ trainer.engine.save_checkpoint(last_step=True)
93+ logger.info("Created shared seed checkpoint")
94+ else:
95+ trainer.train()
96+ except Exception:
97+ if trainer is not None:
98+ trainer.close()
99+ raise
100+ else:
101+ trainer.close()
102+ if dist.is_initialized():
103+ dist.destroy_process_group()
104+ 
105+ 
106+if __name__ == "__main__":
107+ main()
@@ -8,7 +8,7 @@
8# override arguments belong in an example under examples/; extra command-line8# override arguments belong in an example under examples/; extra command-line
9# arguments are passed through unchanged.9# arguments are passed through unchanged.
10#10#
11-# ./scripts/run_train.sh --compile.enable --compile.components model --compile.backend inductor11+# MODULE=my_recipes CONFIG=my_run ./scripts/run_train.sh
12 12 
13set -euo pipefail13set -euo pipefail
14 14 
@@ -9,8 +9,11 @@ from collections.abc import Callable
9from dataclasses import dataclass, fields9from dataclasses import dataclass, fields
10 10 
11import pytest11import pytest
12+from torchtitan.components.checkpointer import CheckpointManager
13+from torchtitan.components.optim import AdamW, Optim, OptimizersContainer
12from torchtitan.config import ConfigManager14from torchtitan.config import ConfigManager
13from torchtitan.config import TrainingConfig as UpstreamTrainingConfig15from torchtitan.config import TrainingConfig as UpstreamTrainingConfig
16+from torchtitan.models.llama3 import model_registry
14from torchtitan.trainer import Trainer17from torchtitan.trainer import Trainer
15 18 
16import torchtitan_npu.config as npu_config19import torchtitan_npu.config as npu_config
@@ -18,6 +21,7 @@ import torchtitan_npu.extensions.torchtitan.trainer as trainer_module
18from torchtitan_npu.config import (21from torchtitan_npu.config import (
19 ExtensionConfig,22 ExtensionConfig,
20 MuonOptimizerProfile,23 MuonOptimizerProfile,
24+ OptimConfig,
21 OptimizerConfig,25 OptimizerConfig,
22 QuantizationExtensionConfig,26 QuantizationExtensionConfig,
23 TrainingExtensionConfig,27 TrainingExtensionConfig,
@@ -31,6 +35,10 @@ from torchtitan_npu.extensions.torchtitan.tools.profiler import CANNProfiler
31from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx35from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
32 36 
33 37 
38+def _debug_model():
39+ return model_registry("debugmodel")
40+ 
41+ 
34def _install_config_registry(42def _install_config_registry(
35 monkeypatch,43 monkeypatch,
36 module_name: str,44 module_name: str,
@@ -47,6 +55,7 @@ def test_config_manager_adapts_standard_component_configs_without_changing_value
47):55):
48 module_name = "_torchtitan_npu_standard_config_registry"56 module_name = "_torchtitan_npu_standard_config_registry"
49 source = Trainer.Config(57 source = Trainer.Config(
58+ model=_debug_model(),
50 hf_assets_path=str(tmp_path),59 hf_assets_path=str(tmp_path),
51 dump_folder="custom-output",60 dump_folder="custom-output",
52 training=UpstreamTrainingConfig(61 training=UpstreamTrainingConfig(
@@ -70,10 +79,10 @@ def test_config_manager_adapts_standard_component_configs_without_changing_value
70 assert isinstance(config.training, NPUTrainingConfig)79 assert isinstance(config.training, NPUTrainingConfig)
71 assert isinstance(config.training.extension, TrainingExtensionConfig)80 assert isinstance(config.training.extension, TrainingExtensionConfig)
72 assert config.training.extension.allow_hf32 is True81 assert config.training.extension.allow_hf32 is True
73- assert isinstance(config.optimizer, OptimizerConfig)82+ assert isinstance(config.optim.optimizer, OptimizerConfig)
74- assert config.optimizer.name == "AdamW"83+ assert config.optim.optimizer.name == "AdamW"
75 for config_field in fields(Trainer.Config):84 for config_field in fields(Trainer.Config):
76- if config_field.name in ("optimizer", "profiler", "training", "checkpoint"):85+ if config_field.name in ("optim", "profiler", "training", "checkpointer"):
77 continue86 continue
78 assert getattr(config, config_field.name) == getattr(source, config_field.name)87 assert getattr(config, config_field.name) == getattr(source, config_field.name)
79 assert isinstance(config.profiler, CANNProfiler.Config)88 assert isinstance(config.profiler, CANNProfiler.Config)
@@ -89,14 +98,10 @@ def test_config_manager_adapts_standard_component_configs_without_changing_value
89 assert config.profiler.extension.profile_with_memory is False98 assert config.profiler.extension.profile_with_memory is False
90 assert config.profiler.extension.profile_with_stack is False99 assert config.profiler.extension.profile_with_stack is False
91 assert config.profiler.extension.enable_online_parse is True100 assert config.profiler.extension.enable_online_parse is True
92- for config_field in fields(source.checkpoint):101+ assert config.checkpointer is None
93- assert getattr(config.checkpoint, config_field.name) == getattr(102+ for config_field in fields(source.optim.optimizer):
94- source.checkpoint,103+ assert getattr(config.optim.optimizer, config_field.name) == getattr(
95- config_field.name,104+ source.optim.optimizer,
96- )
97- for config_field in fields(source.optimizer):
98- assert getattr(config.optimizer, config_field.name) == getattr(
99- source.optimizer,
100 config_field.name,105 config_field.name,
101 )106 )
102 for config_field in fields(UpstreamTrainingConfig):107 for config_field in fields(UpstreamTrainingConfig):
@@ -111,7 +116,7 @@ def test_config_manager_reapplying_patch_does_not_stack_registered_converter(
111 tmp_path,116 tmp_path,
112):117):
113 module_name = "_torchtitan_npu_reapplied_config_converter_registry"118 module_name = "_torchtitan_npu_reapplied_config_converter_registry"
114- source = Trainer.Config(hf_assets_path=str(tmp_path))119+ source = Trainer.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
115 converted_configs: list[Trainer.Config] = []120 converted_configs: list[Trainer.Config] = []
116 121 
117 def test_config() -> Trainer.Config:122 def test_config() -> Trainer.Config:
@@ -142,7 +147,7 @@ def test_config_manager_parses_training_extension_hf32_option(
142 module_name = "_torchtitan_npu_hf32_config_registry"147 module_name = "_torchtitan_npu_hf32_config_registry"
143 148 
144 def test_config() -> Trainer.Config:149 def test_config() -> Trainer.Config:
145- return Trainer.Config(hf_assets_path=str(tmp_path))150+ return Trainer.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
146 151 
147 _install_config_registry(monkeypatch, module_name, test_config)152 _install_config_registry(monkeypatch, module_name, test_config)
148 153 
@@ -167,7 +172,7 @@ def test_config_manager_parses_cann_profiler_without_override(
167 module_name = "_torchtitan_npu_profiler_config_registry"172 module_name = "_torchtitan_npu_profiler_config_registry"
168 173 
169 def test_config() -> Trainer.Config:174 def test_config() -> Trainer.Config:
170- return Trainer.Config(hf_assets_path=str(tmp_path))175+ return Trainer.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
171 176 
172 _install_config_registry(monkeypatch, module_name, test_config)177 _install_config_registry(monkeypatch, module_name, test_config)
173 178 
@@ -211,7 +216,7 @@ def test_config_manager_parses_quantization_extension(
211 module_name = "_torchtitan_npu_quantization_config_registry"216 module_name = "_torchtitan_npu_quantization_config_registry"
212 217 
213 def test_config() -> Trainer.Config:218 def test_config() -> Trainer.Config:
214- return Trainer.Config(hf_assets_path=str(tmp_path))219+ return Trainer.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
215 220 
216 _install_config_registry(monkeypatch, module_name, test_config)221 _install_config_registry(monkeypatch, module_name, test_config)
217 222 
@@ -252,7 +257,7 @@ def test_config_manager_splits_comma_joined_fsdp_prequantize_fqns(monkeypatch, t
252 module_name = "_torchtitan_npu_prequantize_fqns_config_registry"257 module_name = "_torchtitan_npu_prequantize_fqns_config_registry"
253 258 
254 def test_config() -> Trainer.Config:259 def test_config() -> Trainer.Config:
255- return Trainer.Config(hf_assets_path=str(tmp_path))260+ return Trainer.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
256 261 
257 _install_config_registry(monkeypatch, module_name, test_config)262 _install_config_registry(monkeypatch, module_name, test_config)
258 263 
@@ -276,7 +281,7 @@ def test_config_manager_rejects_space_separated_fsdp_prequantize_fqns(monkeypatc
276 module_name = "_torchtitan_npu_prequantize_fqns_space_config_registry"281 module_name = "_torchtitan_npu_prequantize_fqns_space_config_registry"
277 282 
278 def test_config() -> Trainer.Config:283 def test_config() -> Trainer.Config:
279- return Trainer.Config(hf_assets_path=str(tmp_path))284+ return Trainer.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
280 285 
281 _install_config_registry(monkeypatch, module_name, test_config)286 _install_config_registry(monkeypatch, module_name, test_config)
282 287 
@@ -323,8 +328,9 @@ def test_config_manager_materializes_muon_from_cli(monkeypatch, tmp_path):
323 328 
324 def test_config() -> TrainerEx.Config:329 def test_config() -> TrainerEx.Config:
325 return TrainerEx.Config(330 return TrainerEx.Config(
331+ model=_debug_model(),
326 hf_assets_path=str(tmp_path),332 hf_assets_path=str(tmp_path),
327- optimizer=OptimizerConfig(_muon_profile=profile),333+ optim=OptimConfig(optimizer=OptimizerConfig(_muon_profile=profile)),
328 )334 )
329 335 
330 _install_config_registry(monkeypatch, module_name, test_config)336 _install_config_registry(monkeypatch, module_name, test_config)
@@ -335,48 +341,47 @@ def test_config_manager_materializes_muon_from_cli(monkeypatch, tmp_path):
335 module_name,341 module_name,
336 "--config",342 "--config",
337 "test_config",343 "test_config",
338- "--optimizer.name",344+ "--optim.optimizer.name",
339 "Muon",345 "Muon",
340- "--optimizer.lr",346+ "--optim.optimizer.lr",
341 "2.2e-4",347 "2.2e-4",
342- "--optimizer.weight_decay",348+ "--optim.optimizer.weight_decay",
343 "0.1",349 "0.1",
344- "--optimizer.muon_momentum",350+ "--optim.optimizer.muon_momentum",
345 "0.95",351 "0.95",
346- "--optimizer.muon_enable_nesterov",352+ "--optim.optimizer.muon_enable_nesterov",
347- "--optimizer.muon_ns_steps",353+ "--optim.optimizer.muon_ns_steps",
348 "10",354 "10",
349- "--optimizer.muon_adjust_lr_fn",355+ "--optim.optimizer.muon_adjust_lr_fn",
350 "match_rms_adamw",356 "match_rms_adamw",
351 ]357 ]
352 )358 )
353 359 
354- assert config.optimizer.name == "Muon"360+ assert config.optim.optimizer.name == "Muon"
355- assert len(config.optimizer.param_groups) == 2361+ assert len(config.optim.optimizer.optimizers) == 2
356- muon_group, adamw_group = config.optimizer.param_groups362+ muon_group, adamw_group = config.optim.optimizer.optimizers
357- assert muon_group.optimizer_name == "DistMuon"363+ assert type(muon_group).__qualname__ == "DistMuon.Config"
358- assert muon_group.optimizer_kwargs["lr"] == pytest.approx(2.2e-4)364+ assert muon_group.lr == pytest.approx(2.2e-4)
359- assert muon_group.optimizer_kwargs["momentum"] == pytest.approx(0.95)365+ assert muon_group.momentum == pytest.approx(0.95)
360- assert muon_group.optimizer_kwargs["nesterov"] is True366+ assert muon_group.nesterov is True
361- assert muon_group.optimizer_kwargs["ns_steps"] == 10367+ assert muon_group.ns_steps == 10
362- assert muon_group.optimizer_kwargs["foreach"] is False368+ assert isinstance(adamw_group, AdamW.Config)
363- assert adamw_group.optimizer_name == "AdamW"369+ assert adamw_group.foreach is False
364- assert adamw_group.optimizer_kwargs["foreach"] is False
365 370 
366 371 
367def test_config_manager_accepts_adamw_from_cli(monkeypatch, tmp_path):372def test_config_manager_accepts_adamw_from_cli(monkeypatch, tmp_path):
368 module_name = "_torchtitan_npu_adamw_config_registry"373 module_name = "_torchtitan_npu_adamw_config_registry"
369 374 
370 def test_config() -> TrainerEx.Config:375 def test_config() -> TrainerEx.Config:
371- return TrainerEx.Config(hf_assets_path=str(tmp_path))376+ return TrainerEx.Config(model=_debug_model(), hf_assets_path=str(tmp_path))
372 377 
373 _install_config_registry(monkeypatch, module_name, test_config)378 _install_config_registry(monkeypatch, module_name, test_config)
374 379 
375 config = ConfigManager().parse_args(380 config = ConfigManager().parse_args(
376- ["--module", module_name, "--config", "test_config", "--optimizer.name", "AdamW"]381+ ["--module", module_name, "--config", "test_config", "--optim.optimizer.name", "AdamW"]
377 )382 )
378 383 
379- assert config.optimizer.name == "AdamW"384+ assert config.optim.optimizer.name == "AdamW"
380 385 
381 386 
382def test_config_package_does_not_reexport_trainer_config():387def test_config_package_does_not_reexport_trainer_config():
@@ -384,7 +389,9 @@ def test_config_package_does_not_reexport_trainer_config():
384 389 
385 390 
386def test_trainer_ex_config_exposes_hf32_only_under_training_extension():391def test_trainer_ex_config_exposes_hf32_only_under_training_extension():
387- config = TrainerEx.Config()392+ config = TrainerEx.Config(
393+ model=_debug_model(),
394+ )
388 395 
389 assert not hasattr(config, "allow_hf32")396 assert not hasattr(config, "allow_hf32")
390 assert config.training.extension.allow_hf32 is True397 assert config.training.extension.allow_hf32 is True
@@ -398,6 +405,7 @@ def test_config_manager_preserves_explicit_npu_training_extension(
398 405 
399 def test_config() -> Trainer.Config:406 def test_config() -> Trainer.Config:
400 return Trainer.Config(407 return Trainer.Config(
408+ model=_debug_model(),
401 hf_assets_path=str(tmp_path),409 hf_assets_path=str(tmp_path),
402 training=NPUTrainingConfig(410 training=NPUTrainingConfig(
403 steps=23,411 steps=23,
@@ -430,6 +438,7 @@ def test_config_manager_preserves_specialized_trainer_config(
430 438 
431 def test_config() -> Trainer.Config:439 def test_config() -> Trainer.Config:
432 return SpecializedTrainer.Config(440 return SpecializedTrainer.Config(
441+ model=_debug_model(),
433 hf_assets_path=str(tmp_path),442 hf_assets_path=str(tmp_path),
434 specialized_option=11,443 specialized_option=11,
435 )444 )
@@ -460,15 +469,16 @@ def test_config_manager_builds_graph_trainer_ex_and_applies_hf32(monkeypatch, tm
460 469 
461 def test_config() -> GraphTrainer.Config:470 def test_config() -> GraphTrainer.Config:
462 return GraphTrainer.Config(471 return GraphTrainer.Config(
472+ model=_debug_model(),
463 hf_assets_path=str(tmp_path),473 hf_assets_path=str(tmp_path),
464- compile=GraphTrainerCompileConfig(enable=True),474+ compile=GraphTrainerCompileConfig(),
465 training=UpstreamTrainingConfig(steps=23),475 training=UpstreamTrainingConfig(steps=23),
466 )476 )
467 477 
468 _install_config_registry(monkeypatch, module_name, test_config)478 _install_config_registry(monkeypatch, module_name, test_config)
469 479 
470 def initialize_graph_trainer(trainer, config):480 def initialize_graph_trainer(trainer, config):
471- trainer.model_parts = []481+ trainer.engine = types.SimpleNamespace(model_parts=[])
472 trainer.gradient_accumulation_steps = 1482 trainer.gradient_accumulation_steps = 1
473 483 
474 monkeypatch.setattr(trainer_module, "set_allow_hf32", applied_hf32.append)484 monkeypatch.setattr(trainer_module, "set_allow_hf32", applied_hf32.append)
@@ -479,7 +489,6 @@ def test_config_manager_builds_graph_trainer_ex_and_applies_hf32(monkeypatch, tm
479 489 
480 assert isinstance(config, GraphTrainerEx.Config)490 assert isinstance(config, GraphTrainerEx.Config)
481 assert isinstance(config.compile, GraphTrainerCompileConfig)491 assert isinstance(config.compile, GraphTrainerCompileConfig)
482- assert config.compile.enable is True
483 assert isinstance(config.training, NPUTrainingConfig)492 assert isinstance(config.training, NPUTrainingConfig)
484 assert config.training.steps == 23493 assert config.training.steps == 23
485 assert config.training.extension.allow_hf32 is True494 assert config.training.extension.allow_hf32 is True
@@ -489,15 +498,15 @@ def test_config_manager_builds_graph_trainer_ex_and_applies_hf32(monkeypatch, tm
489 498 
490def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monkeypatch):499def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monkeypatch):
491 events = []500 events = []
492- source_model_spec = object()501+ source_model = _debug_model()
493- quantized_model_spec = object()502+ quantized_model = _debug_model()
494 converter_module = types.ModuleType("torchtitan_npu.extensions.adaptor.torchao.converter")503 converter_module = types.ModuleType("torchtitan_npu.extensions.adaptor.torchao.converter")
495 504 
496- def apply_quantization(model_spec, quantization_config, *, model_compile_enabled, override_config=None):505+ def apply_quantization(model, quantization_config, *, model_compile_enabled, override_config=None):
497 events.append(506 events.append(
498 (507 (
499 "quantize",508 "quantize",
500- model_spec,509+ model,
501 quantization_config.recipe,510 quantization_config.recipe,
502 quantization_config.enable_mxfp4_qat,511 quantization_config.enable_mxfp4_qat,
503 quantization_config.dst_type_max,512 quantization_config.dst_type_max,
@@ -505,15 +514,15 @@ def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monk
505 model_compile_enabled,514 model_compile_enabled,
506 )515 )
507 )516 )
508- return quantized_model_spec517+ return quantized_model
509 518 
510 def apply_hf32(allow_hf32):519 def apply_hf32(allow_hf32):
511 events.append(("apply_hf32", allow_hf32))520 events.append(("apply_hf32", allow_hf32))
512 521 
513 def initialize_base_trainer(trainer, base_config):522 def initialize_base_trainer(trainer, base_config):
514- trainer.model_parts = []523+ trainer.engine = types.SimpleNamespace(model_parts=[])
515 trainer.gradient_accumulation_steps = 1524 trainer.gradient_accumulation_steps = 1
516- events.append(("initialize_base", base_config.model_spec))525+ events.append(("initialize_base", base_config.model))
517 526 
518 converter_module.apply_quantization_converter = apply_quantization527 converter_module.apply_quantization_converter = apply_quantization
519 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.adaptor.torchao.converter", converter_module)528 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.adaptor.torchao.converter", converter_module)
@@ -521,7 +530,7 @@ def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monk
521 monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer)530 monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer)
522 531 
523 config = TrainerEx.Config(532 config = TrainerEx.Config(
524- model_spec=source_model_spec,533+ model=source_model,
525 extension=ExtensionConfig(534 extension=ExtensionConfig(
526 quantization=QuantizationExtensionConfig(535 quantization=QuantizationExtensionConfig(
527 enable_quantized_training=True,536 enable_quantized_training=True,
@@ -537,50 +546,51 @@ def test_trainer_ex_applies_enabled_quantization_before_base_initialization(monk
537 546 
538 assert isinstance(trainer, TrainerEx)547 assert isinstance(trainer, TrainerEx)
539 assert events == [548 assert events == [
540- ("quantize", source_model_spec, "all_block_fp8", True, 7.0, False, False),549+ ("quantize", source_model, "all_block_fp8", True, 7.0, False, False),
541 ("apply_hf32", True),550 ("apply_hf32", True),
542- ("initialize_base", quantized_model_spec),551+ ("initialize_base", quantized_model),
543 ]552 ]
544 553 
545 554 
546-def test_trainer_ex_skips_disabled_quantization_and_preserves_model_spec(monkeypatch):555+def test_trainer_ex_skips_disabled_quantization_and_preserves_model(monkeypatch):
547- source_model_spec = object()556+ source_model = _debug_model()
548- initialized_model_specs = []557+ initialized_models = []
549 converter_module = types.ModuleType("torchtitan_npu.extensions.adaptor.torchao.converter")558 converter_module = types.ModuleType("torchtitan_npu.extensions.adaptor.torchao.converter")
550 559 
551 def unexpected_quantization(*args, **kwargs):560 def unexpected_quantization(*args, **kwargs):
552 raise AssertionError("quantization converter must remain disabled")561 raise AssertionError("quantization converter must remain disabled")
553 562 
554 def initialize_base_trainer(trainer, base_config):563 def initialize_base_trainer(trainer, base_config):
555- trainer.model_parts = []564+ trainer.engine = types.SimpleNamespace(model_parts=[])
556 trainer.gradient_accumulation_steps = 1565 trainer.gradient_accumulation_steps = 1
557- initialized_model_specs.append(base_config.model_spec)566+ initialized_models.append(base_config.model)
558 567 
559 converter_module.apply_quantization_converter = unexpected_quantization568 converter_module.apply_quantization_converter = unexpected_quantization
560 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.adaptor.torchao.converter", converter_module)569 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.adaptor.torchao.converter", converter_module)
561 monkeypatch.setattr(trainer_module, "set_allow_hf32", lambda _allow_hf32: None)570 monkeypatch.setattr(trainer_module, "set_allow_hf32", lambda _allow_hf32: None)
562 monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer)571 monkeypatch.setattr(TrainerEx.__base__, "__init__", initialize_base_trainer)
563 572 
564- config = TrainerEx.Config(model_spec=source_model_spec)573+ config = TrainerEx.Config(model=source_model)
565 trainer = config.build()574 trainer = config.build()
566 575 
567 assert isinstance(trainer, TrainerEx)576 assert isinstance(trainer, TrainerEx)
568- assert initialized_model_specs == [source_model_spec]577+ assert initialized_models == [source_model]
569 578 
570 579 
571def test_trainer_ex_applies_training_hf32_before_base_initialization(monkeypatch):580def test_trainer_ex_applies_training_hf32_before_base_initialization(monkeypatch):
572 events = []581 events = []
573 config = TrainerEx.Config(582 config = TrainerEx.Config(
583+ model=_debug_model(),
574 training=NPUTrainingConfig(584 training=NPUTrainingConfig(
575 extension=TrainingExtensionConfig(allow_hf32=False),585 extension=TrainingExtensionConfig(allow_hf32=False),
576- )586+ ),
577 )587 )
578 588 
579 def apply_hf32(allow_hf32):589 def apply_hf32(allow_hf32):
580 events.append(("apply_hf32", allow_hf32))590 events.append(("apply_hf32", allow_hf32))
581 591 
582 def initialize_base_trainer(trainer, base_config):592 def initialize_base_trainer(trainer, base_config):
583- trainer.model_parts = []593+ trainer.engine = types.SimpleNamespace(model_parts=[])
584 trainer.gradient_accumulation_steps = 1594 trainer.gradient_accumulation_steps = 1
585 events.append(("initialize_base", base_config))595 events.append(("initialize_base", base_config))
586 596 
@@ -604,12 +614,133 @@ def test_trainer_ex_config_build_constructs_trainer_ex(monkeypatch):
604 monkeypatch.setattr(TrainerEx, "__init__", capture_config)614 monkeypatch.setattr(TrainerEx, "__init__", capture_config)
605 615 
606 trainer = TrainerEx.Config(616 trainer = TrainerEx.Config(
617+ model=_debug_model(),
607 training=NPUTrainingConfig(618 training=NPUTrainingConfig(
608 extension=TrainingExtensionConfig(allow_hf32=False),619 extension=TrainingExtensionConfig(allow_hf32=False),
609- )620+ ),
610 ).build()621 ).build()
611 622 
612 assert isinstance(trainer, TrainerEx)623 assert isinstance(trainer, TrainerEx)
613 assert len(built_configs) == 1624 assert len(built_configs) == 1
614 assert isinstance(built_configs[0], TrainerEx.Config)625 assert isinstance(built_configs[0], TrainerEx.Config)
615 assert built_configs[0].training.extension.allow_hf32 is False626 assert built_configs[0].training.extension.allow_hf32 is False
627+ 
628+ 
629+def test_config_manager_preserves_nested_optimization_policy(monkeypatch, tmp_path):
630+ from torchtitan.components.optim import EMA, LRSchedulersContainer
631+ 
632+ module_name = "_torchtitan_npu_nested_optim_registry"
633+ adamw = AdamW.Config(pattern=r".*", lr=0.003, betas=(0.8, 0.99), fused=False)
634+ source = Trainer.Config(
635+ model=_debug_model(),
636+ hf_assets_path=str(tmp_path),
637+ optim=Optim.Config(
638+ optimizer=OptimizersContainer.Config(optimizers=[adamw]),
639+ lr_scheduler=LRSchedulersContainer.Config(warmup_steps=17, total_steps=91),
640+ ema=EMA.Config(),
641+ max_norm=0.25,
642+ enable_cuda_graph=True,
643+ ),
644+ checkpointer=CheckpointManager.Config(interval=13),
645+ create_seed_checkpoint=True,
646+ )
647+ _install_config_registry(monkeypatch, module_name, lambda: source)
648+ 
649+ config = ConfigManager().parse_args(["--module", module_name, "--config", "test_config"])
650+ 
651+ assert isinstance(config.optim, OptimConfig)
652+ assert isinstance(config.optim.optimizer, OptimizerConfig)
653+ assert config.optim.optimizer.optimizers == [adamw]
654+ assert config.optim.lr_scheduler.warmup_steps == 17
655+ assert config.optim.lr_scheduler.total_steps == 91
656+ from torchtitan_npu.extensions.torchtitan.components.optimizer.ema import EMA as NPUEMA
657+ 
658+ assert type(config.optim.ema) is NPUEMA.Config
659+ assert type(source.optim.ema) is EMA.Config
660+ assert all(
661+ getattr(config.optim.ema, field.name) == getattr(source.optim.ema, field.name) for field in fields(EMA.Config)
662+ )
663+ assert config.optim.max_norm == 0.25
664+ assert config.optim.enable_cuda_graph is True
665+ assert config.checkpointer.interval == 13
666+ assert config.create_seed_checkpoint is True
667+ assert config.compile is None
668+ 
669+ 
670+def test_config_manager_preserves_recipe_optimizer_type_and_fields(monkeypatch, tmp_path):
671+ class RecipeOptimizer(OptimizersContainer):
672+ @dataclass(kw_only=True, slots=True)
673+ class Config(OptimizersContainer.Config):
674+ recipe_policy: str = "specialized"
675+ 
676+ module_name = "_torchtitan_npu_recipe_optimizer_registry"
677+ source_optimizer = RecipeOptimizer.Config(
678+ optimizers=[AdamW.Config(pattern=r".*", lr=0.007)],
679+ recipe_policy="retain-me",
680+ )
681+ source = Trainer.Config(
682+ model=_debug_model(),
683+ hf_assets_path=str(tmp_path),
684+ optim=Optim.Config(optimizer=source_optimizer),
685+ )
686+ _install_config_registry(monkeypatch, module_name, lambda: source)
687+ 
688+ config = ConfigManager().parse_args(["--module", module_name, "--config", "test_config"])
689+ 
690+ assert type(config.optim.optimizer) is RecipeOptimizer.Config
691+ assert config.optim.optimizer.recipe_policy == "retain-me"
692+ assert config.optim.optimizer.optimizers[0].lr == 0.007
693+ assert config.optim.optimizer._owner is RecipeOptimizer
694+ 
695+ 
696+def test_config_manager_overrides_recipe_owned_optional_components(monkeypatch, tmp_path):
697+ from torchtitan_npu.config import CompileConfig, ModelCompileConfig
698+ from torchtitan_npu.extensions.torchtitan.components.checkpoint import CheckpointManager as NPUCheckpointManager
699+ 
700+ @dataclass(kw_only=True, slots=True)
701+ class RecipeCompileConfig(CompileConfig):
702+ recipe_policy: str = "model-only"
703+ 
704+ class RecipeCheckpointer(NPUCheckpointManager):
705+ @dataclass(kw_only=True, slots=True)
706+ class Config(NPUCheckpointManager.Config):
707+ recipe_policy: str = "retain-me"
708+ 
709+ module_name = "_torchtitan_npu_optional_owner_registry"
710+ source = TrainerEx.Config(
711+ model=_debug_model(),
712+ hf_assets_path=str(tmp_path),
713+ compile=RecipeCompileConfig(components=[], model=ModelCompileConfig()),
714+ checkpointer=RecipeCheckpointer.Config(interval=11, folder="recipe-checkpoints"),
715+ )
716+ _install_config_registry(monkeypatch, module_name, lambda: source)
717+ base = ["--module", module_name, "--config", "test_config"]
718+ 
719+ configured = ConfigManager().parse_args(
720+ [
721+ *base,
722+ "--compile.model.backend",
723+ "aot_eager",
724+ "--compile.model.no-fullgraph",
725+ "--checkpointer.interval",
726+ "17",
727+ "--checkpointer.extensions.verify-hash-manifest",
728+ ]
729+ )
730+ 
731+ assert type(configured.compile) is RecipeCompileConfig
732+ assert configured.compile.components == []
733+ assert configured.compile.recipe_policy == "model-only"
734+ assert isinstance(configured.compile.model, ModelCompileConfig)
735+ assert configured.compile.model.backend == "aot_eager"
736+ assert configured.compile.model.fullgraph is False
737+ assert type(configured.checkpointer) is RecipeCheckpointer.Config
738+ assert configured.checkpointer._owner is RecipeCheckpointer
739+ assert configured.checkpointer.recipe_policy == "retain-me"
740+ assert configured.checkpointer.folder == "recipe-checkpoints"
741+ assert configured.checkpointer.interval == 17
742+ assert configured.checkpointer.extensions.verify_hash_manifest is True
743+ assert source.compile.model.backend == "inductor"
744+ assert source.compile.model.fullgraph is True
745+ assert source.checkpointer.interval == 11
746+ assert source.checkpointer.extensions.verify_hash_manifest is False
@@ -0,0 +1,46 @@
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+"""Real model recipes select the typed Muon replica-dedup configuration."""
7+ 
8+import pytest
9+from torchtitan.config import ConfigManager
10+ 
11+from torchtitan_npu.extensions.torchtitan.components.optimizer.muon import DistMuon
12+ 
13+ 
14+@pytest.mark.parametrize(
15+ ("module", "recipe"),
16+ [
17+ ("torchtitan_npu.models.deepseek_v4.config_registry", "deepseek_v4_debugmodel"),
18+ ("torchtitan_npu.models.deepseek_v4_1.config_registry", "deepseek_v4_1_debugmodel_text"),
19+ ],
20+)
21+@pytest.mark.parametrize("dedup", [False, True])
22+def test_real_muon_recipe_selects_npu_config_and_propagates_replica_dedup(module, recipe, dedup, tmp_path):
23+ args = [
24+ "--module",
25+ module,
26+ "--config",
27+ recipe,
28+ "--hf_assets_path",
29+ str(tmp_path),
30+ "--optim.optimizer.name",
31+ "Muon",
32+ ]
33+ if dedup:
34+ args.append("--optim.optimizer.muon_enable_hsdp_replica_dedup")
35+ 
36+ config = ConfigManager().parse_args(args)
37+ 
38+ muons = [optimizer for optimizer in config.optim.optimizer.optimizers if type(optimizer) is DistMuon.Config]
39+ assert len(muons) == 1
40+ muon = muons[0]
41+ assert type(muon) is DistMuon.Config
42+ assert muon.enable_hsdp_replica_dedup is dedup
43+ assert config.optim.optimizer._muon_profile.optimizer_config_type is DistMuon.Config
44+ assert muon.pattern == config.optim.optimizer._muon_profile.muon_pattern
45+ assert muon.compute_sharding_by_fqn
46+ assert muon.bucket_configs
@@ -23,8 +23,9 @@ import pytest
23import torch23import torch
24 24 
25_REPO = Path(__file__).resolve().parents[2]25_REPO = Path(__file__).resolve().parents[2]
26-sys.path.insert(0, str(_REPO))
27sys.path.insert(0, os.environ.get("TORCHTITAN_DIR", os.path.expanduser("~/workspace/torchtitan")))26sys.path.insert(0, os.environ.get("TORCHTITAN_DIR", os.path.expanduser("~/workspace/torchtitan")))
27+# Spawned workers must resolve this repository's tests package before upstream's.
28+sys.path.insert(0, str(_REPO))
28 29 
29# These features still use the pre-fold-batch trainer/optimizer interfaces.30# These features still use the pre-fold-batch trainer/optimizer interfaces.
30# Keep their tests out of collection until the feature itself is migrated;31# Keep their tests out of collection until the feature itself is migrated;
@@ -119,21 +120,53 @@ def pytest_collection_modifyitems(items):
119 settings = params.get("settings", {})120 settings = params.get("settings", {})
120 # Hash routing discards the vision flag and uses token IDs.121 # Hash routing discards the vision flag and uses token IDs.
121 is_vision |= settings.get("vision_enabled", False) and not settings.get("hash", False)122 is_vision |= settings.get("vision_enabled", False) and not settings.get("hash", False)
123+ if (relative_path, getattr(item, "originalname", item.name)) in {
124+ (
125+ "models/deepseek_v4_1/test_migration_config.py",
126+ "test_debug_recipe_builds_with_token_budget_and_preserves_embedding_weights",
127+ ),
128+ (
129+ "models/deepseek_v4_1/test_v41_lora.py",
130+ "test_lora_recipe_preserves_vision_and_uses_standard_adamw_and_peft",
131+ ),
132+ }:
133+ # These config-only nodes use the migrated target contracts.
134+ is_vision = False
122 if is_vision:135 if is_vision:
123 item.add_marker(pytest.mark.skip(reason="vision migration is outside the current text migration"))136 item.add_marker(pytest.mark.skip(reason="vision migration is outside the current text migration"))
124 if getattr(item, "originalname", item.name) in _DEFERRED_DSV32_FOLD_TESTS.get(relative_path, ()):137 if getattr(item, "originalname", item.name) in _DEFERRED_DSV32_FOLD_TESTS.get(relative_path, ()):
125 item.add_marker(138 item.add_marker(
126 pytest.mark.skip(reason="DeepSeek-V3.2 model boundary still requires the folded-token migration")139 pytest.mark.skip(reason="DeepSeek-V3.2 model boundary still requires the folded-token migration")
127 )140 )
128- if relative_path.startswith("extensions/cpu_offload/") and "muon" in item.name.lower():141+ # These legacy suites still consume removed optimizer interfaces.
129- item.add_marker(pytest.mark.skip(reason="native CPU-offload Muon migration is pending"))142+ # Do not hide new Muon behavior tests by matching their names globally.
130- if item.name.startswith(143+ migrated_muon_config_test = (
131- (144+ relative_path == "models/common/test_lora_muon_profile.py"
132- "test_lora_training_freezes_engram_and_native_dcp_resumes",145+ and getattr(item, "originalname", item.name)
133- "test_v41_adapter_only_resume_restores_engram_and_next_step",146+ == "test_actual_lora_recipe_muon_groups_cover_adapters_with_layouts_and_unique_buckets"
147+ )
148+ if (
149+ not relative_path.startswith("config/")
150+ and not migrated_muon_config_test
151+ and (
152+ (
153+ relative_path
154+ in {
155+ "extensions/cpu_offload/test_no_optimizer_state.py",
156+ "override/common/test_swap_optimizer.py",
157+ "models/common/test_lora_muon_profile.py",
158+ }
159+ and "muon" in item.name.lower()
160+ )
161+ or item.name.startswith(
162+ (
163+ "test_lora_training_freezes_engram_and_native_dcp_resumes",
164+ "test_v41_adapter_only_resume_restores_engram_and_next_step",
165+ )
166+ )
134 )167 )
135 ):168 ):
136- item.add_marker(pytest.mark.skip(reason="LoRA checkpoint migration is pending"))169+ item.add_marker(pytest.mark.skip(reason="checkpoint/Muon migration is pending"))
137 170 
138 171 
139# ---------------------------------------------------------------------------172# ---------------------------------------------------------------------------
@@ -293,6 +326,15 @@ def pytest_configure(config):
293 install()326 install()
294 327 
295 328 
329+@pytest.fixture(scope="module")
330+def single_rank_spmd():
331+ """Provide real CPU mesh axes only to model tests that explicitly request them."""
332+ from tests.unit_tests.models.spmd_test_utils import single_rank_spmd_context
333+ 
334+ with single_rank_spmd_context() as context:
335+ yield context
336+ 
337+ 
296@pytest.fixture(scope="module")338@pytest.fixture(scope="module")
297def dsv4():339def dsv4():
298 """Install the ``cann_ops_transformer`` recorder and import the340 """Install the ``cann_ops_transformer`` recorder and import the
@@ -43,20 +43,18 @@ def quantization_calls(monkeypatch, converter_module):
43 # Patch where the call sites live (generated modules in recipes + the DeepSeek43 # Patch where the call sites live (generated modules in recipes + the DeepSeek
44 # quantized-expert class in configs.deepseek_v4), not the facade, so the patched44 # quantized-expert class in configs.deepseek_v4), not the facade, so the patched
45 # quantize_ is what NpuQuantized*Module.__init__ resolves.45 # quantize_ is what NpuQuantized*Module.__init__ resolves.
46- for mod in ("torchtitan_npu.extensions.adaptor.torchao.recipes",46+ monkeypatch.setattr(
47- "torchtitan_npu.extensions.adaptor.torchao.configs.deepseek_v4"):47+ importlib.import_module("torchtitan_npu.extensions.adaptor.torchao.recipes"), "quantize_", quantize
48- monkeypatch.setattr(importlib.import_module(mod), "quantize_", quantize)48+ )
49 monkeypatch.setitem(sys.modules, "cann_ops_nn.ops", ModuleType("cann_ops_nn.ops"))49 monkeypatch.setitem(sys.modules, "cann_ops_nn.ops", ModuleType("cann_ops_nn.ops"))
50 with torch.random.fork_rng(devices=[]):50 with torch.random.fork_rng(devices=[]):
51 yield calls51 yield calls
52 52 
53 53 
54-@pytest.mark.parametrize("source_kind", ["grouped", "asc"])54+def test_quantized_grouped_projection_keeps_fused_axis_and_skips_reconversion(converter_module, quantization_calls):
55-def test_quantized_grouped_experts_keep_config_and_skip_reconversion(converter_module, quantization_calls, source_kind):
56 from torchtitan_npu.extensions.adaptor.torchao.converter import mxfp8_param_swap55 from torchtitan_npu.extensions.adaptor.torchao.converter import mxfp8_param_swap
57 56 
58- source_cls = converter_module.GroupedExperts if source_kind == "grouped" else converter_module.AscGroupedExperts57+ source = converter_module.GroupedLinear.Config(group_size=2, in_features=2, out_features=4, num_linears=2)
59- source = source_cls.Config(dim=2, hidden_dim=4, num_experts=2, swiglu_limit=1.5)
60 quant_config = mxfp8_param_swap()58 quant_config = mxfp8_param_swap()
61 converter = converter_module.NpuQuantizeConverter.Config(59 converter = converter_module.NpuQuantizeConverter.Config(
62 base_config=quant_config,60 base_config=quant_config,
@@ -67,26 +65,25 @@ def test_quantized_grouped_experts_keep_config_and_skip_reconversion(converter_m
67 65 
68 converted = converter.convert(source)66 converted = converter.convert(source)
69 67 
70- assert isinstance(converted, converter_module.NpuQuantizedAscGroupedExpertsModule.Config)68+ assert isinstance(converted, converter_module.GroupedLinear.Config)
71- assert (converted.dim, converted.hidden_dim, converted.num_experts, converted.swiglu_limit) == (2, 4, 2, 1.5)69+ assert (converted.group_size, converted.in_features, converted.out_features, converted.num_linears) == (2, 2, 4, 2)
72 assert converter.convert(converted) is converted70 assert converter.convert(converted) is converted
73- swiglu_module = importlib.import_module("torchtitan_npu.override.common.swiglu_group")71+ projection = converted.build()
74- assert swiglu_module.asc(converted) is converted72+ assert projection.weight.shape == (2, 2, 4, 2)
75- experts = converted.build()
76 assert len(quantization_calls) == 173 assert len(quantization_calls) == 1
77 module, received_config, filter_fn = quantization_calls[0]74 module, received_config, filter_fn = quantization_calls[0]
78- assert module is experts75+ assert module is projection
79 assert received_config is quant_config76 assert received_config is quant_config
80- assert filter_fn(experts, "")77+ assert filter_fn(projection, "")
81 assert not filter_fn(torch.nn.Identity(), "child")78 assert not filter_fn(torch.nn.Identity(), "child")
82 79 
83 80 
84def test_quantization_converter_preserves_custom_experts(converter_module, quantization_calls):81def test_quantization_converter_preserves_custom_experts(converter_module, quantization_calls):
85 from torchtitan_npu.extensions.adaptor.torchao.converter import mxfp8_param_swap82 from torchtitan_npu.extensions.adaptor.torchao.converter import mxfp8_param_swap
86 83 
87- class CustomExperts(converter_module.GroupedExperts):84+ class CustomExperts(converter_module.GroupedLinear):
88 @dataclass(kw_only=True, slots=True)85 @dataclass(kw_only=True, slots=True)
89- class Config(converter_module.GroupedExperts.Config):86+ class Config(converter_module.GroupedLinear.Config):
90 output_scale: float = 3.087 output_scale: float = 3.0
91 88 
92 def __init__(self, config):89 def __init__(self, config):
@@ -96,7 +93,7 @@ def test_quantization_converter_preserves_custom_experts(converter_module, quant
96 def forward(self, x, num_tokens_per_expert, *, routed_scores_R=None):93 def forward(self, x, num_tokens_per_expert, *, routed_scores_R=None):
97 return x * self.output_scale94 return x * self.output_scale
98 95 
99- source = CustomExperts.Config(dim=2, hidden_dim=4, num_experts=2, output_scale=5.0)96+ source = CustomExperts.Config(group_size=2, in_features=2, out_features=4, output_scale=5.0)
100 converter = converter_module.NpuQuantizeConverter.Config(97 converter = converter_module.NpuQuantizeConverter.Config(
101 base_config=mxfp8_param_swap(),98 base_config=mxfp8_param_swap(),
102 require_match=False,99 require_match=False,
@@ -131,7 +128,6 @@ def test_quantization_converter_keeps_linear_forward(converter_module, quantizat
131 linear = converted.build()128 linear = converted.build()
132 129 
133 assert isinstance(linear, converter_module.Linear)130 assert isinstance(linear, converter_module.Linear)
134- assert not isinstance(linear, converter_module.NpuQuantizedAscGroupedExpertsModule)
135 assert quantization_calls[0][0] is linear131 assert quantization_calls[0][0] is linear
136 assert quantization_calls[0][1] is quant_config132 assert quantization_calls[0][1] is quant_config
137 with torch.no_grad():133 with torch.no_grad():
@@ -224,18 +220,19 @@ def test_sparse_attention_component_triggers_on_real_v41_filters(converter_modul
224 assert "has no sparse_attention filter" not in caplog.text220 assert "has no sparse_attention filter" not in caplog.text
225 221 
226 222 
227-def test_model_type_rejects_unknown_model_spec_name(converter_module):223+def test_model_type_rejects_unknown_model_config(converter_module):
228- with pytest.raises(ValueError, match=r"supports DeepSeek V4 and V4\.1 model specs"):224+ with pytest.raises(ValueError, match=r"supports DeepSeek V4 and V4\.1 model configs"):
229- converter_module._model_type_for_spec(SimpleNamespace(name="deepseek_v3", model=object()))225+ converter_module._model_type_for_config(SimpleNamespace())
230 226 
231 227 
232-def test_model_type_comes_from_model_spec_name(converter_module):228+@pytest.mark.parametrize("family", ["deepseek_v4", "deepseek_v4_1"])
233- kinds = {229+def test_model_type_uses_real_config_owner(converter_module, family):
234- "deepseek_v4": converter_module.ModelType.V4,230+ registry = importlib.import_module(f"torchtitan_npu.models.{family}").model_registry
235- "deepseek_v4_1": converter_module.ModelType.V4_1,231+ name = "debugmodel" if family == "deepseek_v4" else "deepseek_v4_1_debugmodel"
236- }232+ config = registry(name)
237- for spec_name, expected in kinds.items():233+ expected = converter_module.ModelType.V4 if family == "deepseek_v4" else converter_module.ModelType.V4_1
238- assert converter_module._model_type_for_spec(SimpleNamespace(name=spec_name, model=object())) is expected234+ 
235+ assert converter_module._model_type_for_config(config) is expected
239 236 
240 237 
241def test_family_configs_are_split_and_registered(converter_module):238def test_family_configs_are_split_and_registered(converter_module):
@@ -275,9 +272,10 @@ def test_family_configs_are_split_and_registered(converter_module):
275 )272 )
276 273 
277 # The lightning_indexer suffix differs per family; sparse_attention is V4.1-only.274 # The lightning_indexer suffix differs per family; sparse_attention is V4.1-only.
278- assert converter_module._DSV4_CONFIG_FILTERS["lightning_indexer"] is not converter_module._DSV41_CONFIG_FILTERS[275+ assert (
279- "lightning_indexer"276+ converter_module._DSV4_CONFIG_FILTERS["lightning_indexer"]
280- ]277+ is not converter_module._DSV41_CONFIG_FILTERS["lightning_indexer"]
278+ )
281 assert "sparse_attention" not in converter_module._DSV4_CONFIG_FILTERS279 assert "sparse_attention" not in converter_module._DSV4_CONFIG_FILTERS
282 assert "sparse_attention" in converter_module._DSV41_CONFIG_FILTERS280 assert "sparse_attention" in converter_module._DSV41_CONFIG_FILTERS
283 281 
@@ -286,15 +284,11 @@ def test_family_configs_are_split_and_registered(converter_module):
286 284 
287 # Per-model components resolve under their feature name for each family.285 # Per-model components resolve under their feature name for each family.
288 assert (286 assert (
289- type(287+ type(instantiate_component_for_model_and_name(converter_module.ModelType.V4_1, "sparse_attention")).__name__
290- instantiate_component_for_model_and_name(converter_module.ModelType.V4_1, "sparse_attention")
291- ).__name__
292 == "DeepSeekV41QuantSparseAttentionComponent"288 == "DeepSeekV41QuantSparseAttentionComponent"
293 )289 )
294 assert (290 assert (
295- type(291+ type(instantiate_component_for_model_and_name(converter_module.ModelType.V4_1, "compressor")).__name__
296- instantiate_component_for_model_and_name(converter_module.ModelType.V4_1, "compressor")
297- ).__name__
298 == "DeepSeekV41QuantCompressorComponent"292 == "DeepSeekV41QuantCompressorComponent"
299 )293 )
300 assert (294 assert (
@@ -335,24 +329,20 @@ def test_recipe_converters_reject_unknown_model_type(converter_module):
335def test_apply_quantization_converter_passes_model_type(converter_module, monkeypatch, model_name, expected_model_type):329def test_apply_quantization_converter_passes_model_type(converter_module, monkeypatch, model_name, expected_model_type):
336 from torchtitan_npu.config.configs import QuantizationExtensionConfig330 from torchtitan_npu.config.configs import QuantizationExtensionConfig
337 331 
338- @dataclass(frozen=True)332+ registry = importlib.import_module(f"torchtitan_npu.models.{model_name}").model_registry
339- class FakeModelSpec:333+ config_name = "debugmodel" if model_name == "deepseek_v4" else "deepseek_v4_1_debugmodel"
340- name: str334+ model_config = registry(config_name)
341- model: object
342- 
343 quantization_config = QuantizationExtensionConfig(enable_quantized_training=True, recipe="mix")335 quantization_config = QuantizationExtensionConfig(enable_quantized_training=True, recipe="mix")
344 calls = []336 calls = []
345 monkeypatch.setattr(converter_module, "_recipe_converters", lambda *args, **kwargs: calls.append(kwargs) or [])337 monkeypatch.setattr(converter_module, "_recipe_converters", lambda *args, **kwargs: calls.append(kwargs) or [])
346- monkeypatch.setattr(converter_module, "validate_converter_order", lambda converters: None)
347 338 
348- model_spec = FakeModelSpec(name=model_name, model=object())
349 converted = converter_module.apply_quantization_converter(339 converted = converter_module.apply_quantization_converter(
350- model_spec,340+ model_config,
351 quantization_config,341 quantization_config,
352 model_compile_enabled=False,342 model_compile_enabled=False,
353 )343 )
354 344 
355- assert converted is not model_spec345+ assert converted is model_config
356 assert calls[0]["model_type"] == converter_module.ModelType(expected_model_type)346 assert calls[0]["model_type"] == converter_module.ModelType(expected_model_type)
357 347 
358 348 
@@ -360,6 +350,8 @@ def test_apply_quantization_converter_passes_model_type(converter_module, monkey
360def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, converter_module, quant_format):350def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, converter_module, quant_format):
361 from torchtitan_npu.extensions.adaptor.torchao.converter import block_fp8_param_swap, mxfp8_param_swap351 from torchtitan_npu.extensions.adaptor.torchao.converter import block_fp8_param_swap, mxfp8_param_swap
362 352 
353+ # Only the grouped-matmul boundary below runs; registration has no CPU op.
354+ monkeypatch.setitem(sys.modules, "cann_ops_nn", ModuleType("cann_ops_nn"))
363 wrapper_module = importlib.import_module(f"torchao_npu.wrapper_tensors.{quant_format}_wrapper_tensor")355 wrapper_module = importlib.import_module(f"torchao_npu.wrapper_tensors.{quant_format}_wrapper_tensor")
364 if quant_format == "mx":356 if quant_format == "mx":
365 quant_config = mxfp8_param_swap()357 quant_config = mxfp8_param_swap()
@@ -367,22 +359,17 @@ def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, conver
367 else:359 else:
368 quant_config = block_fp8_param_swap()360 quant_config = block_fp8_param_swap()
369 wrapper_cls = wrapper_module.BlockMXTrainingWeightWrapperTensor361 wrapper_cls = wrapper_module.BlockMXTrainingWeightWrapperTensor
370- monkeypatch.setitem(sys.modules, "cann_ops_nn.ops", ModuleType("cann_ops_nn.ops"))362+ source = converter_module.GroupedLinear.Config(group_size=2, in_features=32, out_features=32, num_linears=2)
371- source = converter_module.GroupedExperts.Config(dim=32, hidden_dim=32, num_experts=2)
372 converter = converter_module.NpuQuantizeConverter.Config(363 converter = converter_module.NpuQuantizeConverter.Config(
373 base_config=quant_config,364 base_config=quant_config,
374 unified_npu_quant_modules=converter_module.UNIFIED_NPU_QUANTIZED_MODULES,365 unified_npu_quant_modules=converter_module.UNIFIED_NPU_QUANTIZED_MODULES,
375 specific_npu_quant_modules=converter_module.SPECIFIC_NPU_QUANTIZED_MODULES,366 specific_npu_quant_modules=converter_module.SPECIFIC_NPU_QUANTIZED_MODULES,
376 ).build()367 ).build()
377 368 
378- # Keep real quantize_, parameter wrappers, casts and torch._grouped_mm
379- # dispatch. Replace only the NPU grouped-matmul and SwiGLU boundaries.
380 with torch.random.fork_rng(devices=[]):369 with torch.random.fork_rng(devices=[]):
381- experts = converter.convert(source).build()370+ projection = converter.convert(source).build()
382- for weight in (experts.w1_EFD, experts.w3_EFD, experts.w2_EDF):371+ assert isinstance(projection.weight, wrapper_cls)
383- assert isinstance(weight, wrapper_cls)372+ assert isinstance(projection.weight.flatten(1, -2).bfloat16().transpose(-2, -1), wrapper_cls)
384- assert isinstance(weight.bfloat16().transpose(-2, -1), wrapper_cls)
385- 
386 matmul_calls = []373 matmul_calls = []
387 374 
388 def quantized_grouped_mm(x, weight, offsets, activation_config, weight_config):375 def quantized_grouped_mm(x, weight, offsets, activation_config, weight_config):
@@ -390,40 +377,21 @@ def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, conver
390 return torch.cat((x[:1] @ weight[0], x[1:] @ weight[1]))377 return torch.cat((x[:1] @ weight[0], x[1:] @ weight[1]))
391 378 
392 monkeypatch.setattr(wrapper_module, f"to_{quant_format}_then_grouped_mm", quantized_grouped_mm)379 monkeypatch.setattr(wrapper_module, f"to_{quant_format}_then_grouped_mm", quantized_grouped_mm)
393- swiglu_calls = []
394- 
395- def swiglu(x, *, weight, group_index, clamp_limit):
396- swiglu_calls.append((x, weight, group_index, clamp_limit))
397- # This fixed boundary contract isolates dispatch from CANN numerics.
398- return (x[..., :32].float() * weight.reshape(-1, 1)).to(x.dtype)
399- 
400- monkeypatch.setattr(torch.ops, "cann_ops_nn", SimpleNamespace(swiglu_group=SimpleNamespace(default=swiglu)))
401- ascendc = importlib.import_module("torchtitan_npu.override.common.swiglu_group.ascendc")
402- monkeypatch.setattr(ascendc, "get_spmd_backend", lambda: "torch")
403 with torch.no_grad():380 with torch.no_grad():
404 identity = torch.eye(32)381 identity = torch.eye(32)
405- experts.w1_EFD.copy_(torch.stack((identity, identity * 2)))382+ projection.weight.copy_(
406- experts.w3_EFD.copy_(torch.stack((identity * 0.5, identity * 1.5)))383+ torch.stack((torch.stack((identity, identity * 2)), torch.stack((identity * 3, identity * 4))))
407- experts.w2_EDF.copy_(torch.stack((identity * 3, identity * 4)))384+ )
408- scores = torch.tensor([0.25, 0.5, 0.75])
409 385 
410- output = experts(torch.full((3, 32), 0.25), torch.tensor([1, 2]), routed_scores_R=scores)386+ output = projection(torch.full((3, 32), 0.25, dtype=torch.bfloat16), torch.tensor([1, 3], dtype=torch.int32))
411 387 
412- torch.testing.assert_close(output, torch.tensor([[0.1875], [1.0], [1.5]]).expand(3, 32))388+ expected = torch.tensor([[[0.25], [0.5]], [[0.75], [1.0]], [[0.75], [1.0]]], dtype=torch.bfloat16).expand(3, 2, 32)
413- assert len(matmul_calls) == 3389+ torch.testing.assert_close(output, expected)
414- for offsets, activation_config, weight_config in matmul_calls:390+ assert len(matmul_calls) == 1
415- torch.testing.assert_close(offsets, torch.tensor([1, 3], dtype=torch.int32))391+ offsets, activation_config, weight_config = matmul_calls[0]
416- assert activation_config is quant_config.activation_config392+ torch.testing.assert_close(offsets, torch.tensor([1, 3], dtype=torch.int32))
417- assert weight_config is quant_config.weight_config393+ assert activation_config is quant_config.activation_config
418- assert len(swiglu_calls) == 1394+ assert weight_config is quant_config.weight_config
419- packed, weight, group_index, clamp_limit = swiglu_calls[0]
420- torch.testing.assert_close(packed[:, :32], torch.tensor([[0.25], [0.5], [0.5]], dtype=torch.bfloat16).expand(3, 32))
421- torch.testing.assert_close(
422- packed[:, 32:], torch.tensor([[0.125], [0.375], [0.375]], dtype=torch.bfloat16).expand(3, 32)
423- )
424- torch.testing.assert_close(weight, scores)
425- assert group_index is None
426- assert clamp_limit == -1.0
427 395 
428 396 
429@pytest.mark.parametrize("enabled", [False, True], ids=["disabled", "enabled"])397@pytest.mark.parametrize("enabled", [False, True], ids=["disabled", "enabled"])
@@ -444,7 +412,7 @@ def test_v41_recipe_couples_source_compressor_and_sparse_attention(converter_mod
444 model_compile_enabled=False,412 model_compile_enabled=False,
445 )413 )
446 414 
447- for layer in converted.model.layers:415+ for layer in converted.layers:
448 compressor = layer.attention.compressor416 compressor = layer.attention.compressor
449 compressor_quant = getattr(compressor, "_torchao_npu_config", None)417 compressor_quant = getattr(compressor, "_torchao_npu_config", None)
450 attention_quant = getattr(layer.attention.inner_attention, "_torchao_npu_config", None)418 attention_quant = getattr(layer.attention.inner_attention, "_torchao_npu_config", None)
@@ -460,15 +428,16 @@ def test_v41_recipe_couples_source_compressor_and_sparse_attention(converter_mod
460def _source_compressor_layer(spec, ratio):428def _source_compressor_layer(spec, ratio):
461 return next(429 return next(
462 i430 i
463- for i, layer in enumerate(spec.model.layers)431+ for i, layer in enumerate(spec.layers)
464 if layer.attention.compressor.is_source and layer.attention.compressor.compress_ratio == ratio432 if layer.attention.compressor.is_source and layer.attention.compressor.compress_ratio == ratio
465 )433 )
466 434 
467 435 
468def _build_cpu_compressor(config):436def _build_cpu_compressor(config):
469 module = config.build()437 module = config.build()
438+ module._apply(lambda value: value.to(dtype=torch.bfloat16) if value.is_floating_point() else value)
470 module.init_states(buffer_device=torch.device("cpu"))439 module.init_states(buffer_device=torch.device("cpu"))
471- return module.to(dtype=torch.bfloat16)440+ return module
472 441 
473 442 
474def _capture_compressor_encoding(monkeypatch, width):443def _capture_compressor_encoding(monkeypatch, width):
@@ -520,10 +489,10 @@ def test_v41_teacher_pair_survives_each_supported_switch_combination(
520 "torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc",489 "torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc",
521 ]490 ]
522 ),491 ),
523- converted.model,492+ converted,
524 )493 )
525 494 
526- for layer in converted.model.layers:495+ for layer in converted.layers:
527 selector = layer.attention.indexer.selector496 selector = layer.attention.indexer.selector
528 inner_attention = layer.attention.inner_attention497 inner_attention = layer.attention.inner_attention
529 selector_quant = getattr(selector, "_torchao_npu_config", None)498 selector_quant = getattr(selector, "_torchao_npu_config", None)
@@ -573,15 +542,15 @@ def test_converted_v41_compressor_quantizes_post_rope_and_preserves_gradients(co
573 layer_id = _source_compressor_layer(reference_spec, ratio)542 layer_id = _source_compressor_layer(reference_spec, ratio)
574 with torch.random.fork_rng(devices=[]):543 with torch.random.fork_rng(devices=[]):
575 torch.manual_seed(17)544 torch.manual_seed(17)
576- reference = _build_cpu_compressor(reference_spec.model.layers[layer_id].attention.compressor)545+ reference = _build_cpu_compressor(reference_spec.layers[layer_id].attention.compressor)
577- quantized = _build_cpu_compressor(converted.model.layers[layer_id].attention.compressor)546+ quantized = _build_cpu_compressor(converted.layers[layer_id].attention.compressor)
578 quantized.load_state_dict(reference.state_dict())547 quantized.load_state_dict(reference.state_dict())
579- d = reference_spec.model.layers[layer_id].attention.compressor.wkv.out_features548+ d = reference_spec.layers[layer_id].attention.compressor.wkv.out_features
580 captured = _capture_compressor_encoding(monkeypatch, d)549 captured = _capture_compressor_encoding(monkeypatch, d)
581- dim = reference_spec.model.dim550+ dim = reference_spec.dim
582- x_ref = torch.linspace(-1, 1, 4 * dim, dtype=torch.bfloat16).reshape(1, 4, dim).requires_grad_()551+ x_ref = torch.linspace(-1, 1, 4 * dim, dtype=torch.bfloat16).reshape(4, dim).requires_grad_()
583 x_quant = x_ref.detach().clone().requires_grad_()552 x_quant = x_ref.detach().clone().requires_grad_()
584- positions = torch.arange(4).unsqueeze(0)553+ positions = torch.arange(4)
585 554 
586 expected_kv, expected_latent = reference(x_ref, positions)555 expected_kv, expected_latent = reference(x_ref, positions)
587 actual_kv, actual_latent = quantized(x_quant, positions)556 actual_kv, actual_latent = quantized(x_quant, positions)
@@ -592,7 +561,7 @@ def test_converted_v41_compressor_quantizes_post_rope_and_preserves_gradients(co
592 expected_qdq = torch.tensor([0.25, 0.5], dtype=actual_kv.dtype).repeat(actual_kv.numel() // 2).reshape_as(actual_kv)561 expected_qdq = torch.tensor([0.25, 0.5], dtype=actual_kv.dtype).repeat(actual_kv.numel() // 2).reshape_as(actual_kv)
593 assert torch.equal(actual_kv, expected_qdq)562 assert torch.equal(actual_kv, expected_qdq)
594 assert actual_kv.dtype == expected_kv.dtype563 assert actual_kv.dtype == expected_kv.dtype
595- reuser = converted.model.layers[layer_id + 1].attention.compressor.build()564+ reuser = converted.layers[layer_id + 1].attention.compressor.build()
596 shared, latent = reuser(x_quant, positions, actual_kv)565 shared, latent = reuser(x_quant, positions, actual_kv)
597 assert shared is actual_kv566 assert shared is actual_kv
598 assert latent is None567 assert latent is None
@@ -23,14 +23,13 @@ import pytest
23pytest.importorskip("torchao")23pytest.importorskip("torchao")
24pytest.importorskip("torchao_npu")24pytest.importorskip("torchao_npu")
25 25 
26-from torchtitan.models.common.linear import Linear26+from torchtitan.models.common.linear import GroupedLinear, Linear
27 27 
28from torchtitan_npu.config.configs import QuantizationExtensionConfig28from torchtitan_npu.config.configs import QuantizationExtensionConfig
29from torchtitan_npu.extensions.adaptor.torchao.configs import get_model_config29from torchtitan_npu.extensions.adaptor.torchao.configs import get_model_config
30from torchtitan_npu.extensions.adaptor.torchao.converter import (30from torchtitan_npu.extensions.adaptor.torchao.converter import (
31- NpuQuantizedAscGroupedExpertsModule,
32 _match_fqn_suffix,31 _match_fqn_suffix,
33- _model_type_for_spec,32+ _model_type_for_config,
34 apply_quantization_converter,33 apply_quantization_converter,
35)34)
36from torchtitan_npu.models.deepseek_v4 import model_registry35from torchtitan_npu.models.deepseek_v4 import model_registry
@@ -58,7 +57,7 @@ def test_default_whitelist_keeps_prequantize_on_all_dense_projections():
58 57 
59 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)58 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)
60 59 
61- flags = _collect_flags(converted.model)60+ flags = _collect_flags(converted)
62 assert flags, "debugmodel must expose quantized Linear nodes"61 assert flags, "debugmodel must expose quantized Linear nodes"
63 assert all(flags.values()), f"default whitelist must enable every dense weight: {flags}"62 assert all(flags.values()), f"default whitelist must enable every dense weight: {flags}"
64 63 
@@ -73,7 +72,7 @@ def test_user_whitelist_disables_non_whitelisted_weights():
73 72 
74 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)73 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)
75 74 
76- flags = _collect_flags(converted.model)75+ flags = _collect_flags(converted)
77 wq_a = [flag for fqn, flag in flags.items() if fqn.endswith(".attention.wq_a")]76 wq_a = [flag for fqn, flag in flags.items() if fqn.endswith(".attention.wq_a")]
78 wkv = [flag for fqn, flag in flags.items() if fqn.endswith(".attention.wkv")]77 wkv = [flag for fqn, flag in flags.items() if fqn.endswith(".attention.wkv")]
79 assert wq_a and all(wq_a), "whitelisted wq_a must stay enabled"78 assert wq_a and all(wq_a), "whitelisted wq_a must stay enabled"
@@ -108,7 +107,7 @@ def test_master_switch_off_leaves_policy_inert():
108 107 
109 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)108 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)
110 109 
111- flags = _collect_flags(converted.model)110+ flags = _collect_flags(converted)
112 assert flags and not any(flags.values()), "disabled master switch must keep every weight off pre-quantize"111 assert flags and not any(flags.values()), "disabled master switch must keep every weight off pre-quantize"
113 112 
114 113 
@@ -125,14 +124,13 @@ def test_default_whitelist_covers_every_quantized_projection():
125 quantization = _quantization_config(enable_fsdp_prequantize=True)124 quantization = _quantization_config(enable_fsdp_prequantize=True)
126 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)125 converted = apply_quantization_converter(spec, quantization, model_compile_enabled=False)
127 126 
128- defaults = get_model_config(_model_type_for_spec(spec)).prequantize_default_fqns127+ defaults = get_model_config(_model_type_for_config(spec)).prequantize_default_fqns
129 all_patterns = tuple(pattern for scope in defaults.values() for pattern in scope)128 all_patterns = tuple(pattern for scope in defaults.values() for pattern in scope)
130- flags = _collect_flags(converted.model)129+ flags = _collect_flags(converted)
131 assert flags, "debugmodel must expose quantized Linear nodes"130 assert flags, "debugmodel must expose quantized Linear nodes"
132 for fqn in flags:131 for fqn in flags:
133 assert any(_match_fqn_suffix(fqn, pattern) for pattern in all_patterns), (132 assert any(_match_fqn_suffix(fqn, pattern) for pattern in all_patterns), (
134- f"quantized weight {fqn!r} matches no default whitelist entry; "133+ f"quantized weight {fqn!r} matches no default whitelist entry; update the model's prequantize_default_fqns"
135- f"update the model's prequantize_default_fqns"
136 )134 )
137 135 
138 136 
@@ -146,7 +144,7 @@ def test_mxfp4_communication_keeps_dense_fp8_and_experts_mxfp4():
146 converted = apply_quantization_converter(spec, config, model_compile_enabled=False)144 converted = apply_quantization_converter(spec, config, model_compile_enabled=False)
147 dense_weights = [145 dense_weights = [
148 node._torchao_npu_config.weight_config146 node._torchao_npu_config.weight_config
149- for _, node, _, _ in converted.model.traverse(Linear.Config)147+ for _, node, _, _ in converted.traverse(Linear.Config)
150 if getattr(node, "_torchao_npu_config", None) is not None148 if getattr(node, "_torchao_npu_config", None) is not None
151 ]149 ]
152 assert dense_weights150 assert dense_weights
@@ -154,7 +152,7 @@ def test_mxfp4_communication_keeps_dense_fp8_and_experts_mxfp4():
154 assert weight.fsdp_prequantize152 assert weight.fsdp_prequantize
155 assert weight.fsdp_prequantize_dtype == "fp8"153 assert weight.fsdp_prequantize_dtype == "fp8"
156 assert weight.mxfp4_fake_quantize_config is None154 assert weight.mxfp4_fake_quantize_config is None
157- experts = list(converted.model.traverse(NpuQuantizedAscGroupedExpertsModule.Config))155+ experts = list(converted.traverse(GroupedLinear.Config))
158 assert experts156 assert experts
159 for _, node, _, _ in experts:157 for _, node, _, _ in experts:
160 weight = node._torchao_npu_config.weight_config158 weight = node._torchao_npu_config.weight_config
@@ -169,14 +167,14 @@ def test_mxfp4_communication_config_reaches_only_selected_experts():
169 enable_mxfp4_qat=True,167 enable_mxfp4_qat=True,
170 enable_fsdp_prequantize=True,168 enable_fsdp_prequantize=True,
171 fsdp_prequantize_dtype="mxfp4",169 fsdp_prequantize_dtype="mxfp4",
172- fsdp_prequantize_fqns=[".moe.routed_experts.inner_experts"],170+ fsdp_prequantize_fqns=[".moe.routed_experts.w13", ".moe.routed_experts.w2"],
173 )171 )
174 converted = apply_quantization_converter(spec, config, model_compile_enabled=False)172 converted = apply_quantization_converter(spec, config, model_compile_enabled=False)
175- experts = list(converted.model.traverse(NpuQuantizedAscGroupedExpertsModule.Config))173+ experts = list(converted.traverse(GroupedLinear.Config))
176 assert experts174 assert experts
177 for _, node, _, _ in experts:175 for _, node, _, _ in experts:
178 weight = node._torchao_npu_config.weight_config176 weight = node._torchao_npu_config.weight_config
179 assert weight.fsdp_prequantize177 assert weight.fsdp_prequantize
180 assert weight.fsdp_prequantize_dtype == "mxfp4"178 assert weight.fsdp_prequantize_dtype == "mxfp4"
181 assert weight.mxfp4_fake_quantize_config is not None179 assert weight.mxfp4_fake_quantize_config is not None
182- assert not any(_collect_flags(converted.model).values())180+ assert not any(_collect_flags(converted).values())
@@ -0,0 +1,82 @@
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+from types import SimpleNamespace
7+ 
8+import pytest
9+import torch
10+from torchtitan.components.optim import AdamW, LRSchedulersContainer
11+ 
12+from torchtitan_npu.config import OptimConfig
13+from torchtitan_npu.extensions.components.gradient_clipping import GradientClippingOptim
14+from torchtitan_npu.extensions.torchtitan.components.optimizer.optimizer import HostSparseOptimizersContainer
15+ 
16+ 
17+def _parallelism_context():
18+ return SimpleNamespace(
19+ get_optional_mesh=lambda _name: None,
20+ pp_enabled=False,
21+ ep_enabled=False,
22+ )
23+ 
24+ 
25+def test_optimization_uses_container_clipping_before_update(monkeypatch):
26+ model = torch.nn.Linear(2, 1, bias=False)
27+ model.weight.data.copy_(torch.tensor([[1.0, -2.0]]))
28+ expected = torch.nn.Parameter(model.weight.detach().clone())
29+ reference = torch.optim.AdamW([expected], lr=0.1, eps=0.01, weight_decay=0.0, fused=False)
30+ grad = torch.tensor([[3.0, 4.0]])
31+ expected.grad = grad.clone()
32+ expected_norm = torch.nn.utils.clip_grad_norm_([expected], 1.0)
33+ reference.step()
34+ calls = []
35+ original_clip = HostSparseOptimizersContainer.clip_grad_norm
36+ 
37+ def record_clip(container, parameters, max_norm, **kwargs):
38+ calls.append(max_norm)
39+ return original_clip(container, parameters, max_norm, **kwargs)
40+ 
41+ monkeypatch.setattr(HostSparseOptimizersContainer, "clip_grad_norm", record_clip)
42+ config = OptimConfig(
43+ optimizer=HostSparseOptimizersContainer.Config(
44+ optimizers=[AdamW.Config(pattern=".*", lr=0.1, eps=0.01, weight_decay=0.0, fused=False)]
45+ ),
46+ lr_scheduler=LRSchedulersContainer.Config(warmup_steps=0),
47+ max_norm=1.0,
48+ )
49+ optim = config.build(
50+ model_parts=[model],
51+ parallelism_context=_parallelism_context(),
52+ training_steps=10,
53+ pp_has_last_stage=True,
54+ )
55+ model.weight.grad = grad.clone()
56+ 
57+ norm = optim.step(torch.tensor(1.0), current_step=1)
58+ 
59+ assert isinstance(optim, GradientClippingOptim)
60+ assert calls == [1.0]
61+ torch.testing.assert_close(norm, expected_norm)
62+ torch.testing.assert_close(model.weight, expected)
63+ 
64+ 
65+def test_nonfinite_loss_does_not_commit_optimizer_update():
66+ model = torch.nn.Linear(2, 1, bias=False)
67+ before = model.weight.detach().clone()
68+ config = OptimConfig(
69+ optimizer=HostSparseOptimizersContainer.Config(optimizers=[AdamW.Config(pattern=".*", lr=0.1, fused=False)])
70+ )
71+ optim = config.build(
72+ model_parts=[model],
73+ parallelism_context=_parallelism_context(),
74+ training_steps=10,
75+ pp_has_last_stage=True,
76+ )
77+ model.weight.grad = torch.ones_like(model.weight)
78+ 
79+ with pytest.raises(RuntimeError, match="Loss or gradient norm is not finite"):
80+ optim.step(torch.tensor(float("nan")), current_step=1)
81+ 
82+ torch.testing.assert_close(model.weight, before)
@@ -17,6 +17,7 @@ import logging
17import os17import os
18import threading18import threading
19 19 
20+import pytest
20import torch21import torch
21import torch.distributed as dist22import torch.distributed as dist
22import torch.nn as nn23import torch.nn as nn
@@ -24,17 +25,13 @@ import torch_npu
24from torch.distributed.device_mesh import init_device_mesh25from torch.distributed.device_mesh import init_device_mesh
25from torch.distributed.fsdp._fully_shard import fully_shard26from torch.distributed.fsdp._fully_shard import fully_shard
26from torch.distributed.fsdp._fully_shard._fsdp_api import CPUOffloadPolicy27from torch.distributed.fsdp._fully_shard._fsdp_api import CPUOffloadPolicy
27-from torchtitan.components.optimizer import ParamGroupConfig28+from torchtitan.components.optim import AdamW
28 29 
29import torchtitan_npu.extensions.cpu_offload.runtime as clip_state30import torchtitan_npu.extensions.cpu_offload.runtime as clip_state
30from torchtitan_npu.extensions.distributed import grad_accum, grad_clip31from torchtitan_npu.extensions.distributed import grad_accum, grad_clip
31from torchtitan_npu.override.common.optimizer import CpuOffloadOptimizersContainer32from torchtitan_npu.override.common.optimizer import CpuOffloadOptimizersContainer
32 33 
33-import pytest34+pytestmark = pytest.mark.skipif(not torch_npu.npu.is_available(), reason="NPU not available")
34- 
35-pytestmark = pytest.mark.skipif(
36- not torch_npu.npu.is_available(), reason='NPU not available'
37-)
38 35 
39 36 
40logging.basicConfig(level=logging.INFO, force=True)37logging.basicConfig(level=logging.INFO, force=True)
@@ -74,7 +71,11 @@ def main() -> None:
74 71 
75 container = CpuOffloadOptimizersContainer(72 container = CpuOffloadOptimizersContainer(
76 CpuOffloadOptimizersContainer.Config(73 CpuOffloadOptimizersContainer.Config(
77- param_groups=[ParamGroupConfig(pattern=".*", optimizer_name="AdamW", optimizer_kwargs={"lr": 1e-2})]74+ optimizers=[
75+ AdamW.Config(
76+ pattern=".*", fused=False, foreach=False, betas=(0.9, 0.999), weight_decay=0.01, lr=0.01
77+ )
78+ ]
78 ),79 ),
79 model_parts=[model],80 model_parts=[model],
80 )81 )
@@ -19,9 +19,7 @@ from torchtitan_npu.extensions.cpu_offload.cpu_offload_adamw import CpuOffloadAd
19from torchtitan_npu.extensions.cpu_offload.staging import CpuStaging19from torchtitan_npu.extensions.cpu_offload.staging import CpuStaging
20from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx20from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
21 21 
22-requires_npu = pytest.mark.skipif(22+requires_npu = pytest.mark.skipif(not torch_npu.npu.is_available(), reason="NPU not available")
23- not torch_npu.npu.is_available(), reason="NPU not available"
24-)
25 23 
26 24 
27def _muon_factory_kwargs(*, enable_hsdp_replica_dedup: bool) -> dict[str, object]:25def _muon_factory_kwargs(*, enable_hsdp_replica_dedup: bool) -> dict[str, object]:
@@ -93,9 +91,7 @@ def test_cpu_offload_muon_factory_rejects_enabled_replica_dedup() -> None:
93 )91 )
94 92 
95 93 
96-def _step_sequence(94+def _step_sequence(offload_states: bool, grads: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor, set[int], str]:
97- offload_states: bool, grads: list[torch.Tensor]
98-) -> tuple[torch.Tensor, torch.Tensor, set[int], str]:
99 torch.manual_seed(0)95 torch.manual_seed(0)
100 parameter = torch.nn.Parameter(torch.randn(4, 6))96 parameter = torch.nn.Parameter(torch.randn(4, 6))
101 device = torch.device("npu", torch_npu.npu.current_device())97 device = torch.device("npu", torch_npu.npu.current_device())
@@ -151,6 +147,7 @@ def test_enable_cpu_offload_defaults_to_npu_resident_state(monkeypatch) -> None:
151 from dataclasses import replace147 from dataclasses import replace
152 148 
153 from torchtitan_npu.extensions import trainer as trainer_module149 from torchtitan_npu.extensions import trainer as trainer_module
150+ from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel
154 from torchtitan_npu.override.common.optimizer import (151 from torchtitan_npu.override.common.optimizer import (
155 CpuOffloadNpuStateOptimizersContainer,152 CpuOffloadNpuStateOptimizersContainer,
156 CpuOffloadOptimizersContainer,153 CpuOffloadOptimizersContainer,
@@ -164,20 +161,23 @@ def test_enable_cpu_offload_defaults_to_npu_resident_state(monkeypatch) -> None:
164 captured: dict[str, object] = {}161 captured: dict[str, object] = {}
165 162 
166 def capture_runtime(self, runtime) -> None:163 def capture_runtime(self, runtime) -> None:
167- captured["optimizer"] = runtime.optimizer164+ captured["optimizer"] = runtime.optim.optimizer
168 raise ReachedUpstreamError165 raise ReachedUpstreamError
169 166 
170 monkeypatch.setattr(trainer_module, "set_allow_hf32", lambda _: None)167 monkeypatch.setattr(trainer_module, "set_allow_hf32", lambda _: None)
171 monkeypatch.setattr(cpu_dtensor_init, "install", lambda: None)168 monkeypatch.setattr(cpu_dtensor_init, "install", lambda: None)
172 monkeypatch.setattr(trainer_module.Trainer, "__init__", capture_runtime)169 monkeypatch.setattr(trainer_module.Trainer, "__init__", capture_runtime)
173 170 
174- config = TrainerEx.Config(training=TrainingConfig(enable_cpu_offload=True))171+ config = TrainerEx.Config(
172+ model=deepseek_v4_debugmodel().model,
173+ training=TrainingConfig(enable_cpu_offload=True),
174+ )
175 # Config rebuilds keep the plain schema: the derive happens exactly once,175 # Config rebuilds keep the plain schema: the derive happens exactly once,
176 # at trainer construction (regression: config.build() does replace(self),176 # at trainer construction (regression: config.build() does replace(self),
177 # which re-runs __post_init__ on the already-derived node).177 # which re-runs __post_init__ on the already-derived node).
178 for cfg in (config, replace(config)):178 for cfg in (config, replace(config)):
179- assert type(cfg.optimizer) is OptimizerConfig179+ assert type(cfg.optim.optimizer) is OptimizerConfig
180- assert isinstance(cfg.optimizer.materialize(), type(None))180+ assert isinstance(cfg.optim.optimizer.materialize(), type(None))
181 181 
182 with pytest.raises(ReachedUpstreamError):182 with pytest.raises(ReachedUpstreamError):
183 TrainerEx(config)183 TrainerEx(config)
@@ -191,8 +191,8 @@ def test_enable_cpu_offload_defaults_to_npu_resident_state(monkeypatch) -> None:
191 assert not isinstance(derived, CpuOffloadNpuStateOptimizersContainer.Config)191 assert not isinstance(derived, CpuOffloadNpuStateOptimizersContainer.Config)
192 192 
193 # Without the offload switch the optimizer schema stays untouched.193 # Without the offload switch the optimizer schema stays untouched.
194- plain = TrainerEx.Config()194+ plain = TrainerEx.Config(model=config.model)
195- assert type(plain.optimizer) is OptimizerConfig195+ assert type(plain.optim.optimizer) is OptimizerConfig
196 196 
197 197 
198@requires_npu198@requires_npu
@@ -204,8 +204,13 @@ def test_adamw_restore_continues_on_compute_device() -> None:
204 parameter = torch.nn.Parameter(torch.randn(4, 6))204 parameter = torch.nn.Parameter(torch.randn(4, 6))
205 staging = CpuStaging(device, owner="test-restore")205 staging = CpuStaging(device, owner="test-restore")
206 optimizer = CpuOffloadAdamW(206 optimizer = CpuOffloadAdamW(
207- [parameter], lr=1e-2, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1,207+ [parameter],
208- staging=staging, offload_states=False,208+ lr=1e-2,
209+ betas=(0.9, 0.95),
210+ eps=1e-8,
211+ weight_decay=0.1,
212+ staging=staging,
213+ offload_states=False,
209 )214 )
210 return optimizer, parameter215 return optimizer, parameter
211 216 
@@ -288,9 +293,7 @@ def test_muon_checkpoint_roundtrip_steps_on_compute_device() -> None:
288 return build_cpu_offload_distributed_muon(293 return build_cpu_offload_distributed_muon(
289 [{"params": [parameter], "param_names": ["weight"]}],294 [{"params": [parameter], "param_names": ["weight"]}],
290 staging=staging,295 staging=staging,
291- compute_sharding_by_fqn={296+ compute_sharding_by_fqn={"weight": ComputeLayout(shardings_by_mesh_axis={"dp_shard": Owned()})},
292- "weight": ComputeLayout(shardings_by_mesh_axis={"dp_shard": Owned()})
293- },
294 bucket_configs=[BucketConfig(patterns=("weight",), name="test")],297 bucket_configs=[BucketConfig(patterns=("weight",), name="test")],
295 offload_states=False,298 offload_states=False,
296 lr=1e-2,299 lr=1e-2,
@@ -12,13 +12,19 @@ from types import SimpleNamespace
12import pytest12import pytest
13import torch13import torch
14from torch import nn14from torch import nn
15+from torchtitan.components.data.types import TrainingMicrobatch
16+from torchtitan.components.optim import Optim
17+from torchtitan.models.common.activation import Sigmoid
18+from torchtitan.models.common.linear import RouterGateLinear
15from torchtitan.models.common.moe import TokenChoiceTopKRouter19from torchtitan.models.common.moe import TokenChoiceTopKRouter
20+from torchtitan.training_engine import TrainingEngine
16 21 
22+from torchtitan_npu.config.configs import CompileConfig, ModelCompileConfig
17from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode23from torchtitan_npu.extensions.experiment.anticipatory_routing.cache import RoutingMode
18from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig24from torchtitan_npu.extensions.experiment.anticipatory_routing.config import AnticipatoryRoutingConfig
19from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache25from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache
20from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase26from torchtitan_npu.extensions.experiment.anticipatory_routing.schedule import AnticipatorySchedule, Phase
21-from torchtitan_npu.extensions.torchtitan.trainer import Trainer, TrainerEx27+from torchtitan_npu.extensions.torchtitan.trainer import NPUTrainingEngine, TrainerEx
22 28 
23 29 
24class Scheduler(torch.optim.lr_scheduler.StepLR):30class Scheduler(torch.optim.lr_scheduler.StepLR):
@@ -73,7 +73,7 @@ def test_detection_only_skips_checkpoint_requirements_but_rejects_pp():
73 anticipatory=AnticipatoryRoutingConfig(enable=True, max_rollbacks=0),73 anticipatory=AnticipatoryRoutingConfig(enable=True, max_rollbacks=0),
74 parallelism=SimpleNamespace(pipeline_parallel_degree=1),74 parallelism=SimpleNamespace(pipeline_parallel_degree=1),
75 debug=SimpleNamespace(moe_force_load_balance=False),75 debug=SimpleNamespace(moe_force_load_balance=False),
76- checkpoint=SimpleNamespace(enable=False, load_only=True, exclude_from_loading=["optimizer"]),76+ checkpointer=SimpleNamespace(load_only=True, exclude_from_loading=["optimizer"]),
77 )77 )
78 validate_anticipatory_config(config)78 validate_anticipatory_config(config)
79 config.anticipatory.max_rollbacks = 179 config.anticipatory.max_rollbacks = 1
@@ -10,44 +10,33 @@ import torch.distributed as dist
10import torch.multiprocessing as mp10import torch.multiprocessing as mp
11import torch.nn.functional as F11import torch.nn.functional as F
12from torch.distributed.device_mesh import init_device_mesh12from torch.distributed.device_mesh import init_device_mesh
13-from torch.distributed.tensor import DTensor, Replicate, Shard, distribute_tensor13+from torch.distributed.tensor import DTensor, Partial, Replicate, Shard, distribute_tensor
14 14 
15from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache15from torchtitan_npu.extensions.experiment.anticipatory_routing.router import build_routing_cache
16from torchtitan_npu.models.deepseek_v4_1.moe import DeepSeekV41Router16from torchtitan_npu.models.deepseek_v4_1.moe import DeepSeekV41Router
17 17 
18 18 
19def _router():19def _router():
20- from torchtitan.models.common.linear import Linear20+ from torchtitan.models.common.activation import Sigmoid
21- from torchtitan.models.common.moe import GroupedExperts, MoE, RoutedExperts21+ from torchtitan.models.common.linear import RouterGateLinear
22 22 
23- from torchtitan_npu.patches.torchtitan.models.common.token_dispatcher import LocalTokenDispatcher23+ config = DeepSeekV41Router.Config(
24- 
25- config = MoE.Config(
26 num_experts=4,24 num_experts=4,
27- router=DeepSeekV41Router.Config(25+ gate=RouterGateLinear.Config(in_features=4, out_features=4),
28- num_experts=4,26+ score_func=Sigmoid.Config(),
29- gate=Linear.Config(in_features=4, out_features=4),27+ top_k=2,
30- top_k=2,28+ sorted_topk=True,
31- sorted_topk=True,29+ route_norm=True,
32- route_norm=True,30+ route_scale=1.4,
33- route_scale=1.4,
34- ),
35- routed_experts=RoutedExperts.Config(
36- inner_experts=GroupedExperts.Config(dim=4, hidden_dim=4, num_experts=4),
37- token_dispatcher=LocalTokenDispatcher.Config(num_experts=4, top_k=2),
38- ),
39 )31 )
40 with torch.random.fork_rng(devices=[]):32 with torch.random.fork_rng(devices=[]):
41- result = config.router.build()33+ result = config.build()
42 assert isinstance(result, DeepSeekV41Router)34 assert isinstance(result, DeepSeekV41Router)
43 return result35 return result
44 36 
45 37 
46def _replay_worker(rank, rendezvous):38def _replay_worker(rank, rendezvous):
47- from torchtitan.distributed.utils import set_spmd_backend
48- 
49 torch.set_num_threads(1)39 torch.set_num_threads(1)
50- set_spmd_backend("partial_dtensor")
51 dist.init_process_group("gloo", init_method=f"file://{rendezvous}", rank=rank, world_size=2)40 dist.init_process_group("gloo", init_method=f"file://{rendezvous}", rank=rank, world_size=2)
52 cache = None41 cache = None
53 try:42 try:
@@ -67,6 +56,8 @@ def _replay_worker(rank, rendezvous):
67 )56 )
68 router = _router()57 router = _router()
69 router.gate.weight = torch.nn.Parameter(distribute_tensor(capture_weight.clone(), mesh, [Replicate()]))58 router.gate.weight = torch.nn.Parameter(distribute_tensor(capture_weight.clone(), mesh, [Replicate()]))
59+ # Token statistics are rank-local partial sums, as in the upstream router sharding plan.
60+ router.tokens_per_expert_E = DTensor.from_local(torch.zeros(4), mesh, [Partial()], run_check=False)
70 sharded_inputs = distribute_tensor(inputs.clone(), mesh, [Shard(0)]).requires_grad_()61 sharded_inputs = distribute_tensor(inputs.clone(), mesh, [Shard(0)]).requires_grad_()
71 cache = build_routing_cache([router], index_store_dtype="int16", device=torch.device("cpu"))62 cache = build_routing_cache([router], index_store_dtype="int16", device=torch.device("cpu"))
72 key = router._anticipatory_key63 key = router._anticipatory_key
@@ -102,7 +93,7 @@ def _replay_worker(rank, rendezvous):
102 93 
103 cache.begin_training([slot])94 cache.begin_training([slot])
104 cache.select(0)95 cache.select(0)
105- selected, replay_ids, scores = router(sharded_inputs)96+ selected, replay_ids, routing_map = router(sharded_inputs)
106 assert isinstance(replay_ids, DTensor)97 assert isinstance(replay_ids, DTensor)
107 assert replay_ids.device_mesh == mesh and replay_ids.placements == (Shard(0),)98 assert replay_ids.device_mesh == mesh and replay_ids.placements == (Shard(0),)
108 assert replay_ids.shape == (6, 2) and replay_ids.to_local().shape == (3, 2)99 assert replay_ids.shape == (6, 2) and replay_ids.to_local().shape == (3, 2)
@@ -111,7 +102,8 @@ def _replay_worker(rank, rendezvous):
111 assert not torch.equal(live_scores.topk(2, -1).indices, expected_ids)102 assert not torch.equal(live_scores.topk(2, -1).indices, expected_ids)
112 reference_selected = live_scores.gather(-1, expected_ids)103 reference_selected = live_scores.gather(-1, expected_ids)
113 reference_selected = reference_selected / (reference_selected.sum(-1, keepdim=True) + 1e-20) * 1.4104 reference_selected = reference_selected / (reference_selected.sum(-1, keepdim=True) + 1e-20) * 1.4
114- torch.testing.assert_close(scores.full_tensor(), live_scores, rtol=1e-6, atol=1e-7)105+ expected_map = torch.zeros_like(live_scores, dtype=torch.bool).scatter_(-1, expected_ids, True)
106+ torch.testing.assert_close(routing_map.full_tensor(), expected_map, rtol=0, atol=0)
115 torch.testing.assert_close(selected.full_tensor(), reference_selected, rtol=1e-6, atol=1e-7)107 torch.testing.assert_close(selected.full_tensor(), reference_selected, rtol=1e-6, atol=1e-7)
116 upstream = torch.tensor([[0.3, -0.6], [1.2, 0.7], [-0.4, 1.1], [0.8, -0.2], [-0.9, 0.5], [1.4, -1.0]])108 upstream = torch.tensor([[0.3, -0.6], [1.2, 0.7], [-0.4, 1.1], [0.8, -0.2], [-0.9, 0.5], [1.4, -1.0]])
117 (selected.to_local() * upstream[row]).sum().backward()109 (selected.to_local() * upstream[row]).sum().backward()
@@ -139,13 +131,14 @@ def test_anticipatory_replay_preserves_dtensor_ids_and_current_score_gradients(t
139 131 
140 132 
141def test_cache_wraps_dynamic_router_but_not_v4_hash_router():133def test_cache_wraps_dynamic_router_but_not_v4_hash_router():
142- from torchtitan.models.common.linear import Linear134+ from torchtitan.models.common.activation import Sigmoid
135+ from torchtitan.models.common.linear import RouterGateLinear
143 from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router136 from torchtitan.models.deepseek_v4.moe import DeepSeekV4Router
144 137 
145- gate = Linear.Config(in_features=4, out_features=4)138+ gate = RouterGateLinear.Config(in_features=4, out_features=4)
146 with torch.random.fork_rng(devices=[]):139 with torch.random.fork_rng(devices=[]):
147 hash_router = DeepSeekV4Router.Config(140 hash_router = DeepSeekV4Router.Config(
148- num_experts=4, gate=gate, top_k=2, vocab_size=8, layer_id=0, n_hash_layers=1141+ num_experts=4, gate=gate, score_func=Sigmoid.Config(), top_k=2, vocab_size=8, layer_id=0, n_hash_layers=1
149 ).build()142 ).build()
150 dynamic_router = _router()143 dynamic_router = _router()
151 model = torch.nn.ModuleList([hash_router, dynamic_router])144 model = torch.nn.ModuleList([hash_router, dynamic_router])
@@ -605,20 +605,21 @@ def test_only_v4_selects_ao_reader(readers, monkeypatch, tmp_path):
605 DeepSeekV4Model=SimpleNamespace(Config=object),605 DeepSeekV4Model=SimpleNamespace(Config=object),
606 ),606 ),
607 )607 )
608+ 
609+ class V4Adapter(V3Adapter):
610+ pass
611+ 
612+ upstream_v4 = ModuleType("torchtitan.models.deepseek_v4.state_dict_adapter")
613+ upstream_v4.DeepSeekV4StateDictAdapter = V4Adapter
614+ monkeypatch.setitem(sys.modules, upstream_v4.__name__, upstream_v4)
615+ 
616+ class PEFTMixin:
617+ pass
618+ 
608 monkeypatch.setitem(619 monkeypatch.setitem(
609 sys.modules,620 sys.modules,
610- "_ao_test_components.lora",621+ "torchtitan_npu.models.deepseek_v4.lora",
611- SimpleNamespace(622+ SimpleNamespace(DeepSeekPEFTAdapter=PEFTMixin, is_lora_parameter=lambda _name: False),
612- _PEFT_MODULE_SUFFIXES=(),
613- MODULE_PATHS=(),
614- PEFT_PREFIX="base_model.model.",
615- pack_expert_factor=lambda tensor, factor: tensor,
616- DEEPSEEK_V4_LORA_TARGETS=(),
617- DeepSeekV4LoRAConverter=SimpleNamespace(Config=object),
618- LoRAOptions=object,
619- is_lora_parameter=lambda _name: False,
620- peft_target_modules=lambda targets: targets,
621- ),
622 )623 )
623 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.mx_storage_reader.hf_storage", readers.hf_storage)624 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.mx_storage_reader.hf_storage", readers.hf_storage)
624 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.mx_storage_reader.ao_hf_storage", readers.ao_hf_storage)625 monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.mx_storage_reader.ao_hf_storage", readers.ao_hf_storage)
@@ -287,34 +287,46 @@ def test_only_v4_selects_mx_reader(reader_module, monkeypatch, tmp_path, weight_
287 upstream = ModuleType("torchtitan.models.deepseek_v3.state_dict_adapter")287 upstream = ModuleType("torchtitan.models.deepseek_v3.state_dict_adapter")
288 upstream.DeepSeekV3StateDictAdapter = V3Adapter288 upstream.DeepSeekV3StateDictAdapter = V3Adapter
289 monkeypatch.setitem(sys.modules, upstream.__name__, upstream)289 monkeypatch.setitem(sys.modules, upstream.__name__, upstream)
290- monkeypatch.setitem(sys.modules, "_mx_test_components.model", SimpleNamespace(290+ 
291- DeepSeekV4Model=SimpleNamespace(Config=object),291+ class V4Adapter(V3Adapter):
292- ))292+ pass
293- # Load the adapter under an isolated package name without importing the293+ 
294- # full DeepSeek-V4 model package. The reader-selection method does not294+ upstream_v4 = ModuleType("torchtitan.models.deepseek_v4.state_dict_adapter")
295- # exercise LoRA conversion, but the adapter module still imports these295+ upstream_v4.DeepSeekV4StateDictAdapter = V4Adapter
296- # symbols at module load time.296+ monkeypatch.setitem(sys.modules, upstream_v4.__name__, upstream_v4)
297- monkeypatch.setitem(sys.modules, "_mx_test_components.lora", SimpleNamespace(297+ monkeypatch.setitem(
298- _PEFT_MODULE_SUFFIXES=(),298+ sys.modules,
299- MODULE_PATHS=(),299+ "_mx_test_components.model",
300- PEFT_PREFIX="base_model.model.",300+ SimpleNamespace(
301- pack_expert_factor=lambda tensor, factor: tensor,301+ DeepSeekV4Model=SimpleNamespace(Config=object),
302- DEEPSEEK_V4_LORA_TARGETS=(),302+ ),
303- DeepSeekV4LoRAConverter=SimpleNamespace(Config=object),303+ )
304- LoRAOptions=object,304+ 
305- is_lora_parameter=lambda _name: False,305+ # Reader selection only needs the PEFT mixin in the MRO; conversion is outside this test.
306- peft_target_modules=lambda targets: targets,306+ class PEFTMixin:
307- ))307+ pass
308- monkeypatch.setitem(sys.modules,308+ 
309- "torchtitan_npu.extensions.mx_storage_reader.hf_storage", reader_module)309+ monkeypatch.setitem(
310+ sys.modules,
311+ "torchtitan_npu.models.deepseek_v4.lora",
312+ SimpleNamespace(
313+ DeepSeekPEFTAdapter=PEFTMixin,
314+ is_lora_parameter=lambda _name: False,
315+ ),
316+ )
317+ monkeypatch.setitem(sys.modules, "torchtitan_npu.extensions.mx_storage_reader.hf_storage", reader_module)
310 # The V4 adapter probes the AO reader before the fixed-format MX reader.318 # The V4 adapter probes the AO reader before the fixed-format MX reader.
311- monkeypatch.setitem(sys.modules,319+ monkeypatch.setitem(
312- "torchtitan_npu.extensions.mx_storage_reader.ao_hf_storage",320+ sys.modules,
313- sys.modules["_mx_test_components.ao_hf_storage"])321+ "torchtitan_npu.extensions.mx_storage_reader.ao_hf_storage",
322+ sys.modules["_mx_test_components.ao_hf_storage"],
323+ )
314 root = Path(__file__).resolve().parents[4] / "torchtitan_npu/models"324 root = Path(__file__).resolve().parents[4] / "torchtitan_npu/models"
315 classes = []325 classes = []
316- for model, class_name in (("deepseek_v4", "DeepSeekV4StateDictAdapter"),326+ for model, class_name in (
317- ("deepseek_v3_2", "DeepSeekV32StateDictAdapter")):327+ ("deepseek_v4", "DeepSeekV4StateDictAdapter"),
328+ ("deepseek_v3_2", "DeepSeekV32StateDictAdapter"),
329+ ):
318 spec = importlib.util.spec_from_file_location(330 spec = importlib.util.spec_from_file_location(
319 f"_mx_test_components.{model}", root / model / "state_dict_adapter.py"331 f"_mx_test_components.{model}", root / model / "state_dict_adapter.py"
320 )332 )
@@ -323,8 +335,12 @@ def test_only_v4_selects_mx_reader(reader_module, monkeypatch, tmp_path, weight_
323 spec.loader.exec_module(module)335 spec.loader.exec_module(module)
324 classes.append(getattr(module, class_name))336 classes.append(getattr(module, class_name))
325 v4, v32 = classes337 v4, v32 = classes
326- dtype = {"mxfp4": torch.uint8, "mxfp8": torch.float8_e4m3fn,338+ dtype = {
327- "bf16": torch.bfloat16, "block-fp8": torch.float8_e4m3fn}[weight_format]339+ "mxfp4": torch.uint8,
340+ "mxfp8": torch.float8_e4m3fn,
341+ "bf16": torch.bfloat16,
342+ "block-fp8": torch.float8_e4m3fn,
343+ }[weight_format]
328 tensors = {"linear.weight": torch.ones(1, 32).to(dtype)}344 tensors = {"linear.weight": torch.ones(1, 32).to(dtype)}
329 if weight_format.startswith("mx"):345 if weight_format.startswith("mx"):
330 tensors["linear.scale"] = torch.full((1, 2 if weight_format == "mxfp4" else 1), 127, dtype=torch.uint8)346 tensors["linear.scale"] = torch.full((1, 2 if weight_format == "mxfp4" else 1), 127, dtype=torch.uint8)
@@ -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+"""Upstream EMA scheduling through the NPU configuration and offload adapter."""
7+ 
8+import importlib.util
9+import sys
10+import types
11+from pathlib import Path
12+ 
13+import pytest
14+import torch
15+ 
16+ 
17+def _tracked_model():
18+ model = torch.nn.Module()
19+ model.weight = torch.nn.Parameter(torch.tensor([2.0, -2.0]))
20+ model.frozen = torch.nn.Parameter(torch.tensor([9.0]), requires_grad=False)
21+ model.register_buffer("expert_bias", torch.tensor([1.0, 3.0]))
22+ model.register_buffer("untracked", torch.tensor([5.0]))
23+ return model
24+ 
25+ 
26+@pytest.mark.parametrize("offload", [False, True], ids=["resident", "cpu-offload"])
27+@pytest.mark.parametrize("npu_recipe", [False, True], ids=["upstream-recipe", "npu-recipe"])
28+def test_config_manager_preserves_ema_schedule_and_selects_device_adapter(monkeypatch, tmp_path, offload, npu_recipe):
29+ from torchtitan.components.optim import Optim
30+ from torchtitan.components.optim.ema import EMA as _EMA
31+ from torchtitan.config import ConfigManager
32+ from torchtitan.models.llama3 import model_registry
33+ from torchtitan.trainer import Trainer
34+ 
35+ from torchtitan_npu.extensions.torchtitan.components.optimizer.ema import EMA
36+ from torchtitan_npu.extensions.torchtitan.trainer import TrainerEx
37+ 
38+ source_ema = _EMA.Config(
39+ decay=0.5,
40+ start_step=1,
41+ update_every_n_steps=2,
42+ offload_to_cpu=offload,
43+ buffer_patterns=[r"^expert_bias$"],
44+ )
45+ source = (TrainerEx.Config if npu_recipe else Trainer.Config)(
46+ model=model_registry("debugmodel"),
47+ hf_assets_path=str(tmp_path),
48+ optim=Optim.Config(ema=source_ema),
49+ )
50+ module_name = "_npu_ema_config_registry"
51+ registry = types.ModuleType(module_name)
52+ registry.ema_recipe = lambda: source
53+ monkeypatch.setitem(sys.modules, module_name, registry)
54+ 
55+ config = ConfigManager().parse_args(["--module", module_name, "--config", "ema_recipe"])
56+ model = _tracked_model()
57+ ema = config.optim.ema.build(model_parts=[model])
58+ 
59+ assert type(config.optim.ema) is EMA.Config
60+ assert type(ema) is EMA
61+ assert source.optim.ema is source_ema and type(source_ema) is _EMA.Config
62+ assert ema.offload_to_cpu is offload
63+ assert (ema.start_step, ema.update_every_n_steps, ema.decay) == (1, 2, 0.5)
64+ assert model.frozen not in ema._param_optimizers[0].state
65+ assert model.untracked not in ema._buffer_optimizers[0].state
66+ averaged_weight = ema._param_optimizers[0].state[model.weight]["ema_params"]
67+ averaged_bias = ema._buffer_optimizers[0].state[model.expert_bias]["ema_params"]
68+ 
69+ with torch.no_grad():
70+ model.weight.copy_(torch.tensor([10.0, 6.0]))
71+ model.expert_bias.copy_(torch.tensor([5.0, 11.0]))
72+ ema.step(1)
73+ ema.step(2)
74+ torch.testing.assert_close(averaged_weight, torch.tensor([2.0, -2.0]), rtol=0, atol=0)
75+ torch.testing.assert_close(averaged_bias, torch.tensor([1.0, 3.0]), rtol=0, atol=0)
76+ ema.step(3)
77+ torch.testing.assert_close(averaged_weight, torch.tensor([6.0, 2.0]), rtol=0, atol=0)
78+ torch.testing.assert_close(averaged_bias, torch.tensor([3.0, 7.0]), rtol=0, atol=0)
79+ with torch.no_grad():
80+ model.weight.copy_(torch.tensor([14.0, 10.0]))
81+ model.expert_bias.copy_(torch.tensor([9.0, 15.0]))
82+ ema.step(4)
83+ torch.testing.assert_close(averaged_weight, torch.tensor([6.0, 2.0]), rtol=0, atol=0)
84+ ema.step(5)
85+ torch.testing.assert_close(averaged_weight, torch.tensor([10.0, 6.0]), rtol=0, atol=0)
86+ torch.testing.assert_close(averaged_bias, torch.tensor([6.0, 11.0]), rtol=0, atol=0)
87+ 
88+ 
89+@pytest.fixture
90+def ema_module(monkeypatch):
91+ # The adapter has no import side effects; isolate only unrelated package
92+ # activation so the CPU offload branch also runs without a CANN runtime.
93+ path = Path(__file__).resolve().parents[6] / "torchtitan_npu/extensions/torchtitan/components/optimizer/ema.py"
94+ spec = importlib.util.spec_from_file_location("_npu_ema_definition", path)
95+ module = importlib.util.module_from_spec(spec)
96+ monkeypatch.setitem(sys.modules, spec.name, module)
97+ spec.loader.exec_module(module)
98+ return module
99+ 
100+ 
101+def test_cpu_offload_ema_uses_native_dynamic_decay_and_step_bias(ema_module):
102+ model = _tracked_model()
103+ ema = ema_module.EMA.Config(half_life_fraction=0.5, step_bias=1, offload_to_cpu=True).build(model_parts=[model])
104+ averaged = ema._param_optimizers[0].state[model.weight]["ema_params"]
105+ with torch.no_grad():
106+ model.weight.fill_(6.0)
107+ 
108+ ema.step(1)
109+ 
110+ # The first firing plus bias is two updates: decay = 2**(-1/(0.5*2)) = 0.5.
111+ torch.testing.assert_close(averaged, torch.tensor([4.0, 2.0]), rtol=0, atol=0)
112+ torch.testing.assert_close(model.weight, torch.tensor([6.0, 6.0]), rtol=0, atol=0)
113+ assert averaged.data_ptr() != model.weight.data_ptr()
@@ -7,85 +7,18 @@
7 7 
8from __future__ import annotations8from __future__ import annotations
9 9 
10-import importlib.util
11import sys10import sys
12import types11import types
13-from dataclasses import dataclass
14-from enum import Enum
15from pathlib import Path12from pathlib import Path
16from unittest.mock import MagicMock, patch13from unittest.mock import MagicMock, patch
17 14 
18import pytest15import pytest
19import torch16import torch
17+from torchtitan.components.checkpointer.dcp import CheckpointManager as _CheckpointManager
20 18 
19+from torchtitan_npu.extensions.torchtitan.components import checkpoint as product_checkpoint
21 20 
22-class _AsyncMode(str, Enum):21+_AsyncMode = product_checkpoint.AsyncMode
23- DISABLED = "disabled"
24- ASYNC = "async"
25- ASYNC_WITH_PINNED_MEM = "async_with_pinned_mem"
26- 
27- 
28-class _CheckpointManager:
29- @dataclass(kw_only=True, slots=True)
30- class Config:
31- interval: int = 1
32- enable: bool = True
33- async_mode: str = "disabled"
34- 
35- def __init__(self, config, **kwargs):
36- self.config = config
37- 
38- def save(self, curr_step, last_step=False):
39- return True
40- 
41- def dcp_save(self, **kwargs):
42- return "upstream-save"
43- 
44- def dcp_load(self, *args, **kwargs):
45- return "upstream-load"
46- 
47- 
48-torchtitan_stub = types.ModuleType("torchtitan")
49-torchtitan_stub.__path__ = []
50-components_stub = types.ModuleType("torchtitan.components")
51-components_stub.__path__ = []
52-torchtitan_stub.components = components_stub
53-checkpoint_stub = types.ModuleType("torchtitan.components.checkpointer")
54-checkpoint_stub.AsyncMode = _AsyncMode
55-checkpoint_stub.CheckpointManager = _CheckpointManager
56-components_stub.checkpointer = checkpoint_stub
57-observability_stub = types.ModuleType("torchtitan.observability")
58-observability_stub.structured_logger = types.SimpleNamespace(log_trace_span=lambda name: lambda function: function)
59-torchtitan_stub.observability = observability_stub
60-tools_stub = types.ModuleType("torchtitan.tools")
61-tools_stub.__path__ = []
62-torchtitan_stub.tools = tools_stub
63-utils_stub = types.ModuleType("torchtitan.tools.utils")
64-utils_stub.GarbageCollection = MagicMock()
65-tools_stub.utils = utils_stub
66-validation_stub = types.ModuleType("torchtitan_npu.extensions.components.validation")
67-validation_stub.mark_checkpoint_manifest_pending = MagicMock()
68-validation_stub.verify_checkpoint_manifest = MagicMock()
69-validation_stub.write_checkpoint_manifest = MagicMock()
70- 
71-module_path = Path(__file__).resolve().parents[5] / "torchtitan_npu/extensions/torchtitan/components/checkpoint.py"
72-module_name = "torchtitan_npu.extensions.torchtitan.components.checkpoint"
73-module_spec = importlib.util.spec_from_file_location(module_name, module_path)
74-product_checkpoint = importlib.util.module_from_spec(module_spec)
75- 
76-with patch.dict(
77- sys.modules,
78- {
79- "torchtitan": torchtitan_stub,
80- "torchtitan.components": components_stub,
81- "torchtitan.components.checkpointer": checkpoint_stub,
82- "torchtitan.observability": observability_stub,
83- "torchtitan.tools": tools_stub,
84- "torchtitan.tools.utils": utils_stub,
85- "torchtitan_npu.extensions.components.validation": validation_stub,
86- },
87-):
88- module_spec.loader.exec_module(product_checkpoint)
89 22 
90 23 
91pytestmark = pytest.mark.cpu24pytestmark = pytest.mark.cpu
@@ -102,8 +35,10 @@ def test_manager_reads_hash_manifest_extension_config():
102 extensions=product_checkpoint.CheckpointExtensions(verify_hash_manifest=True)35 extensions=product_checkpoint.CheckpointExtensions(verify_hash_manifest=True)
103 )36 )
104 37 
105- manager = product_checkpoint.CheckpointManager(config)38+ with patch.object(_CheckpointManager, "__init__", return_value=None) as initialize:
39+ manager = product_checkpoint.CheckpointManager(config)
106 40 
41+ initialize.assert_called_once_with(config=config)
107 assert manager.verify_hash_manifest is True42 assert manager.verify_hash_manifest is True
108 43 
109 44 
@@ -121,9 +56,11 @@ def test_manager_rejects_pinned_async_for_swap_optimizer():
121def test_manager_keeps_pinned_async_for_native_optimizer():56def test_manager_keeps_pinned_async_for_native_optimizer():
122 config = product_checkpoint.CheckpointManager.Config(async_mode="async_with_pinned_mem")57 config = product_checkpoint.CheckpointManager.Config(async_mode="async_with_pinned_mem")
123 58 
124- manager = product_checkpoint.CheckpointManager(config, optimizers=object())59+ optimizers = object()
60+ with patch.object(_CheckpointManager, "__init__", return_value=None) as initialize:
61+ product_checkpoint.CheckpointManager(config, optimizers=optimizers)
125 62 
126- assert manager.config is config63+ initialize.assert_called_once_with(config=config, optimizers=optimizers)
127 64 
128 65 
129def test_save_marks_pending_before_save_and_writes_manifest_afterward():66def test_save_marks_pending_before_save_and_writes_manifest_afterward():
@@ -189,7 +126,7 @@ def test_save_skips_manifest_operations_when_disabled():
189 write.assert_not_called()126 write.assert_not_called()
190 127 
191 128 
192-def test_dcp_load_verifies_manifest_before_upstream_load():129+def test_load_checkpoint_verifies_manifest_before_upstream_load():
193 manager = object.__new__(product_checkpoint.CheckpointManager)130 manager = object.__new__(product_checkpoint.CheckpointManager)
194 manager.verify_hash_manifest = True131 manager.verify_hash_manifest = True
195 events = []132 events = []
@@ -202,22 +139,46 @@ def test_dcp_load_verifies_manifest_before_upstream_load():
202 ),139 ),
203 patch.object(140 patch.object(
204 _CheckpointManager,141 _CheckpointManager,
205- "dcp_load",142+ "_load_checkpoint",
206- side_effect=lambda *args, **kwargs: events.append("load checkpoint") or "loaded",143+ side_effect=lambda *args, **kwargs: events.append("load checkpoint"),
207 ),144 ),
208 ):145 ):
209- result = manager.dcp_load({}, "checkpoint")146+ result = manager._load_checkpoint({}, "checkpoint", from_hf=True, from_quantized=False)
210 147 
211- assert result == "loaded"148+ assert result is None
212 assert events == ["verify manifest", "load checkpoint"]149 assert events == ["verify manifest", "load checkpoint"]
213 150 
214 151 
152+def test_load_checkpoint_hash_failure_prevents_restore():
153+ manager = object.__new__(product_checkpoint.CheckpointManager)
154+ manager.verify_hash_manifest = True
155+ with (
156+ patch.object(product_checkpoint, "verify_checkpoint_manifest", side_effect=ValueError("hash mismatch")),
157+ patch.object(_CheckpointManager, "_load_checkpoint") as restore,
158+ pytest.raises(ValueError, match="hash mismatch"),
159+ ):
160+ manager._load_checkpoint({}, "checkpoint", from_hf=False, from_quantized=False)
161+ restore.assert_not_called()
162+ 
163+ 
164+def test_load_checkpoint_disabled_verification_preserves_states_and_flags():
165+ manager = object.__new__(product_checkpoint.CheckpointManager)
166+ manager.verify_hash_manifest = False
167+ states = {"model": object()}
168+ with (
169+ patch.object(product_checkpoint, "verify_checkpoint_manifest") as verify,
170+ patch.object(_CheckpointManager, "_load_checkpoint") as restore,
171+ ):
172+ manager._load_checkpoint(states, "checkpoint", from_hf=True, from_quantized=True)
173+ verify.assert_not_called()
174+ restore.assert_called_once_with(states, "checkpoint", from_hf=True, from_quantized=True)
175+ 
176+ 
215def _run_isolated_patch(script, *args):177def _run_isolated_patch(script, *args):
216 import subprocess178 import subprocess
217 179 
218 module_path = (180 module_path = (
219- Path(__file__).resolve().parents[5]181+ Path(__file__).resolve().parents[5] / "torchtitan_npu/patches/torchtitan/distributed/checkpoint/filesystem.py"
220- / "torchtitan_npu/patches/torchtitan/distributed/checkpoint/filesystem.py"
221 )182 )
222 subprocess.run([sys.executable, "-c", script, str(module_path), *map(str, args)], check=True)183 subprocess.run([sys.executable, "-c", script, str(module_path), *map(str, args)], check=True)
223 184 
@@ -16,7 +16,7 @@ from torch.distributed.checkpoint.state_dict_saver import _stateful_to_state_dic
16pytest.importorskip("torch_checkpointing")16pytest.importorskip("torch_checkpointing")
17 17 
18from torch_checkpointing.storage.filesystem import LocalFileSystemStorageConfig18from torch_checkpointing.storage.filesystem import LocalFileSystemStorageConfig
19-from torchtitan.components.optimizer import LRSchedulersContainer, OptimizersContainer, ParamGroupConfig19+from torchtitan.components.optim import AdamW, LRSchedulersContainer, OptimizersContainer
20 20 
21from torchtitan_npu.extensions.torchtitan.components.torch_checkpointing import TorchCheckpointingManager21from torchtitan_npu.extensions.torchtitan.components.torch_checkpointing import TorchCheckpointingManager
22 22 
@@ -46,13 +46,11 @@ def test_native_config_restores_full_state_after_async_and_final_save(tmp_path,
46 with torch.random.fork_rng(devices=[]):46 with torch.random.fork_rng(devices=[]):
47 model = torch.nn.Linear(2, 1, bias=False)47 model = torch.nn.Linear(2, 1, bias=False)
48 optimizers = OptimizersContainer.Config(48 optimizers = OptimizersContainer.Config(
49- implementation="for-loop",49+ optimizers=[AdamW.Config(pattern=".*", lr=0.1, fused=False)],
50- param_groups=[ParamGroupConfig(pattern=".*", optimizer_name="AdamW", optimizer_kwargs={"lr": 0.1})],
51 ).build(model_parts=[model])50 ).build(model_parts=[model])
52- scheduler = LRSchedulersContainer(optimizers, lr_lambda=lambda step: 1.0)51+ scheduler = LRSchedulersContainer.Config().build(optimizers=optimizers, training_steps=3)
53 progress, dataloader = _Progress(), _Progress()52 progress, dataloader = _Progress(), _Progress()
54 manager = TorchCheckpointingManager.Config(53 manager = TorchCheckpointingManager.Config(
55- enable=True,
56 folder=str(tmp_path / "checkpoint"),54 folder=str(tmp_path / "checkpoint"),
57 interval=1,55 interval=1,
58 load_only=load_only,56 load_only=load_only,
@@ -66,6 +64,7 @@ def test_native_config_restores_full_state_after_async_and_final_save(tmp_path,
66 model_parts=[model],64 model_parts=[model],
67 optimizers=optimizers,65 optimizers=optimizers,
68 lr_schedulers=scheduler,66 lr_schedulers=scheduler,
67+ ema=None,
69 states={"progress": progress},68 states={"progress": progress},
70 sd_adapter=None,69 sd_adapter=None,
71 )70 )
@@ -0,0 +1,175 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+# SPDX-License-Identifier: BSD-3-Clause
3+ 
4+"""Check the placements passed to FSDP without running device collectives."""
5+ 
6+import importlib.util
7+from pathlib import Path
8+from types import SimpleNamespace
9+ 
10+import pytest
11+import torch
12+from torch import nn
13+from torch.distributed.tensor import Shard
14+from torchtitan.models.common.config_utils import make_ffn_config, make_routed_experts_config
15+ 
16+ 
17+@pytest.fixture(scope="module")
18+def fsdp():
19+ # This definition-only module does not require package activation. Load it
20+ # directly to keep unrelated NPU runtime patches outside this CPU policy test.
21+ path = Path(__file__).resolve().parents[5] / "torchtitan_npu/extensions/torchtitan/distributed/fsdp.py"
22+ spec = importlib.util.spec_from_file_location("npu_fsdp_policy", path)
23+ module = importlib.util.module_from_spec(spec)
24+ spec.loader.exec_module(module)
25+ return module
26+ 
27+ 
28+class _StorageMeshStub(dict):
29+ """Expose only the axis names and sizes consumed by the EP=1 policy."""
30+ 
31+ def __init__(self, dp_shard, cp=1):
32+ super().__init__(dp_shard=SimpleNamespace(size=lambda: dp_shard))
33+ if cp > 1:
34+ self["cp"] = SimpleNamespace(size=lambda: cp)
35+ self.mesh_dim_names = tuple(self)
36+ 
37+ 
38+def _decoder_shell(block):
39+ model = nn.Module()
40+ model.enable_weight_tying = False
41+ model.tok_embeddings = model.norm = model.lm_head = None
42+ model.layers = nn.ModuleDict({"0": block})
43+ return model
44+ 
45+ 
46+@pytest.fixture
47+def shard_calls(monkeypatch, fsdp):
48+ calls = []
49+ 
50+ def record_shard(module, **kwargs):
51+ placement_fn = kwargs.get("shard_placement_fn", lambda parameter: None)
52+ placements = {name: placement_fn(parameter) for name, parameter in module.named_parameters()}
53+ calls.append((module, placements, kwargs))
54+ 
55+ monkeypatch.setattr(fsdp, "fully_shard", record_shard)
56+ return calls
57+ 
58+ 
59+@pytest.mark.parametrize(
60+ "dp_shard,cp,expected_w13,expected_w2",
61+ [(2, 1, 0, 0), (4, 1, 0, 0), (2, 4, 2, 1)],
62+ ids=["experts-fit", "experts-equal-shards", "cp-exceeds-experts"],
63+)
64+def test_ep1_expert_storage_overrides_stacked_projection_placement(
65+ fsdp, shard_calls, dp_shard, cp, expected_w13, expected_w2
66+):
67+ with torch.device("meta"):
68+ block = nn.Module()
69+ block.moe_enabled = True
70+ block.moe = nn.Module()
71+ block.moe.num_experts = 4
72+ block.moe.routed_experts = make_routed_experts_config(
73+ dim=8, hidden_dim=16, num_experts=4, top_k=1, param_init={}, comm_backend="standard"
74+ ).build()
75+ block.moe.shared_experts = make_ffn_config(dim=8, hidden_dim=16, w1_param_init={}, w2w3_param_init={}).build()
76+ model = _decoder_shell(block)
77+ model.host_table = nn.Parameter(torch.empty(4, 8))
78+ mesh = _StorageMeshStub(dp_shard, cp)
79+ ignored = {model.host_table}
80+ 
81+ fsdp.apply_fsdp_to_decoder(model, mesh, torch.bfloat16, torch.float32, pp_enabled=False, ignored_params=ignored)
82+ 
83+ assert shard_calls[0][0] is block
84+ # W13 is [E, 2, F, D]; W2 is [E, D, F]. Expert-axis sharding
85+ # takes precedence until dp_shard * cp exceeds E.
86+ assert shard_calls[0][1] == {
87+ "moe.routed_experts.w13.weight": Shard(expected_w13),
88+ "moe.routed_experts.w2.weight": Shard(expected_w2),
89+ "moe.shared_experts.w13.weight": Shard(1),
90+ "moe.shared_experts.w2.weight": None,
91+ }
92+ assert shard_calls[-1][0] is model
93+ assert all(kwargs["ignored_params"] is ignored for _, _, kwargs in shard_calls)
94+ assert all(kwargs["mesh"] is mesh for _, _, kwargs in shard_calls)
95+ 
96+ 
97+def test_dense_stacked_gate_up_shards_matrix_rows(fsdp, shard_calls):
98+ with torch.device("meta"):
99+ block = nn.Module()
100+ block.moe_enabled = False
101+ block.feed_forward = make_ffn_config(dim=8, hidden_dim=16, w1_param_init={}, w2w3_param_init={}).build()
102+ model = _decoder_shell(block)
103+ 
104+ fsdp.apply_fsdp_to_decoder(model, _StorageMeshStub(4), torch.bfloat16, torch.float32, pp_enabled=False)
105+ 
106+ assert shard_calls[0][0] is block
107+ assert shard_calls[0][1] == {
108+ "feed_forward.w13.weight": Shard(1),
109+ "feed_forward.w2.weight": None,
110+ }
111+ 
112+ 
113+@pytest.fixture
114+def ep2_storage_meshes():
115+ import torch.distributed as dist
116+ from torch.distributed.device_mesh import DeviceMesh
117+ from torch.testing._internal.distributed.fake_pg import FakeStore
118+ 
119+ # Real mesh selection with no communication; fully_shard itself is recorded
120+ # by shard_calls, so this does not claim FSDP collective coverage.
121+ assert not dist.is_initialized()
122+ dist.init_process_group("fake", store=FakeStore(), rank=1, world_size=4)
123+ try:
124+ dense = DeviceMesh("cpu", torch.arange(4), mesh_dim_names=("dp_shard",))
125+ sparse = DeviceMesh("cpu", torch.arange(4).reshape(2, 2), mesh_dim_names=("edp_shard", "ep"))
126+ yield dense, sparse
127+ finally:
128+ dist.destroy_process_group()
129+ 
130+ 
131+@pytest.mark.parametrize("num_experts,expected_axes", [(4, (0, 0)), (2, (2, 1))], ids=["experts-fit", "row-sharded"])
132+def test_ep2_selects_sparse_fsdp_mesh_and_preserves_dense_stacked_placement(
133+ fsdp, shard_calls, ep2_storage_meshes, num_experts, expected_axes
134+):
135+ from torch.distributed.fsdp import DataParallelMeshDims
136+ 
137+ with torch.device("meta"):
138+ block = nn.Module()
139+ block.moe_enabled = True
140+ block.moe = nn.Module()
141+ block.moe.num_experts = num_experts
142+ block.moe.routed_experts = make_routed_experts_config(
143+ dim=8, hidden_dim=16, num_experts=num_experts, top_k=1, param_init={}, comm_backend="standard"
144+ ).build()
145+ block.moe.shared_experts = make_ffn_config(dim=8, hidden_dim=16, w1_param_init={}, w2w3_param_init={}).build()
146+ model = _decoder_shell(block)
147+ model.host_table = nn.Parameter(torch.empty(4, 8))
148+ dense_mesh, sparse_mesh = ep2_storage_meshes
149+ ignored = {model.host_table}
150+ 
151+ fsdp.apply_fsdp_to_decoder(
152+ model,
153+ dense_mesh,
154+ torch.bfloat16,
155+ torch.float32,
156+ pp_enabled=False,
157+ ep_degree=2,
158+ edp_mesh=sparse_mesh,
159+ dp_mesh_dims=DataParallelMeshDims(shard="dp_shard"),
160+ edp_mesh_dims=DataParallelMeshDims(shard="edp_shard"),
161+ ignored_params=ignored,
162+ )
163+ 
164+ placements = shard_calls[0][1]
165+ for projection, axis in zip(("w13", "w2"), expected_axes, strict=True):
166+ placement = placements[f"moe.routed_experts.{projection}.weight"]
167+ assert placement.placement == Shard(axis)
168+ assert placement.mesh_info.spmd_mesh is sparse_mesh
169+ assert placement.mesh_info.mesh.mesh.tolist() == [1, 3]
170+ for projection, axis in (("w13", 1), ("w2", 0)):
171+ placement = placements[f"moe.shared_experts.{projection}.weight"]
172+ assert placement.placement == Shard(axis)
173+ assert placement.mesh_info.spmd_mesh is dense_mesh
174+ assert placement.mesh_info.mesh.mesh.tolist() == [0, 1, 2, 3]
175+ assert all(kwargs["ignored_params"] is ignored for _, _, kwargs in shard_calls)