Merged
feat: adapt TorchTitan v0.4.0 for DeepSeek eager training #1211
feat: adapt TorchTitan v0.4.0 for DeepSeek eager training #1211
Merged
1Fire4Add on 27 days ago
Total: 319 files changed+11408-8598
@@ -0,0 +1,23 @@
1+# TorchTitan 0.4.0 训练 recipe 归属迁移
2+ 
3+基线为 PR [#1211](https://gitcode.com/cann/torchtitan-npu/pull/1211) 的 `hitwdy:upgrade_0.4.0_upstream`。当前目标提交 `1da1222` 使用 PyPI `torchtitan==0.4.0`;对应发布源码为 `45e33cd413b64cb37a7840cfd3c9765d3c639ae1`。
4+ 
5+## 本轮范围
6+ 
7+完整训练工厂从模型 `config_registry.py` 移至 `torchtitan_npu_recipes/models/`,GraphTrainer 组合移至 `torchtitan_npu_recipes/graph_trainer/`。模型 flavor registry 保留在模型包。调用方、包分发和文档同步切换到新归属。
8+ 
9+Muon profile、Engram 优化器 schema、V4.1 trainer/engine、Qwen 数据转换和 GraphTrainer schema 转换保留在模型实现中,插件不得反向导入 recipe。V4.1 工厂补充其已有 `OptimConfig(...)` 调用所需的显式导入。
10+ 
11+随后将 `examples/` 下全部 34 个训练脚本的组合移入 `torchtitan_npu_recipes/examples/`,每个脚本选择一个同名工厂:V4 19 个、V4.1 12 个、Qwen3.5 2 个、Qwen3.6 1 个。数据、训练预算、模型与 RoPE、Muon 参数组、并行、checkpoint、profiling、量化和 golden/override 组合均使用真实 typed schema。共用 launcher 只处理资源、进程启动与原生参数透传,支持不启动 worker 的 `--print-config`。
12+ 
13+迁移保留原场景的训练选择,不移植旧通用 CLI 的字符串解析,也不引入 callable override adapter。旧文本参数环境变量会明确拒绝;资源路径和各工厂明确支持的环境变量继续有效。GraphTrainer、CP、多模态、SFT、LoRA 以及 Qwen27B 等延期路径保留实际构造或运行时限制,不因配置迁移成为已验收功能。
14+ 
15+## 验证边界
16+ 
17+新增 CPU 测试通过真实 ConfigLoader 选择 V4 eager 与 V4.1 文本 eager 工厂,检查模型类型、数据对齐和优化器 profile;不使用伪造配置替代产品导入。
18+ 
19+示例迁移增加真实 ConfigLoader 的场景语义检查,包括 token budget、Muon materialize、quantization、golden、checkpoint、Qwen 数据与拓扑;启动契约测试覆盖 34 个 wrapper、原生参数分组、节点数、网卡地址、退出码和打印配置。启动替身测试只验证 shell,不表示 NPU 训练通过。
20+ 
21+本轮验证:87 个相关检查、36 个 shell 语法检查以及 eager、V4 mini、V4.1 mini 的真实入口 `--print-config` 均通过。格式、架构和合规检查通过;全仓 Pyrefly 的 73 个错误与未修改的 `1da1222` 完全一致。扩大运行的 Qwen adapter 检查另有 9 个失败,在该基线上逐项复现。本轮使用可用的 PTA `c36fa4e` 与 CANN 20261104,未匹配计划声明的精确依赖组合,也未执行 NPU 训练或数值对齐。
22+ 
23+训练工厂和模型 helper 的源码搬移须与上述基线比较,静态一致不能替代运行时和数值验证。合入前仍需在匹配 0.4.0 pin 的 torch/torch-npu 环境执行相关 UT、NPU 集成和同 checkpoint 的逐 step loss/grad_norm 比特一致比较。环境受阻或未执行的检查记录在 PR 中,不标记为通过。
@@ -0,0 +1,565 @@
1+# TorchTitan v0.4.0 升级规划:DSV4 / DSV4.1 eager 优先
2+ 
3+- Status: proposed
4+- Created: 2026-11-04
5+- Last updated: 2026-11-05
6+- Related Issue/PR: 尚未创建
7+ 
8+## 当前执行状态(2026-11-05)
9+ 
10+**最新验收范围变更:2026-11-05 用户要求两模型 8 卡长程改为 50 步,随后明确「续训测完 Muon 就够了」。当前必需范围为 8 卡 50 步训练及两模型 Muon 双卡完整续训;不再追加 8 卡 AdamW 恢复。此前已完成的 100-step、AdamW 续训与跨版本诊断保留为历史证据。模型规模、eager、FullAC 与精确判定不变。**
11+ 
12+本轮指定的「两模型 8 卡 50 步训练 + Muon 双卡完整续训」已完成,训练证据固定为 C16;其后的 runtime 带宽接线修复仅有 CPU 与静态检查证据。整轮升级的历史 golden 和全仓 Lint 仍有未通过项。下文保留原规划与逐阶段证据,当前结论以本节和最新验证记录为准。
13+ 
14+| 项目 | 当前证据与未完成项 |
15+| --- | --- |
16+| 软件栈 | 固定目标上游;Torch 2.15 / 固定源码 Torch-NPU wheel 已在两台隔离环境完成正式 requirements 安装、版本来源检查及 pip check。原 2.14 配对因缺少目标上游必需 API 未继续采用 |
17+| 文本 eager 主路径 | C16 同 head 核心 NPU 矩阵 14/14 通过,三项 HCCL 边界通过;覆盖两模型单卡、EP2/FSDP2、GA2/padding、无 AC/FullAC、V4 MTP 和 V4.1 Host Engram;融合 V4.1 路径保留 reference Sinkhorn 边界 |
18+| 新版续训 | C16 两模型 Muon EP2/FSDP2 GA2 连续 4 步 vs 2→4 恢复,指标与完整状态精确比较通过;包括 momentum、Engram/SparseAdam 及真实 Gloo metadata / HCCL WORLD 核验。按最新用户指令不再追加 AdamW 续训,已完成的历史对照保留 |
19+| V4 裁剪 Flash | C16 同 head 50 步已完成,raw TB 的 loss/grad_norm 覆盖 1..50 且有限,step50 indexer audit 通过(21 pairs / 84 projections);按用户范围取消最终保存/AdamW 恢复,runner exit143 为有记录的主动取消。跨 head 18,520-key 恢复对照作为历史诊断单列 |
20+| V4.1 裁剪 Flash | C16 的 50 步 raw TB 指标完整有限、step50 indexer audit 通过;按最新用户范围有意取消多余最终保存/恢复,原 runner exit143 单列,不记作完整两阶段 suite 返回0。使用 reference Sinkhorn、融合 attention/indexer、65,536 行 Engram;历史 C12 100 步完整续训通过及 C15 保存失败均留证 |
21+| 严格数值门槛 | 三个历史 30-step golden 仍失败且未刷新;旧适配基线诊断也未通过历史 golden。V4 单卡 GA2 反事实已复现旧侧 30 步 loss / grad_norm;原默认路径、其他 golden 与最终全状态仍不能据此称为比特一致 |
22+| 全仓检查 | 完整 Lint 未通过;目标 Pyrefly 最新剩余 30 项后置能力与其他模型接口错误。补充公共入口 CPU 检查通过,不等于其他模型训练兼容 |
23+ 
24+## Context
25+ 
26+本次升级涉及公共模型接口、损失归一化、重计算和插件接入点,不能仅修改依赖版本。分析依据为本地固定版本的 Git 差异与源码,不代表运行验证通过。
27+ 
28+| 项目 | 固定版本 |
29+| --- | --- |
30+| 起始 torchtitan-npu | `c422c623bdc15b967e93b8b46972b8d876e785ef` |
31+| 当前适配上游 | `ebdfc8c2a24d89d89c99c0ef96ed8ac149864175` |
32+| 目标上游 v0.4.0 | `45e33cd413b64cb37a7840cfd3c9765d3c639ae1` |
33+| 上游差异 | 317 个提交、990 个文件;基线为目标的祖先 |
34+ 
35+起始静态扫描发现 NPU 生产代码的 60 处 import 引用了目标版本已删除或搬迁的 15 个模块,不包含同模块内符号、参数及行为变化。上一轮升级见 [dc3985 → ebdfc8 计划](2026-10-31-upgrade-torchtitan-plan.md)。
36+ 
37+## Proposal
38+ 
39+### 首阶段边界
40+ 
41+- 验收 DSV4、DSV4.1 文本 CPT eager 训练与新版续训,按单卡小模型、EP2/FSDP2、8 卡裁剪 Flash 递进。
42+- 裁剪 Flash 保留完整层结构、16 experts;V4 为 43 层,V4.1 为 40 层。完整 Flash 规模验收后置。
43+- DSV4 包含已有 MTP;V4.1 文本实现没有 MTP,本轮不新增。
44+- V4.1 包含 Host Engram、稀疏参数更新、Full/Reindex/Reuse 链和状态恢复。
45+- TP、CP、PP 均固定为 1。不安排 PP、LoRA 适配;CP、多模态、SFT 后置。
46+- 保留 HF 权重加载,只要求新版 DCP 保存与续训,不兼容升级前完整 DCP 或 optimizer 状态。
47+- CLI 迁移已有独立计划,只作为配置入口前置依赖,不重复拆解或实现旧 CLI 兼容层。
48+- 只修改 NPU 插件仓,不修改上游 checkout,不维护旧上游兼容分支。
49+- eager 指模型和 loss 不进入 Dynamo/AOT 编译执行;关闭 local compile、GraphTrainer 和 CUDA graphs,`aot_eager` 不计作纯 eager。
50+ 
51+### 上游变化与接口迁移
52+ 
53+| 领域 | 上游变化 | NPU 适配决定 |
54+| --- | --- | --- |
55+| 依赖与目录 | 基类迁到 `models.base`;attention、linear、MoE 拆为子包;数据和 recipe 重组 | 同步 import、patch 目标、注册入口与依赖声明 |
56+| 模型构造 | 统一 `feed_forward`;构造期完成更多分片配置 | 同批迁移字段、工厂、sharding、FSDP、Muon 筛选、HF 映射和 override FQN |
57+| Linear / Router | `RouterGateLinear` 改为 `HiMidLoLinear`;新增原位 WGRAD | 首阶段关闭原位 WGRAD,HiMidLo 使用非 CUDA FP32 路径,优化另行验证 |
58+| 激活 | 输入改为 `gate_up[...,2,F]` | 同步小算子、TileLang 和 CANN 路径,保留 DeepSeek clamp 公式,不直接替换为上游同名但公式不同的激活 |
59+| 输入和 loss | preprocess 返回四项;loss / routing 分离逐 objective 计数 | 传递 `loss_kwargs`、`global_loss_token_counts` 与 routing denominators,覆盖 padding 和梯度累积 |
60+| MTP | 各深度分别归一化;chunked loss 累积 dtype 改变 | 统一 predictions / labels tuple,保留 mHC MTP 和本地 chunked loss;计算变化独立验收 |
61+| Attention | backend-owned metadata、DSV4 packed documents | 复用新接口,保留 NPU 多压缩几何 key、文档边界与 V4.1 复用语义 |
62+| MoE / EP | 新 `padding_mask_T`、dispatcher 返回值及 batch-wise aux loss | 迁移输入与统计协议,保留 pre-W2 score absorption,避免重复乘 score |
63+| AC | FullAC / SelectiveAC 迁到 `torch_remat` region | 先无 AC 建立基线,再接 FullAC,核验 router、aux loss 和 Engram 重算副作用 |
64+| 运行时与优化 | 新 GradientClipper、分布式初始化、GC / accelerator API | 接入 sparse norm 扩展点,移除失效调用,收缩整段上游复制 |
65+| Checkpoint | `extra_states`、HF 量化布局 keyword、多副本 EMA 状态 | 首阶段 native DCP;更新 adapter 签名;不新增旧格式转换层 |
66+ 
67+关键上游变更包括 `#5345`(feed-forward)、`#5335/#4897`(metadata)、`#5055`(MTP)、`#4893/#5101`(remat)、`#5394`(clipper)、`#5063`(HF 布局)及 `#5417`(mHC)。上游源码以目标 SHA 为准,插件调用点见 [V4 模型](../../../../torchtitan_npu/models/deepseek_v4/model.py)、[V4.1 模型](../../../../torchtitan_npu/models/deepseek_v4_1/model.py)、[V4 MTP](../../../../torchtitan_npu/models/deepseek_v4/mtp.py) 和 [训练扩展](../../../../torchtitan_npu/extensions/torchtitan/trainer.py)。
68+ 
69+### 必须保护的语义
70+ 
71+- 保留 pre-W2 路由分数乘法及 BF16 舍入、DeepSeek clamp、partial RoPE、BatchedLinear 和 Engram ownership。
72+- `_grouped_mm` 接口仍匹配,复用现有 kernel,验证空专家、零 token 和反向边界。
73+- 两模型通过共享的插件侧 `_get_attention_metadata` 保留 geometry-keyed 构造;复用上游 preprocess,移除被替代的全局 stamping 和整段 Decoder 覆盖。
74+- eager mask patch 必须绑定拆包后的真实 attention 子模块,不能只修改包对象。
75+- 本地 mHC 已等价实现上游修正的混合轴,不重复改动计算。
76+- Lightning Indexer carrier 仅用于 autograd teacher 通道,不能读取其值作为上游新 SparseIndexerLoss 的 logits。保留 teacher pair、排序与既有缩放,单独核验 GA / EP 下梯度尺度。
77+- MTP tuple 要求在起始上游已存在,本地 list 输出是既有定制差异;本次新增的是逐 objective 计数与归一化,不能混淆归因。
78+ 
79+## Migration plan
80+ 
81+| 工作包 | 实施内容 | 完成条件 |
82+| --- | --- | --- |
83+| T0 版本与依赖 | requirements、pyproject、CI 固定目标 SHA;同步 attn-gym 0.0.17、spmd_types 0.3.1、torch_remat 0.2.2、torch_checkpointing 0.1.1、renderers 0.1.12 | 依赖解析无冲突、导入来源为目标 SHA;保留现有 torch / torch_npu 配对并实际核验 |
84+| T1 公共接口 | import、hook、patch 接线;feed_forward、新工厂、激活与 selector;新版 parallelize 参数 | 两个文本小模型与 HF adapter 可构造,关键 override 命中;未启用图模式不阻断导入 |
85+| T2 metadata 与 loss | 四项 preprocess、loss/routing counts、共享 geometry 扩展、V4 MTP | packed、padding、多压缩比和各 MTP 深度局部前反向通过 |
86+| T3 单卡 eager | 参考与融合算子分别验证,V4.1 小 Engram table;修复 mask 接线、关闭 local compile | 前向、反向、参数更新完成,各路径预期梯度产生,无误入编译执行 |
87+| T4 EP/FSDP 与 remat | dispatcher 协议、dense/expert mesh、Host ignored 参数、clipper、FullAC | EP2/FSDP2 无死锁,score 顺序、ownership、replica reduction 正确;无重复稀疏更新 |
88+| T5 HF 与新版续训 | adapter keyword / FQN、native DCP 完整状态、Engram SparseAdam | HF 加载 / 回环正确;恢复后的 loss、grad_norm 和最终训练状态一致 |
89+| T6 8 卡 Flash | 43/40 层、16 experts、EP8/FSDP8、4K 文本;V4.1 独立文本配方与 Engram 链 | 短冒烟后完成 50-step 训练与 indexer 审计;续训以 Muon 双卡完整对照验收(依最新用户指令),仅声明裁剪规模通过 |
90+ 
91+依赖顺序为 `T0 → T1 → T2 → T3 → T4/T5 → T6`。HF adapter 静态迁移随 T1 完成,真实分布式续训在 T4 后验收。
92+ 
93+先使用 AdamW;Engram 使用现有虚拟优化器和 SparseAdam。融合 attention/indexer 梯度完整后再验证 Muon/NovaSwap,不用缺少 indexer 梯度的参考路径验证 Muon。
94+ 
95+### 后续新特性
96+ 
97+| 特性 | 后续适配边界 |
98+| --- | --- |
99+| Sparse indexer loss | normalized KL、mass weighting 与现有 fused teacher 通道独立比较,不在接口迁移中改目标 |
100+| MoE balancing / Dist-MoE | aux loss 接协议但保持既有启用策略;Dist-MoE 单独适配 NPU 通信、容量和反向 |
@@ -29,7 +29,6 @@
29 ".torchtitan.models.common",29 ".torchtitan.models.common",
30 ".torchtitan.trainer",30 ".torchtitan.trainer",
31 ".torchtitan.components.metrics",31 ".torchtitan.components.metrics",
32- ".torchtitan.experiments.graph_trainer",
33 ".torchtitan.tools.utils",32 ".torchtitan.tools.utils",
34 ".torchtitan.eager_flex",33 ".torchtitan.eager_flex",
35 ".compile.dynamo_config"34 ".compile.dynamo_config"
@@ -38,16 +37,11 @@
38 ".components.checkpointer",37 ".components.checkpointer",
39 ".components.metrics",38 ".components.metrics",
40 ".components.optimizer",39 ".components.optimizer",
41- ".distributed.context_parallel",
42- ".experiments.graph_trainer.chunked_loss",
43- ".experiments.graph_trainer.ep_overlap_shape_queries",
44 ".observability",40 ".observability",
45- ".models.common.attention_metadata",
46- ".models.common.decoder",
47 ".models.common.moe",41 ".models.common.moe",
48 ".models.common.rope",42 ".models.common.rope",
49 ".models.common.token_dispatcher",43 ".models.common.token_dispatcher",
50- ".models.deepseek_v3.mtp"44+ ".models.deepseek_v4"
51 ]45 ]
52 }46 }
53}47}
@@ -0,0 +1,160 @@
1+#!/usr/bin/env bash
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
3+#
4+# This source code is licensed under the BSD-style license found in the
5+# LICENSE file in the root directory of this source tree.
6+ 
7+# Build a candidate wheel from a fresh checkout. Never install or publish it.
8+set -euo pipefail
9+ 
10+readonly TORCH_NPU_REPOSITORY="https://github.com/Ascend/pytorch.git"
11+readonly TORCH_NPU_REVISION="848b8e7271069d5a9947bf75fd02a162092b41a6"
12+readonly TORCH_NPU_VERSION="2.15.0+git848b8e7"
13+readonly TORCH_VERSION="2.15.0+cpu"
14+readonly -a SUBMODULES=(
15+ third_party/op-plugin
16+ third_party/nlohmann
17+ third_party/fmt
18+ third_party/dvm/dvm
19+ third_party/acl_src/runtime
20+ third_party/acl_src/ge
21+ third_party/acl_src/graph-autofusion
22+)
23+ 
24+usage() {
25+ echo "Usage: PYTHON_BIN=/path/to/python $0 --wheelhouse DIR"
26+ echo " PYTHON_BIN=/path/to/python $0 --verify-wheel FILE"
27+}
28+ 
29+if [[ $# != 2 ]] || [[ "$1" != "--wheelhouse" && "$1" != "--verify-wheel" ]]; then
30+ if [[ $# == 1 && "$1" == "--help" ]]; then usage; exit 0; fi
31+ usage >&2
32+ exit 2
33+fi
34+mode="$1"
35+output="$2"
36+if [[ -z "$output" ]]; then
37+ echo "A non-empty output path is required." >&2
38+ exit 2
39+fi
40+PYTHON_BIN="$(command -v "${PYTHON_BIN:-python}")" || { echo "Python interpreter not found." >&2; exit 1; }
41+export PYTHONNOUSERSITE=1 TORCH_DEVICE_BACKEND_AUTOLOAD=0
42+ 
43+verify_wheel() {
44+ "${PYTHON_BIN}" - "$1" "$TORCH_NPU_VERSION" "$TORCH_VERSION" <<'PY'
45+import email
46+import sys
47+import zipfile
48+from pathlib import Path
49+ 
50+from packaging.requirements import Requirement
51+from packaging.tags import sys_tags
52+from packaging.utils import canonicalize_name, parse_wheel_filename
53+from packaging.version import Version
54+ 
55+if sys.version_info[:2] != (3, 12):
56+ raise ValueError("Python 3.12 is required to verify this candidate")
57+path = Path(sys.argv[1])
58+name, version, _, tags = parse_wheel_filename(path.name)
59+if canonicalize_name(name) != "torch-npu" or version != Version(sys.argv[2]):
60+ raise ValueError(f"unexpected wheel name/version: {path.name}")
61+compatible = set(tags).intersection(sys_tags())
62+if not any(tag.interpreter == "cp312" and tag.abi == "cp312" and tag.platform != "any" for tag in compatible):
63+ raise ValueError(f"wheel is incompatible with this CPython 3.12 interpreter: {path.name}")
64+with zipfile.ZipFile(path) as wheel:
65+ metadata_files = [name for name in wheel.namelist() if name.endswith(".dist-info/METADATA")]
66+ if len(metadata_files) != 1:
67+ raise ValueError("wheel must contain exactly one METADATA file")
68+ metadata = email.message_from_bytes(wheel.read(metadata_files[0]))
69+if canonicalize_name(metadata["Name"]) != "torch-npu" or Version(metadata["Version"]) != version:
70+ raise ValueError("wheel metadata disagrees with its filename")
71+requirements = [Requirement(value) for value in metadata.get_all("Requires-Dist", [])]
72+torch_requirements = [
73+ requirement
74+ for requirement in requirements
75+ if canonicalize_name(requirement.name) == "torch"
76+ and (requirement.marker is None or requirement.marker.evaluate({"extra": ""}))
77+]
78+if (
79+ len(torch_requirements) != 1
80+ or not torch_requirements[0].specifier
81+ or not torch_requirements[0].specifier.contains(Version(sys.argv[3]))
82+):
83+ raise ValueError(f"wheel does not declare a compatible torch requirement: {torch_requirements}")
84+print(f"Verified {path.name}: {torch_requirements[0]}")
85+PY
86+}
87+ 
88+if [[ "$mode" == "--verify-wheel" ]]; then
89+ verify_wheel "$output"
90+ exit 0
91+fi
92+ 
93+"${PYTHON_BIN}" - "$TORCH_VERSION" <<'PY'
94+import sys
95+from importlib.metadata import version
96+ 
97+if sys.version_info[:2] != (3, 12):
98+ raise SystemExit(f"Python 3.12 is required, got {sys.version}")
99+if version("torch") != sys.argv[1]:
100+ raise SystemExit(f"Expected torch {sys.argv[1]}, got {version('torch')}")
101+PY
102+ 
103+# The upstream build invokes `python3.12`; ensure it selects this environment,
104+# without replacing or installing an interpreter in the environment.
105+python_dir="$(cd "$(dirname "$PYTHON_BIN")" && pwd -P)"
106+export PATH="${python_dir}:${PATH}"
107+if [[ "$(python3.12 -c 'import sys; print(sys.prefix)')" != "$("$PYTHON_BIN" -c 'import sys; print(sys.prefix)')" ]]; then
108+ echo "python3.12 does not resolve to the requested Python environment." >&2
109+ exit 1
110+fi
111+mkdir -p "$output"
112+wheelhouse="$(cd "$output" && pwd -P)"
113+build_dir="$(mktemp -d "${TMPDIR:-/tmp}/torchtitan-npu-wheel.XXXXXXXX")"
114+trap 'rm -rf -- "$build_dir"' EXIT
115+checkout="${build_dir}/pytorch"
116+git clone --no-checkout "$TORCH_NPU_REPOSITORY" "$checkout"
117+git -C "$checkout" checkout --detach "$TORCH_NPU_REVISION"
118+[[ "$(git -C "$checkout" rev-parse HEAD)" == "$TORCH_NPU_REVISION" ]]
119+git -C "$checkout" submodule update --init -- "${SUBMODULES[@]}"
120+for path in "${SUBMODULES[@]}"; do
121+ expected="$(git -C "$checkout" ls-tree HEAD -- "$path" | awk '{print $3}')"
122+ actual="$(git -C "$checkout/$path" rev-parse HEAD)"
123+ if [[ -z "$expected" || "$expected" != "$actual" ]]; then
124+ echo "Submodule does not match gitlink: $path" >&2
125+ exit 1
126+ fi
127+done
128+{
129+ printf 'repository=%s\nrevision=%s\n' "$TORCH_NPU_REPOSITORY" "$TORCH_NPU_REVISION"
130+ printf 'python=%s\n' "$("$PYTHON_BIN" --version 2>&1)"
131+ printf 'torch=%s\n' "$TORCH_VERSION"
132+ printf 'command=ci/build.sh --python=3.12 --torch=2.15.0 --disable_torchair --disable_fxrt --disable_rpc\n'
133+ git -C "$checkout" submodule status -- "${SUBMODULES[@]}"
134+} > "${build_dir}/manifest"
135+(
136+ cd "$checkout"
137+ bash ci/build.sh --python=3.12 --torch=2.15.0 --disable_torchair --disable_fxrt --disable_rpc
138+)
139+shopt -s nullglob
140+wheels=("${checkout}"/dist/torch_npu-*.whl)
141+if [[ ${#wheels[@]} != 1 ]]; then
142+ echo "Expected exactly one torch_npu wheel; found ${#wheels[@]}." >&2
143+ exit 1
144+fi
145+verify_wheel "${wheels[0]}"
146+wheel_name="$(basename "${wheels[0]}")"
147+destination="${wheelhouse}/${wheel_name}"
148+if [[ -e "$destination" ]]; then
149+ if ! cmp -s -- "${wheels[0]}" "$destination"; then
150+ echo "Refusing to overwrite a different wheel: $destination" >&2
151+ exit 1
152+ fi
153+else
154+ cp -- "${wheels[0]}" "$destination"
155+fi
156+checksum="$(sha256sum "$destination" | awk '{print $1}')"
157+printf 'sha256=%s %s\n' "$checksum" "$wheel_name" >> "${build_dir}/manifest"
158+manifest="$(mktemp "${wheelhouse}/${wheel_name}.build-info.XXXXXXXX")"
159+cp -- "${build_dir}/manifest" "$manifest"
160+printf 'Wheel: %s\nManifest: %s\n' "$destination" "$manifest"
@@ -66,12 +66,9 @@ _setup_torchtitan "${TORCHTITAN_DIR}"
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 CI image supplies torch 2.14.0.dev; the matching torchvision CPU wheel
70-# is installed with --no-deps (resolving its torch pin would fight the image).
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"
72"${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu, torchvision'69"${PYTHON_BIN}" -c 'import torchtitan, torchtitan_npu, torchvision'
73 70 
74-export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"71+export MODULE="${MODULE:-torchtitan_npu_recipes.models.deepseek_v4}"
75export CONFIG="${CONFIG:-deepseek_v4_debugmodel}"72export CONFIG="${CONFIG:-deepseek_v4_debugmodel}"
76export NGPU73export NGPU
77export LOG_RANK="${LOG_RANK:-0}"74export LOG_RANK="${LOG_RANK:-0}"
@@ -26,19 +26,3 @@ RUN python3 -m pip install --no-cache-dir \
26 26 
27COPY requirements.txt /tmp/requirements.txt27COPY requirements.txt /tmp/requirements.txt
28COPY requirements-dev.txt /tmp/requirements-dev.txt28COPY requirements-dev.txt /tmp/requirements-dev.txt
29- 
30-# The self-built torch_npu wheel is CPython 3.12/aarch64 only. Install its
31-# dependencies first, then install the wheel without dependencies because its
32-# metadata pins torch==2.14.0 while this image intentionally uses a matching
33-# torch nightly build.
34-RUN test "$(uname -m)" = "aarch64" \
35- && python3 -c 'import sys; assert sys.version_info[:2] == (3, 12), sys.version' \
36- && sed -E '/^torch_npu[[:space:]]*(@|==)/d' /tmp/requirements.txt > /tmp/requirements_without_torch_npu.txt \
37- && python3 -m pip install --no-cache-dir --prefer-binary --retries 10 --timeout 120 \
38- -r /tmp/requirements_without_torch_npu.txt \
39- -r /tmp/requirements-dev.txt \
40- && { grep '^--find-links[[:space:]]' /tmp/requirements.txt > /tmp/torch_npu_requirement.txt || true; } \
41- && grep -E '^torch_npu[[:space:]]*(@|==)' /tmp/requirements.txt >> /tmp/torch_npu_requirement.txt \
42- && test -s /tmp/torch_npu_requirement.txt \
43- && python3 -m pip install --no-cache-dir --no-deps --retries 10 --timeout 120 \
44- -r /tmp/torch_npu_requirement.txt
@@ -5,27 +5,22 @@
5 5 
6set -e6set -e
7 7 
8-# set python3.12 and pip3.12 as default8+# Use one interpreter for pip, TorchTitan setup, and the test process.
9-if ! PYTHON_BIN="$(command -v python3.12)"; then9+if ! PYTHON_BIN="$(command -v "${PYTHON_BIN:-python3.12}")"; then
10- echo "python3.12 not found" >&210+ echo "Python interpreter not found" >&2
11 exit 111 exit 1
12fi12fi
13-if ! PIP_BIN="$(command -v pip3.12)"; then13+"${PYTHON_BIN}" -c 'import sys; assert sys.version_info[:2] == (3, 12), sys.version'
14- echo "pip3.12 not found" >&214+readonly PYTHON_BIN
15- exit 1
16-fi
17-readonly PYTHON_BIN PIP_BIN
18readonly PYTHON_SHIM_DIR="$(mktemp -d "${TMPDIR:-/tmp}/torchtitan-npu-python.XXXXXX")"15readonly PYTHON_SHIM_DIR="$(mktemp -d "${TMPDIR:-/tmp}/torchtitan-npu-python.XXXXXX")"
19ln -s "${PYTHON_BIN}" "${PYTHON_SHIM_DIR}/python"16ln -s "${PYTHON_BIN}" "${PYTHON_SHIM_DIR}/python"
20ln -s "${PYTHON_BIN}" "${PYTHON_SHIM_DIR}/python3"17ln -s "${PYTHON_BIN}" "${PYTHON_SHIM_DIR}/python3"
21-ln -s "${PIP_BIN}" "${PYTHON_SHIM_DIR}/pip"
22export PATH="${PYTHON_SHIM_DIR}:${PATH}"18export PATH="${PYTHON_SHIM_DIR}:${PATH}"
23 19 
24_cleanup_python_shims() {20_cleanup_python_shims() {
25 rm -f -- \21 rm -f -- \
26 "${PYTHON_SHIM_DIR}/python" \22 "${PYTHON_SHIM_DIR}/python" \
27- "${PYTHON_SHIM_DIR}/python3" \23+ "${PYTHON_SHIM_DIR}/python3"
28- "${PYTHON_SHIM_DIR}/pip"
29 rmdir -- "${PYTHON_SHIM_DIR}"24 rmdir -- "${PYTHON_SHIM_DIR}"
30}25}
31trap _cleanup_python_shims EXIT26trap _cleanup_python_shims EXIT
@@ -37,26 +32,62 @@ source "${SCRIPT_DIR}/setup_torchtitan.sh"
37TORCHTITAN_COMMIT="$(_torchtitan_revision)"32TORCHTITAN_COMMIT="$(_torchtitan_revision)"
38TORCHTITAN_DIR="${TORCHTITAN_DIR:-${PROJECT_ROOT}/third_party/torchtitan}"33TORCHTITAN_DIR="${TORCHTITAN_DIR:-${PROJECT_ROOT}/third_party/torchtitan}"
39 34 
40-source /home/jenkins/Ascend/cann-9.2.0/set_env.sh35+# v0.4.0 pairs torch_npu 2.15 with CANN 9.3; keep 9.2 as the image fallback.
36+if [[ -f /home/jenkins/Ascend/cann-9.3.0/set_env.sh ]]; then
37+ source /home/jenkins/Ascend/cann-9.3.0/set_env.sh
38+else
39+ source /home/jenkins/Ascend/cann-9.2.0/set_env.sh
40+fi
41# Prevent torch from eagerly importing torch_npu while spmd_types is initializing.41# Prevent torch from eagerly importing torch_npu while spmd_types is initializing.
42export TORCH_DEVICE_BACKEND_AUTOLOAD=042export TORCH_DEVICE_BACKEND_AUTOLOAD=0
43+# torch 2.15 headers require C++20 when cann_ops_nn builds its JIT extensions.
44+export CXXFLAGS="${CXXFLAGS:-} -std=c++20"
43 45 
44cd "${PROJECT_ROOT}"46cd "${PROJECT_ROOT}"
45export PYTHONPATH="${PROJECT_ROOT}${PYTHONPATH:+:${PYTHONPATH}}"47export PYTHONPATH="${PROJECT_ROOT}${PYTHONPATH:+:${PYTHONPATH}}"
46-pip install -r requirements-dev.txt48+"${PYTHON_BIN}" -m pip install -r requirements-dev.txt
47 49 
48_setup_torchtitan "${TORCHTITAN_DIR}"50_setup_torchtitan "${TORCHTITAN_DIR}"
49export TORCHTITAN_DIR51export TORCHTITAN_DIR
50-# Resolve upstream runtime dependencies using the transport configured above.52+# Resolve the runtime dependencies pinned by the target TorchTitan release.
51-pip install -e "${TORCHTITAN_DIR}"53+"${PYTHON_BIN}" -m pip install torch_remat==0.2.2
52-# The NPU package overrides upstream's attn-gym pin; keep the image's torch stack.54+# The UT image is x86_64 CPython 3.12. Pull the pinned wheel set from the CI wheel
53-pip install --no-deps \55+# mirror; the PTA daily bundle is too slow from the restricted CI network.
56+test "$(uname -m)" = "x86_64" || {
57+ echo "The CI wheel set is published for x86_64 only" >&2
58+ exit 1
59+}
60+CI_WHEELS_TAG="${CI_WHEELS_TAG:-torch-2.15.0-cpu-cp312-x86_64}"
61+CI_WHEELS_BASE="${CI_WHEELS_BASE:-https://gitcode.com/hitwdy/torchtitan-npu-ci-wheels/releases/download/${CI_WHEELS_TAG}}"
62+TORCH_WHEELHOUSE="$(mktemp -d "${TMPDIR:-/tmp}/torchtitan-npu-torch.XXXXXX")"
63+trap '_cleanup_python_shims; rm -rf -- "${TORCH_WHEELHOUSE}"' EXIT
64+TORCH_VERSION="$(sed -n 's/^torch==//p' requirements.txt)"
65+TORCHVISION_VERSION="$(sed -n 's/^torchvision==//p' requirements.txt)"
66+TORCH_NPU_VERSION="$(sed -n 's/^torch_npu==//p' requirements.txt)"
67+TORCH_WHEEL="torch-${TORCH_VERSION}-cp312-cp312-manylinux_2_28_x86_64.whl"
68+TORCHVISION_WHEEL="torchvision-${TORCHVISION_VERSION}-py3-none-manylinux_2_28_x86_64.whl"
69+TORCH_NPU_WHEEL="torch_npu-${TORCH_NPU_VERSION}-cp312-cp312-manylinux_2_28_x86_64.whl"
70+curl -fL --retry 3 "${CI_WHEELS_BASE}/${TORCH_WHEEL//+/%2B}" -o "${TORCH_WHEELHOUSE}/${TORCH_WHEEL}"
71+curl -fL --retry 3 "${CI_WHEELS_BASE}/${TORCHVISION_WHEEL//+/%2B}" -o "${TORCH_WHEELHOUSE}/${TORCHVISION_WHEEL}"
72+curl -fL --retry 3 "${CI_WHEELS_BASE}/${TORCH_NPU_WHEEL//+/%2B}" -o "${TORCH_WHEELHOUSE}/${TORCH_NPU_WHEEL}"
73+(
74+ cd "${TORCH_WHEELHOUSE}"
75+ sha256sum -c <<'EOF'
76+0955c7e3446326293f48af18fad67872fa31dee5a36a87690eb9e5be8b465be3 torch-2.15.0+cpu-cp312-cp312-manylinux_2_28_x86_64.whl
77+87631236a47be98ab21301e8cb4fc1cbb9325fe0aa7a022e18d2f894087b68c3 torchvision-0.29.2+cpu-py3-none-manylinux_2_28_x86_64.whl
78+45fff2691b918f8591801c3bbae4bc4c0799e38f2bf811766dd49b35cc5a9ffb torch_npu-2.15.0.dev20261105-cp312-cp312-manylinux_2_28_x86_64.whl
79+EOF
80+)
81+"${PYTHON_BIN}" -m pip install --no-cache-dir --force-reinstall --no-deps \
82+ "${TORCH_WHEELHOUSE}/${TORCH_WHEEL}" \
83+ "${TORCH_WHEELHOUSE}/${TORCHVISION_WHEEL}" \
84+ "${TORCH_WHEELHOUSE}/${TORCH_NPU_WHEEL}"
85+"${PYTHON_BIN}" -m pip install -e "${TORCHTITAN_DIR}"
86+# Keep the torch stack installed above and the target TorchTitan attention version.
87+"${PYTHON_BIN}" -m pip install --no-deps \
54 --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torchft/index.html \88 --find-links https://cann-ai.obs.cn-north-4.myhuaweicloud.com/torchtitan-npu/simple/torchft/index.html \
55- 'torchft==0.2.0' 'attn-gym==0.0.16'89+ 'torchft==0.2.0' 'attn-gym==0.0.17'
56-pip install --no-deps -e .90+"${PYTHON_BIN}" -m pip install --no-deps -e .
57- 
58-pip install --no-deps torchvision==0.29.0+cpu \
59- --index-url https://download.pytorch.org/whl/cpu
60 91 
61python -c 'import grain, renderers, spmd_types, torch_remat, torchtitan, torchtitan_npu'92python -c 'import grain, renderers, spmd_types, torch_remat, torchtitan, torchtitan_npu'
62python -m pytest -v --tb=short tests/unit_tests93python -m pytest -v --tb=short tests/unit_tests
@@ -11,6 +11,7 @@
11| `torchtitan_npu/extensions/` | 永久扩展、可选 adaptor 和组件集成 |11| `torchtitan_npu/extensions/` | 永久扩展、可选 adaptor 和组件集成 |
12| `torchtitan_npu/override/` | 由 `override.imports` 显式启用的组件替换 |12| `torchtitan_npu/override/` | 由 `override.imports` 显式启用的组件替换 |
13| `torchtitan_npu/models/` | 模型配置、实现、并行化和 checkpoint 适配 |13| `torchtitan_npu/models/` | 模型配置、实现、并行化和 checkpoint 适配 |
14+| `torchtitan_npu_recipes/` | 返回完整 Trainer.Config 的训练组合;可复用实现保留在插件包 |
14| `torchtitan_npu/ops/` | NPU 专属算子与后端注册 |15| `torchtitan_npu/ops/` | NPU 专属算子与后端注册 |
15| `torchtitan_npu/tools/` | 随 package 分发的转换和导出工具 |16| `torchtitan_npu/tools/` | 随 package 分发的转换和导出工具 |
16| `scripts/` | 仓库维护、训练和合规脚本 |17| `scripts/` | 仓库维护、训练和合规脚本 |
@@ -57,7 +57,7 @@ SIG 例会:[sig-framework-adapter](https://meeting.osinfra.cn/cann?sig=sig-fra
57```shell57```shell
58git clone https://gitcode.com/cann/torchtitan-npu.git58git clone https://gitcode.com/cann/torchtitan-npu.git
59cd torchtitan-npu59cd torchtitan-npu
60-git checkout master60+git checkout dev_0.4.0
61pip install -r requirements.txt61pip install -r requirements.txt
62pip install -e .62pip install -e .
63```63```
@@ -68,6 +68,8 @@ pip install -e .
68快速启动大语言模型的训练任务,参见68快速启动大语言模型的训练任务,参见
69[快速上手文档](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) 。
70 70 
71+完整训练配置位于 [`torchtitan_npu_recipes`](torchtitan_npu_recipes/README.md),自定义训练组合见 [Python 配置指南](docs/developer_guides/python_recipes.md)。
72+ 
71 73 
72<a id="特性支持概览"></a>74<a id="特性支持概览"></a>
73 75 
@@ -6,9 +6,10 @@
6 6 
7```text7```text
8torchtitan_npu/ Ascend NPU 插件主体8torchtitan_npu/ Ascend NPU 插件主体
9+torchtitan_npu_recipes/ 完整训练配置与 recipe 组合
9experiments/ 独立实验包;当前包含 torchao-npu distribution10experiments/ 独立实验包;当前包含 torchao-npu distribution
10docs/ 架构、开发者、功能和用户文档11docs/ 架构、开发者、功能和用户文档
11-examples/ 可运行 recipe、模型配置与示例 launcher12+examples/ 选择完整 Python 配置的示例 launcher
12scripts/ 训练、转换、合规检查与辅助脚本13scripts/ 训练、转换、合规检查与辅助脚本
13tests/ CPU UT、NPU ST 与 tooling 自测14tests/ CPU UT、NPU ST 与 tooling 自测
14.agents/ Agent Notes 与可复用 skills15.agents/ Agent Notes 与可复用 skills
@@ -22,7 +23,7 @@ tests/ CPU UT、NPU ST 与 tooling 自测
22 23 
23| 子包 | 职责 | 直接依赖边界 |24| 子包 | 职责 | 直接依赖边界 |
24| --- | --- | --- |25| --- | --- | --- |
25-| `config/` | NPU config schema、纯转换器和显式注册 API | 当前包导入会安装 ConfigManager loader wrapper;目标是移至 extension 激活入口且不反向导入具体 extension |26+| `config/` | NPU config schema、纯转换器和显式注册 API | 当前包导入会安装 ConfigLoader loader wrapper;目标是移至 extension 激活入口且不反向导入具体 extension |
26| `patches/` | 上游 `torchtitan` 或 `torch_npu` 的待合入补丁 | 不得新增对 `extensions/` 的依赖;现有反向边记录为迁移债务 |27| `patches/` | 上游 `torchtitan` 或 `torch_npu` 的待合入补丁 | 不得新增对 `extensions/` 的依赖;现有反向边记录为迁移债务 |
27| `models/` | 尚未上游化的模型定义、配置、并行化与 checkpoint 适配 | 现有跨层依赖为迁移债务,不以本文宣称已清零 |28| `models/` | 尚未上游化的模型定义、配置、并行化与 checkpoint 适配 | 现有跨层依赖为迁移债务,不以本文宣称已清零 |
28| `extensions/` | 本仓永久额外扩展、组件集成与图编译注册 | 可以依赖 `patches/` 提供的定义;不得新增对 `models/`、`override/` 或 `ops/` 的依赖 |29| `extensions/` | 本仓永久额外扩展、组件集成与图编译注册 | 可以依赖 `patches/` 提供的定义;不得新增对 `models/`、`override/` 或 `ops/` 的依赖 |
@@ -31,6 +32,10 @@ tests/ CPU UT、NPU ST 与 tooling 自测
31| `ops/` | 设备后端 kernel、最小启动封装与 `torch.library` 注册 | 仅保留实现算子所需的后端代码 |32| `ops/` | 设备后端 kernel、最小启动封装与 `torch.library` 注册 | 仅保留实现算子所需的后端代码 |
32| `tools/` | 随 package 分发的 checkpoint 转换与导出工具 | 依赖公开模型与 integration API,不承载训练期自动注入 |33| `tools/` | 随 package 分发的 checkpoint 转换与导出工具 | 依赖公开模型与 integration API,不承载训练期自动注入 |
33 34 
35+完整训练工厂位于 [`torchtitan_npu_recipes/`](../torchtitan_npu_recipes/README.md),通过完整模块路径和工厂名选择。模型 flavor registry、Muon profile、Engram 优化器 schema、数据转换函数和模型专属 trainer/engine 保留在插件中;插件实现不得反向导入 recipe。图训练组合单独放在 `torchtitan_npu_recipes/graph_trainer/`,不会因 eager recipe 的导入而自动启用。
36+ 
37+`torchtitan_npu_recipes/examples/` 保存与每个示例脚本同名的完整配置工厂,组合基础模型工厂以及数据、优化器、并行、checkpoint 和 override 选择。`examples/` shell 只设置启动资源并调用共用 launcher,原生 CLI 参数原样传递。
38+ 
34模型无关能力放在最通用的适用位置。完整的开发约束见 [主包规则](../torchtitan_npu/AGENTS.md) 及其目录级规则。39模型无关能力放在最通用的适用位置。完整的开发约束见 [主包规则](../torchtitan_npu/AGENTS.md) 及其目录级规则。
35 40 
36## 导入与启用41## 导入与启用
@@ -43,7 +48,7 @@ patches → config → extensions → ops
43 48 
44这是当前运行时行为,不是目标顺序。`patches` 先替换上游实现;`extensions` 可从 `torchtitan_npu.patches.*` 复用 patch 提供的定义,也可经 `torchtitan.*`、`torch.*` 或 `torch_npu.*` 使用已替换结果。反向的 `patches → extensions` 依赖不得新增。49这是当前运行时行为,不是目标顺序。`patches` 先替换上游实现;`extensions` 可从 `torchtitan_npu.patches.*` 复用 patch 提供的定义,也可经 `torchtitan.*`、`torch.*` 或 `torch_npu.*` 使用已替换结果。反向的 `patches → extensions` 依赖不得新增。
45 50 
46-`config` 当前导入 `manager` 时会安装 `ConfigManager._load_config` 的转换 wrapper;该副作用是现有配置转换链的一部分。将其改为仅由 extension 激活入口安装是后续目标,不是当前行为。51+`config` 当前导入 `manager` 时会安装 `ConfigLoader._load_config` 的转换 wrapper;该副作用是现有配置转换链的一部分。将其改为仅由 extension 激活入口安装是后续目标,不是当前行为。
47 52 
48`override` 不自动加载;一次训练由 `override.imports` 显式选择。将自动导入收敛为下列顺序是后续目标,不能据此描述当前行为:53`override` 不自动加载;一次训练由 `override.imports` 显式选择。将自动导入收敛为下列顺序是后续目标,不能据此描述当前行为:
49 54 
@@ -71,7 +76,7 @@ patch 替换后必须刷新或说明上游 `from ... import ...` 已捕获的绑
71 76 
72### extensions77### extensions
73 78 
74-`extensions/torchtitan/` 放镜像上游结构的 monkey-patch 激活模块;新增替换必须声明 owner 和顺序。现有 `MetricsProcessor.log`、`CheckpointManager` 与 `ConfigManager._load_config` 的多层包装保留为历史例外,包装顺序由对应测试保护,本轮不合并其业务行为。`extensions/components/` 放带声明名称的自包含集成;当前 TrainerEx、checkpoint extension 和 DeepSeek-V4.1 配置仍存在组件顶层接线或反向使用,这是迁移债务,不是新组件约束。`extensions/compile/` 放 graph-pass 注册基础设施和具体 pattern。79+`extensions/torchtitan/` 放镜像上游结构的 monkey-patch 激活模块;新增替换必须声明 owner 和顺序。现有 `MetricsProcessor.log`、`CheckpointManager` 与 `ConfigLoader._load_config` 的多层包装保留为历史例外,包装顺序由对应测试保护,本轮不合并其业务行为。`extensions/components/` 放带声明名称的自包含集成;当前 TrainerEx、checkpoint extension 和 DeepSeek-V4.1 配置仍存在组件顶层接线或反向使用,这是迁移债务,不是新组件约束。`extensions/compile/` 放 graph-pass 注册基础设施和具体 pattern。
75 80 
76`extensions/` 当前还包含 `adaptor/`、`cpu_offload/`、`distributed/`、`mx_storage_reader/`、`novaswap/` 与 `experiment/`。其中仅包入口显式列出的模块自动加载;其余目录由调用路径按需导入。各目录的职责和加载方式见 [extensions 规则](../torchtitan_npu/extensions/AGENTS.md)。81`extensions/` 当前还包含 `adaptor/`、`cpu_offload/`、`distributed/`、`mx_storage_reader/`、`novaswap/` 与 `experiment/`。其中仅包入口显式列出的模块自动加载;其余目录由调用路径按需导入。各目录的职责和加载方式见 [extensions 规则](../torchtitan_npu/extensions/AGENTS.md)。
77 82 
@@ -1,5 +1,7 @@
1# Checkpoint 使用指南1# Checkpoint 使用指南
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3本文说明如何使用 TorchTitan 的 checkpoint 机制保存、加载5本文说明如何使用 TorchTitan 的 checkpoint 机制保存、加载
4`torchtitan-npu` 训练状态,以及如何加载或保存 Hugging Face safetensors 权重。6`torchtitan-npu` 训练状态,以及如何加载或保存 Hugging Face safetensors 权重。
5 7 
@@ -17,8 +19,8 @@
17 19 
18| 模块 | 配置入口 | checkpoint 默认值 |20| 模块 | 配置入口 | checkpoint 默认值 |
19| --- | --- | --- |21| --- | --- | --- |
20-| `torchtitan_npu.models.deepseek_v4.config_registry` | `deepseek_v4_debugmodel`、`deepseek_v4_flash`、`deepseek_v4_pro` | `enable=False`,`interval=100` |22+| `torchtitan_npu_recipes.models.deepseek_v4` | `deepseek_v4_debugmodel`、`deepseek_v4_flash`、`deepseek_v4_pro` | `enable=False`,`interval=100` |
21-| `torchtitan_npu.models.deepseek_v3_2.config_registry` | `deepseek_v3_2_debugmodel` | `enable=False`,`interval=10`,`last_save_model_only=False` |23+| `torchtitan_npu_recipes.models.deepseek_v3_2` | `deepseek_v3_2_debugmodel` | `enable=False`,`interval=10`,`last_save_model_only=False` |
22 24 
23`enable=False` 时既不会保存 checkpoint,也不会执行 checkpoint 加载。训练命令需要显式25`enable=False` 时既不会保存 checkpoint,也不会执行 checkpoint 加载。训练命令需要显式
24传入 `--checkpoint.enable`,或在 Python 配置中设置 `checkpoint.enable = True`。26传入 `--checkpoint.enable`,或在 Python 配置中设置 `checkpoint.enable = True`。
@@ -275,4 +277,4 @@ bash scripts/run_train.sh \
275- [快速上手](../user-guides/quickstart.md)277- [快速上手](../user-guides/quickstart.md)
276- [安装指南](../user-guides/installation.md)278- [安装指南](../user-guides/installation.md)
277- [训练启动脚本](../../scripts/run_train.sh)279- [训练启动脚本](../../scripts/run_train.sh)
278-- [DeepSeek-V4 checkpoint 配置](../../torchtitan_npu/models/deepseek_v4/config_registry.py)280+- [DeepSeek-V4 checkpoint 配置](../../torchtitan_npu_recipes/models/deepseek_v4.py)
@@ -1,5 +1,7 @@
1# 调试支持特性1# 调试支持特性
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3torchtitan-npu 目前提供多种调试特性支持,帮助开发者定位分布式训练中的各类问题,包括内存问题和性能瓶颈等。以下是常见使用场景和对应功能的快速参考:5torchtitan-npu 目前提供多种调试特性支持,帮助开发者定位分布式训练中的各类问题,包括内存问题和性能瓶颈等。以下是常见使用场景和对应功能的快速参考:
4 6 
5| 使用场景 | 对应功能 |7| 使用场景 | 对应功能 |
@@ -38,7 +40,7 @@ torchtitan 原生内存快照功能优先使用 `--profiler.memory-snapshot-freq
38 40 
39```bash41```bash
40torchrun --nproc_per_node=2 -m torchtitan_npu.train \42torchrun --nproc_per_node=2 -m torchtitan_npu.train \
41- --module torchtitan_npu.models.deepseek_v4 \43+ --module torchtitan_npu_recipes.models.deepseek_v4 \
42 --config deepseek_v4_debugmodel \44 --config deepseek_v4_debugmodel \
43 --profiler.enable-memory-snapshot \45 --profiler.enable-memory-snapshot \
44 --profiler.save-memory-snapshot-folder profiling/memory_snapshot \46 --profiler.save-memory-snapshot-folder profiling/memory_snapshot \
@@ -120,7 +122,7 @@ python3 scripts/parse_profiling_data.py path/to/save_traces_folder
120 122 
121```bash123```bash
122torchrun --nproc_per_node=2 -m torchtitan_npu.train \124torchrun --nproc_per_node=2 -m torchtitan_npu.train \
123- --module torchtitan_npu.models.deepseek_v4 \125+ --module torchtitan_npu_recipes.models.deepseek_v4 \
124 --config deepseek_v4_debugmodel \126 --config deepseek_v4_debugmodel \
125 --profiler.enable-profiling \127 --profiler.enable-profiling \
126 --profiler.save-traces-folder profiling/traces \128 --profiler.save-traces-folder profiling/traces \
@@ -0,0 +1,59 @@
1+# Python 训练配置
2+ 
3+完整训练工厂位于 [`torchtitan_npu_recipes`](../../torchtitan_npu_recipes/README.md)。工厂返回完整训练配置;shell launcher 只选择工厂、设备进程数及启动资源。专用训练策略、golden、优化器与算子组合应定义新 Python 工厂。
4+ 
5+`examples/` 下的训练脚本在 `torchtitan_npu_recipes.examples.<model>` 中选择对应工厂。例如 `deepseek_v4_mini_1p_cpt_2k_a3.sh` 选择 `torchtitan_npu_recipes.examples.deepseek_v4.deepseek_v4_mini_1p_cpt_2k_a3`;A3 8P Flash CPT debug 脚本默认选择带 `_eager` 后缀的工厂。工厂包含数据、模型、token budget、优化器、并行、checkpoint、profiling 和算子选择;基础模型工厂仍在 `torchtitan_npu_recipes.models` 中供组合复用。
6+ 
7+DeepSeek-V4 和 V4.1 示例默认使用非 golden 算子组合,显式设置 `USE_GOLDEN=1` 才选择参考组合。该开关由示例工厂读取,不改变基础模型工厂的默认配置。
8+ 
9+## 文本 eager 兼容性设置
10+ 
11+DeepSeek-V4 和 V4.1 文本 eager 基础工厂在 `config.override.imports` 中显式选择 `torchtitan_npu.override.common.rope.workaround`。该现有实现先将复数缓存展开为实数 cos/sin 缓存,再按位置索引,避开 NPU 不支持的 complex64 索引。基础配置同时使用 `compile=None` 和 `model.local_compile_regions=[]`;仅设置前者不能关闭模型组件的局部编译。
12+ 
13+这些兼容性设置不构成数值对齐证据;与原实现的数值比较尚未完成。融合或量化示例通过各自工厂选择算子组合,不能将文本 eager 的结果推广到这些配置。
14+ 
15+## 组合已有配置
16+ 
17+例如在仓库根目录创建 `my_recipes.py`,定义短步数 eager 配置:
18+ 
19+```python
20+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_debugmodel
21+ 
22+ 
23+def debug_five_steps():
24+ config = deepseek_v4_debugmodel()
25+ config.training.steps = 5
26+ config.hf_assets_path = "tests/assets/deepseek_v3"
27+ return config
28+```
29+ 
30+使用维护的单卡 launcher 选择该配置:
31+ 
32+```bash
33+MODULE=my_recipes CONFIG=debug_five_steps \
34+ bash examples/deepseek_v4/debug/deepseek_v4_eager_1p.sh
35+```
36+ 
37+HF 资源目录由 Python 配置的 `hf_assets_path` 字段指定;自定义 tokenizer 或模型资源时修改工厂中的路径,指向包含 tokenizer、`config.json` 等 HF 资源的目录。共用 launcher 会进入仓库根目录,相对路径从该目录解析。示例工厂也保留各自的 `HF_ASSETS_PATH`、数据路径等资源环境变量,具体默认值见对应 Python 工厂。
38+ 
39+上游 ConfigLoader 解析 `--module`、`--config`、`--override`、`--comm-backend`、`--output-dir`、`--resume-step` 和 `--print-config`。`--hf-assets-path` 及通用 `--training.*`、`--parallelism.*`、`--optimizer.*` 和 `--override.imports` 字段参数不属于 0.4.0 接口;将这些选择写入 Python 配置。现有 override 仍由配置的 `override.imports` 或 `--override` 选择,本轮不改变其注册机制。
40+ 
41+修改序列长度时同时调整模型、RoPE、数据与 token budget 的相应字段。并行与断点续训组合需要定义完整的 Python 工厂,并通过[集成测试入口](../../tests/integration_tests/README.md)验证。
42+ 
43+## 查看配置与启动资源
44+ 
45+所有示例将原生参数原样传递给共用 launcher。`--print-config` 原样交给上游 ConfigLoader,worker 打印配置后退出,不执行训练:
46+ 
47+```bash
48+bash examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh --print-config
49+```
50+ 
51+`NGPU`、`NNODES`、`NODE_IPS`、`NODE_RANK`、`MASTER_ADDR` 和 CANN 环境等进程启动资源留在 shell。多机示例在提供 `NODE_IPS` 时按地址数推导节点数;节点数以显式 `NNODES` 为准。未提供地址列表时需在每台机器设置 `MASTER_ADDR` 和 `NODE_RANK`。单机脚本 `scripts/run_train.sh` 只启动本机进程;多机示例显式调用 `scripts/run_train_multinodes.sh`,并在各节点执行。`WORLD_SIZE` 由 torchrun 设置,shell 不单独解析 `--print-config`;多机配置打印也经过正常的多机启动流程。
52+ 
53+旧 `CLI_OVERRIDES`、`OPTIMIZER_OVERRIDES` 等文本字段组合已移入 Python;传入这些旧入口会明确报错。自定义训练行为应修改或组合工厂,使用 `MODULE` / `CONFIG` 选择。
54+ 
55+## 归属与支持范围
56+ 
57+模型实现、Muon profile、数据转换和 trainer/engine 保留在 `torchtitan_npu/models/`,recipe 通过普通 Python import 组合这些实现。实现层不依赖 recipe。旧模型 `config_registry.py` 只保留 flavor registry,不再提供训练工厂。
58+ 
59+图训练基础工厂位于独立的 `torchtitan_npu_recipes.graph_trainer.deepseek_v4` 模块;示例组合由对应的 `examples` 工厂选择。配置迁移不代表新能力已经可用;当前 0.4.0 适配优先覆盖 DeepSeek 文本 eager,图训练、CP、多模态、SFT、LoRA 等路径仍保留各自的实现限制,并在构造或运行时明确失败。打印配置成功也不能代替 NPU 训练和数值回归。
@@ -1,5 +1,7 @@
1# DeepSeek-V4 系列上下文并行(CP)1# DeepSeek-V4 系列上下文并行(CP)
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3DeepSeek-V4(DSV4)与 DeepSeek-V4.1(DSV4.1)共用同一套上下文并行语义:**查询按文档内部分成5DeepSeek-V4(DSV4)与 DeepSeek-V4.1(DSV4.1)共用同一套上下文并行语义:**查询按文档内部分成
4`cp` 份,KV 与压缩 KV 保持整行**。融合内核在边界处把本地 slab 声明式 all-gather 成整行,再用6`cp` 份,KV 与压缩 KV 保持整行**。融合内核在边界处把本地 slab 声明式 all-gather 成整行,再用
5frame 的 `seqused = reach` 把可见范围限制在本 rank 的 chunk 之前。两栈共用7frame 的 `seqused = reach` 把可见范围限制在本 rank 的 chunk 之前。两栈共用
@@ -108,7 +110,7 @@ entry 的 `prepare_cp_metadata` 用 rank-local chunk 重建这三个 frame 以
108 110 
109```bash111```bash
110# DeepSeek-V4.1,两个 rank;先设置 HF_ASSETS_PATH 指向 tokenizer。112# DeepSeek-V4.1,两个 rank;先设置 HF_ASSETS_PATH 指向 tokenizer。
111-MODULE=torchtitan_npu.models.deepseek_v4_1 CONFIG=deepseek_v4_1_stripped NGPU=2 \113+MODULE=torchtitan_npu_recipes.models.deepseek_v4_1 CONFIG=deepseek_v4_1_stripped NGPU=2 \
112 bash scripts/run_train.sh \114 bash scripts/run_train.sh \
113 --hf-assets-path "$HF_ASSETS_PATH" \115 --hf-assets-path "$HF_ASSETS_PATH" \
114 --training.max-context-length 512 \116 --training.max-context-length 512 \
@@ -1,6 +1,6 @@
1# DeepSeek-V4 GraphTrainer 编译路径适配1# DeepSeek-V4 GraphTrainer 编译路径适配
2 2 
3-GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式分布式训练实验:用 `minimal_fx_tracer` 把 forward、loss、backward(可选 optimizer.step)整体捕获为单个 FX 图,所有优化都以 graph pass 的形式作用于同一张图。本适配让 DeepSeek-V4(DSV4)在该编译路径上可在 Ascend NPU 运行,与现有 eager 路径并行存在、互不影响。默认不启用:需要显式选择 `graph_trainer_*` 配置名。3+GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式分布式训练实验:用 `minimal_fx_tracer` 把 forward、loss、backward(可选 optimizer.step)整体捕获为单个 FX 图,所有优化都以 graph pass 的形式作用于同一张图。本仓保留 DeepSeek-V4(DSV4)的 NPU 图训练实现;TorchTitan 0.4.0 的当前验收范围为文本 eager,图训练仍待迁移和回归。图训练配置位于独立 recipe 模块。
4 4 
5## 上游 GraphTrainer 特性5## 上游 GraphTrainer 特性
6 6 
@@ -18,7 +18,7 @@ GraphTrainer 是 torchtitan 上游 `experiments/graph_trainer/` 中的编译式
18 18 
19### 配置入口19### 配置入口
20 20 
21-`torchtitan_npu/models/deepseek_v4/config_registry.py` 新增 5 个配置工厂,均复用对应 eager 配置,经 `to_graph_trainer_config` 包装为 `GraphTrainer.Config`:21+`torchtitan_npu_recipes/graph_trainer/deepseek_v4.py` 保存图训练组合,均复用 `torchtitan_npu_recipes.models.deepseek_v4` 中的对应 eager 配置,经 `torchtitan_npu/models/deepseek_v4/graph_trainer.py` 的 `to_graph_trainer_config` 包装为 `GraphTrainer.Config`:
22 22 
23| 配置名 | 对应 eager 配置 |23| 配置名 | 对应 eager 配置 |
24| --- | --- |24| --- | --- |
@@ -55,27 +55,11 @@ GraphTrainer 的 trace 约束与 eager 有本质差异:`minimal_fx_tracer` 在
55 55 
56## 激活方式56## 激活方式
57 57 
58-以 flash 43layers 模型、8 卡 EP=8 为例(对应 0825 验证脚本 `acc_align_smoke_ep_overlap.sh`):58+TorchTitan 0.4.0 适配当前只验收 DeepSeek 文本 eager,GraphTrainer 尚未完成迁移和回归。本页说明保留的实现结构,不作为当前版本可运行的图训练指南。
59 59 
60-```bash60+旧图训练 launcher 位于 `examples/deepseek_v4/` 及其 `debug/` 子目录,模块选择指向 `torchtitan_npu_recipes.graph_trainer.deepseek_v4`。其中的通用字段 CLI 参数仍需迁移为 Python 配置;迁移完成前不要据此启动 0.4.0 图训练。完整训练策略应定义新 recipe,由 shell launcher 选择,组合方式见 [recipe 指南](../../torchtitan_npu_recipes/README.md)。
61-torchrun --nproc_per_node=8 -m torchtitan.train \
62- --module torchtitan_npu.models.deepseek_v4 \
63- --config graph_trainer_deepseek_v4_flash_43layers_16experts \
64- --parallelism.expert-parallel-degree 8 \
65- --parallelism.data-parallel-shard-degree 8 \
66- --parallelism.spmd-backend spmd_types \
67- --override.imports \
68- torchtitan_npu.override.common.rms_norm.asc \
69- torchtitan_npu.override.common.rope.asc_complex \
70- 'torchtitan_npu.override.deepseek_v4.sparse_attn.asc={"num_heads":16,"index_num_heads":8}' \
71- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc \
72- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre \
73- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post \
74- torchtitan_npu.override.common.token_dispatcher.asc \
75- torchtitan_npu.override.common.optimizer.virtual
76-```
77 61 
78-编译配置(`aot_fx_trace`、禁用 `cudagraph_pass`)由配置工厂内置,无需 CLI 传入;`--compile.disable_passes cudagraph_pass` 仅对 eager 配置的默认编译路径必需。62+下表描述保留实现的设计范围;历史验证不代表当前依赖组合已通过验收。
79 63 
80## 支持范围与限制64## 支持范围与限制
81 65 
@@ -1,5 +1,7 @@
1# DeepSeek-V4 GraphTrainer 激活重计算1# DeepSeek-V4 GraphTrainer 激活重计算
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3本文说明 `torchtitan-npu` 中 DeepSeek-V4 GraphTrainer 的激活重计算设计,包括默认 `full` 策略、可选 `dsv4-mhc` / `dsv4-mhc-moe-save` 策略、使用方式和已知限制。5本文说明 `torchtitan-npu` 中 DeepSeek-V4 GraphTrainer 的激活重计算设计,包括默认 `full` 策略、可选 `dsv4-mhc` / `dsv4-mhc-moe-save` 策略、使用方式和已知限制。
4 6 
5 7 
@@ -33,7 +35,7 @@ disable_passes = ["cudagraph_pass"]
33配置位置:35配置位置:
34 36 
35```text37```text
36-torchtitan_npu/models/deepseek_v4/config_registry.py38+torchtitan_npu_recipes/graph_trainer/deepseek_v4.py
37```39```
38 40 
39五个 GraphTrainer recipe 均使用 `num_mtp_layers=0` 和 `memory_policy="full"`。41五个 GraphTrainer recipe 均使用 `num_mtp_layers=0` 和 `memory_policy="full"`。
@@ -165,7 +167,7 @@ CPU offload 与 SAR 之前把变异写入显式化为数据流,原生 SAR 随
165 167 
166| 功能 | 文件 |168| 功能 | 文件 |
167| --- | --- |169| --- | --- |
168-| DSV4 GraphTrainer 配置 | `torchtitan_npu/models/deepseek_v4/config_registry.py` |170+| DSV4 GraphTrainer 配置 | `torchtitan_npu_recipes/graph_trainer/deepseek_v4.py` |
169| 通用 full policy | `torchtitan/experiments/graph_trainer/memory_policy.py` |171| 通用 full policy | `torchtitan/experiments/graph_trainer/memory_policy.py` |
170| NPU policy 框架 | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py` |172| NPU policy 框架 | `torchtitan_npu/patches/torchtitan/experiments/graph_trainer/memory_policy.py` |
171| `dsv4-mhc` / `dsv4-mhc-moe-save` 策略 | `torchtitan_npu/models/deepseek_v4/memory_policy.py` |173| `dsv4-mhc` / `dsv4-mhc-moe-save` 策略 | `torchtitan_npu/models/deepseek_v4/memory_policy.py` |
@@ -1,5 +1,7 @@
1# 融合算子接入指南1# 融合算子接入指南
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3本文面向在 `torchtitan-npu` 中接入 AscendC、Triton 或者 Tilelang 等融合算子的开发者。5本文面向在 `torchtitan-npu` 中接入 AscendC、Triton 或者 Tilelang 等融合算子的开发者。
4融合算子应作为 NPU 适配层通过 [override 机制](../../torchtitan_npu/override/README.md) 接入,不修改上游 `torchtitan`;默认训练路径不受影响,只有在 `override.imports` 中显式列出入口后才会替换组件。6融合算子应作为 NPU 适配层通过 [override 机制](../../torchtitan_npu/override/README.md) 接入,不修改上游 `torchtitan`;默认训练路径不受影响,只有在 `override.imports` 中显式列出入口后才会替换组件。
5 7 
@@ -173,7 +175,7 @@ replacement 只支持具体 Config 类型时设置 `exact=True`;需要按层
173 175 
174```bash176```bash
175python -m torchtitan_npu.train \177python -m torchtitan_npu.train \
176- --module torchtitan_npu.models.deepseek_v4 \178+ --module torchtitan_npu_recipes.models.deepseek_v4 \
177 --config deepseek_v4_debugmodel \179 --config deepseek_v4_debugmodel \
178 --override.imports \180 --override.imports \
179 torchtitan_npu.override.common.rms_norm.asc \181 torchtitan_npu.override.common.rms_norm.asc \
@@ -1,5 +1,7 @@
1# DeepSeek-V3.2 / DeepSeek-V4 MTP1# DeepSeek-V3.2 / DeepSeek-V4 MTP
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3本文介绍 TorchTitan-NPU 中 DeepSeek-V3.2 和 DeepSeek-V4 的 Multi-Token Prediction(MTP)训练特性,内容包括 MTP 原理、代码结构和使能方式。5本文介绍 TorchTitan-NPU 中 DeepSeek-V3.2 和 DeepSeek-V4 的 Multi-Token Prediction(MTP)训练特性,内容包括 MTP 原理、代码结构和使能方式。
4 6 
5## 1. MTP 原理7## 1. MTP 原理
@@ -52,22 +54,18 @@ MTP block 复用 DeepSeek-V3.2 的 DSA attention 配置,但拥有独立参数
52 54 
53### 1.3 DeepSeek-V4 MTP55### 1.3 DeepSeek-V4 MTP
54 56 
55-DeepSeek-V4 主干使用 mHC,多流 hidden state 的形状为 `[tokens, hc_mult, hidden]`。MTP 过程中不能先把这些 stream 合并成普通二维 hidden,否则会丢失 mHC 状态。每个 DeepSeek-V4 MTP block 执行:57+DeepSeek-V4 主干使用 mHC,多流 hidden state 的形状为 `[batch, sequence, hc_mult, hidden]`。MTP 过程中不能先把这些 stream 合并成普通三维 hidden,否则会丢失 mHC 状态。每个 DeepSeek-V4 MTP block 执行:
56 58 
571. 分别投影未来 token embedding 和上一深度的多流 hidden state;591. 分别投影未来 token embedding 和上一深度的多流 hidden state;
582. 将 token embedding 投影广播到每个 mHC stream;602. 将 token embedding 投影广播到每个 mHC stream;
593. 通过 `HcPre -> Attention -> HcPost` 更新 attention 分支;613. 通过 `HcPre -> Attention -> HcPost` 更新 attention 分支;
604. 通过 `HcPre -> FFN/MoE -> HcPost` 更新 FFN 分支;624. 通过 `HcPre -> FFN/MoE -> HcPost` 更新 FFN 分支;
61-5. 使用当前深度独立的 `HcHead` 生成二维 prediction hidden;63+5. 使用当前深度独立的 `HcHead` 生成三维 prediction hidden;
62-6. 二维 prediction hidden 进入共享 LM head,多流 hidden state 则继续传给下一64+6. 三维 prediction hidden 进入共享 LM head,多流 hidden state 则继续传给下一
63 个 MTP 深度。65 个 MTP 深度。
64 66 
65DeepSeek-V4 MTP 保留 mHC 多流状态,但其 attention 使用非压缩形式,不启用主干 DSA 的 compressor 和 indexer。67DeepSeek-V4 MTP 保留 mHC 多流状态,但其 attention 使用非压缩形式,不启用主干 DSA 的 compressor 和 indexer。
66 68 
67-NPU 主干 block 保留原有适配;MTP block 直接使用上游 `MTPBlock`,复用其 mask、融合投影、mHC 更新及预测归一化。配置仍构建当前 NPU attention、MoE 和 mHC 组件;decoder 在调用 block 时选择对应的 metadata 并传入 positions。`DeepSeekV4Model` 直接继承 `Decoder`,在 `model.py` 中持有 `mtp_layers` 并通过 `mtp_forward` 执行辅助深度;MTP batch 构造、chunked loss 与梯度隔离辅助逻辑位于 V4 的 `mtp.py`。
68- 
69-当前固定上游提交 `ebdfc8c` 已包含 V3 的多输出 chunked loss 支持。V4 沿用本仓的 MTP loss 封装,以接入 CP 预切分 labels 和共享 LM head 的梯度隔离。
70- 
71### 1.4 DeepSeek-V4 Context Parallel69### 1.4 DeepSeek-V4 Context Parallel
72 70 
73MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移动会在 rank 边界读到不属于本 rank 的 token。V4 的 CP 布局由切分施加(`--parallelism.context-parallel-load-balancer doc_chunk`,见[Context Parallel](context_parallel.md)),实现因此保持在 `cp_shard` 之前对完整序列统一生成:71MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移动会在 rank 边界读到不属于本 rank 的 token。V4 的 CP 布局由切分施加(`--parallelism.context-parallel-load-balancer doc_chunk`,见[Context Parallel](context_parallel.md)),实现因此保持在 `cp_shard` 之前对完整序列统一生成:
@@ -76,15 +74,17 @@ MTP 的 future-token shift 不能在 CP rank-local 序列上执行:局部移
76- packed sequence 感知的有效位置 mask;74- packed sequence 感知的有效位置 mask;
77- 每个 MTP 深度的监督 label。75- 每个 MTP 深度的监督 label。
78 76 
79-`model.py` 的 `DeepSeekV4Model.preprocess_inputs` 在 MTP 启用时先准备全局 MTP batch,并应用输入的 padding mask。主输入、labels 和 positions 走原有 decoder 预处理,MTP batch 随后用相同的 `doc_chunk` 布局和全局 positions 单独切分。前向按深度取本地 token 和 mask,chunked loss 读取对应的本地辅助 labels。关闭 CP 时,模型直接使用准备好的全局 MTP batch。77+这些张量在 `preprocess_inputs` 中先于基座切分、在全局行上构建;随后 `super().preprocess_inputs()` 完成 `inputs`/`labels`/`positions` 的切分,MTP 三个张量再用**同一把连续切片**单独 `cp_shard`(本地切片,无通信),保证 token、label 和 mask 与 `inputs` 在每个 rank 上严格同位。
80 78 
81-该流程只接入 DeepSeek-V4,继续复用已有 metadata 和 CP plan。DeepSeek-V3.2 保留社区 MTP 的 CP 限制。本仓 CP 实现仍要求 fused attention;CPU 输入处理检查不能替代真实 NPU CP 训练验证。79+该流程只接入 DeepSeek-V4:继续复用已有压缩 metadata 和 CP plan 构造;MTP 张量的切分是独立的一次 `cp_shard` 调用,与 `inputs`/`labels`/`positions` 的切分使用同一把连续切片。DeepSeek-V3 和 DeepSeek-V3.2 保留社区 MTP 的原有限制,`context_parallel_degree > 1` 时在配置更新阶段报错;DeepSeek-V3.2 的 varlen attention 本身也不支持 CP,DeepSeek-V3 已有的非 MTP CP 路径不变。
80+ 
81+该处理与 Megatron-LM MTP 在 CP 边界交换 future token/label 的数学目标一致;区别是 TorchTitan 的模型 metadata hook 位于 CP 切分之前,因此可直接在全局序列上生成,再按和输入相同的连续切法单独切分,无需额外点对点通信。
82 82 
83### 1.5 Chunked loss83### 1.5 Chunked loss
84 84 
85-DeepSeek-V4 在启用 MTP 的 recipe 中使用 `MTPChunkedLossWrapper`。它继承并逐预测分支调用 TorchTitan 原生 `ChunkedLossWrapper`,因此复用其 sequence chunk、LM head FSDP、梯度累加和 decoder backward bridge。主分支权重为 `1`,每个 MTP 分支权重为 `mtp_scale / K`。85+DeepSeek-V4 的默认 recipe 使用 `MTPChunkedLossWrapper`。它继承并逐预测分支调用 TorchTitan 原生 `ChunkedLossWrapper`,因此复用其 sequence chunk、LM head FSDP、梯度累加和 decoder backward bridge。主分支权重为 `1`,每个 MTP 分支权重为 `mtp_scale / K`。
86 86 
87-分支权重在分块 loss 内部、内部 `backward()` 之前应用,而不是在最终标量上事后相乘。这样 LM head 和 decoder hidden gradient 都与未分块 MTP loss 保持相同缩放,同时避免构造完整 `[tokens, vocab]` logits。87+分支权重在分块 loss 内部、内部 `backward()` 之前应用,而不是在最终标量上事后相乘。这样 LM head 和 decoder hidden gradient 都与未分块 MTP loss 保持相同缩放,同时避免构造完整 `[batch, sequence, vocab]` logits。
88 88 
89DeepSeek-V3.2 不适配 chunk loss,直接复用社区 `list[logits] + MTPLoss` 训练路径。89DeepSeek-V3.2 不适配 chunk loss,直接复用社区 `list[logits] + MTPLoss` 训练路径。
90 90 
@@ -115,11 +115,11 @@ TorchTitan-NPU 只补充社区当前尚未提供的组合能力:
115 115 
116| 对象 | 职责 |116| 对象 | 职责 |
117|---|---|117|---|---|
118-| `prepare_mtp_batch` | 在 CP 切分前准备各深度 token、mask 和 label |118+| `prepare_mtp_batch` | 为 DeepSeek-V4 在 CP 之前生成各深度 token、mask 和 label |
119| `MTPChunkedLossWrapper` | 为 DeepSeek-V4 将原生 chunked loss 扩展到主预测和各 MTP 预测 |119| `MTPChunkedLossWrapper` | 为 DeepSeek-V4 将原生 chunked loss 扩展到主预测和各 MTP 预测 |
120| `SharedLinear` | MTP 投影期间使用 detached 权重,保留输入梯度及原模块的 FSDP 调用路径 |120| `SharedLinear` | MTP 投影期间使用 detached 权重,保留输入梯度及原模块的 FSDP 调用路径 |
121 121 
122-DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造和并行入口。DeepSeek-V4 直接使用社区 `MTPBlock` 和 `roll_mtp_sequence`,由 `DeepSeekV4Model(Decoder)` 统一管理主干和 MTP,不再定义独立 MTP decoder 或 block 子类。本仓补充 CP、chunked loss 和梯度隔离所需的输入与梯度处理;没有修改社区 `MTPDecoder` 或 `MTPLoss`。122+DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造和并行入口。DeepSeek-V4 复用 `roll_mtp_sequence` 和社区多预测列表接口,只实现 mHC 多流状态、CP 和 chunk loss 所需的专用 decoder 与 block。只有 DeepSeek-V4 的专用 decoder 配置放开 MTP 与 CP 的组合;没有修改社区 `MTPDecoder` 或 `MTPLoss`。
123 123 
124### 2.2 DeepSeek-V3.2 目录124### 2.2 DeepSeek-V3.2 目录
125 125 
@@ -136,9 +136,9 @@ DeepSeek-V3.2 直接继承社区 MTP decoder,并复用社区的 block 构造
136| 文件 | MTP 相关职责 |136| 文件 | MTP 相关职责 |
137|---|---|137|---|---|
138| `deepseek_v4/__init__.py` | 根据模型规格构造非压缩、mHC-aware 的 MTP blocks |138| `deepseek_v4/__init__.py` | 根据模型规格构造非压缩、mHC-aware 的 MTP blocks |
139-| `deepseek_v4/model.py` | 保留原主干适配,管理 MTP 前向与 CP 预处理 |139+| `deepseek_v4/model.py` | 保留主干多流 state,并组织主预测和 MTP 预测 |
140-| `deepseek_v4/mtp.py` | 构造全局 MTP batch,适配多分支 chunked loss 与梯度隔离 |140+| `deepseek_v4/mtp.py` | 实现 DeepSeek-V4 mHC MTP block、CP batch 和 chunk loss |
141-| `deepseek_v4/config_registry.py` | 根据 `num_mtp_layers` 配置模型和对应的 chunked loss |141+| `deepseek_v4/config_registry.py` | 默认 recipe 构造 MTP 模型并配置 MTP chunk loss |
142| `deepseek_v4/parallelize.py` | 让 MTP blocks 复用现有 DSV4 并行流程 |142| `deepseek_v4/parallelize.py` | 让 MTP blocks 复用现有 DSV4 并行流程 |
143| `deepseek_v4/sharding.py` | 增加 MTP fusion、mHC head 和有效掩码布局 |143| `deepseek_v4/sharding.py` | 增加 MTP fusion、mHC head 和有效掩码布局 |
144| `deepseek_v4/state_dict_adapter.py` | 转换本地 `mtp_layers` 与 HF `mtp.<depth>` 参数 |144| `deepseek_v4/state_dict_adapter.py` | 转换本地 `mtp_layers` 与 HF `mtp.<depth>` 参数 |
@@ -161,20 +161,16 @@ Pipeline Parallel(PP),启用时必须保持 `context_parallel_degree=1`
161 161 
162## 3. 使能方式162## 3. 使能方式
163 163 
164-### 3.1 启用 DeepSeek-V4 MTP164+### 3.1 默认 recipe
165 165 
166-DeepSeek-V4 普通 recipe 的 `num_mtp_layers` 默认是 `0`。在自定义 recipe 中显式启用一层 MTP:166+DeepSeek-V4 的默认 recipe 已经启用 MTP,不需要额外提供只转调默认配置的 `deepseek_v4_debugmodel_mtp`
167 167 
168-```python168+```text
169-from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_debugmodel169+DeepSeek-V4:
170- 170+ --module torchtitan_npu_recipes.models.deepseek_v4
171- 171+ --config deepseek_v4_debugmodel
172-def deepseek_v4_mtp():
173- return deepseek_v4_debugmodel(num_mtp_layers=1)
174```172```
175 173 
176-已有集成测试 `tests.integration_tests.mtp_config.deepseek_v4_debugmodel_mtp` 使用相同入口。GraphTrainer recipes 仍关闭 MTP。
177- 
178该 recipe 会构造一个 MTP 深度,并使用 `MTPChunkedLossWrapper.Config`;其内部仍使用标准 `CrossEntropyLoss`。DeepSeek-V3.2 不在 NPU `config_registry.py` 中重复声明 MTP recipe,模型侧直接复用社区 MTP 能力。174该 recipe 会构造一个 MTP 深度,并使用 `MTPChunkedLossWrapper.Config`;其内部仍使用标准 `CrossEntropyLoss`。DeepSeek-V3.2 不在 NPU `config_registry.py` 中重复声明 MTP recipe,模型侧直接复用社区 MTP 能力。
179 175 
180模型和 loss 必须同时切换。只构造 MTP layers 而继续使用普通 loss,或者只配置 `MTPLoss` 而没有构造 MTP layers,都会造成模型输出与 loss 输入不匹配。176模型和 loss 必须同时切换。只构造 MTP layers 而继续使用普通 loss,或者只配置 `MTPLoss` 而没有构造 MTP layers,都会造成模型输出与 loss 输入不匹配。
@@ -215,8 +211,8 @@ config.loss = MTPChunkedLossWrapper.Config(
215| `num_chunks` | DeepSeek-V4 每个主/MTP hidden sequence 的 loss 分块数 |211| `num_chunks` | DeepSeek-V4 每个主/MTP hidden sequence 的 loss 分块数 |
216| `mtp_layers` | 模型内部展开后的 MTP block 配置列表,通常不手工构造 |212| `mtp_layers` | 模型内部展开后的 MTP block 配置列表,通常不手工构造 |
217 213 
218-DeepSeek-V4 MTP chunked loss 默认使用 `mtp_scale=0.3`。214+DeepSeek-V4 默认 recipe 使用 `mtp_scale=0.3`。
219 215 
220### 3.3 关闭 MTP216### 3.3 关闭 MTP
221 217 
222-DeepSeek-V4 使用 `num_mtp_layers=0` 并配合普通 loss 关闭 MTP。此时 `config.mtp_layers` 为空列表,运行时 `model.mtp_layers` 为空的 TorchTitan `ModuleList`,不创建 MTP 参数,训练只计算主预测 loss。V3.2 的关闭参数仍为 `num_mtp_layers=0`。218+关闭 MTP 时需要让模型构造保持 `num_mtp_layers=0`,并使用普通 loss。此时 `config.mtp_layers` 为空列表,运行时 `model.mtp_layers is None`;模型不创建 MTP 参数,训练只计算主 MTP loss。
@@ -1,5 +1,7 @@
1# DeepSeek-V4 Muon 优化器1# DeepSeek-V4 Muon 优化器
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3本文说明当前实现中的 Muon 方案、使用方法和能力边界。实现以 TorchTitan 上游5本文说明当前实现中的 Muon 方案、使用方法和能力边界。实现以 TorchTitan 上游
4`DistMuon`/FlexShard 为核心;上游的 `ComputeLayout`、`Owned`、`BlockShard`、bucket6`DistMuon`/FlexShard 为核心;上游的 `ComputeLayout`、`Owned`、`BlockShard`、bucket
5和 storage-to-compute 语义参见 [TorchTitan FlexShard README](https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/flex_shard/README.md)。7和 storage-to-compute 语义参见 [TorchTitan FlexShard README](https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/flex_shard/README.md)。
@@ -7,7 +9,7 @@
7## 当前方案9## 当前方案
8 10 
9DSV4 使用混合优化器容器:匹配 Muon 规则的二维矩阵参数交给 `DistMuon`,其余参数交给11DSV4 使用混合优化器容器:匹配 Muon 规则的二维矩阵参数交给 `DistMuon`,其余参数交给
10-AdamW。`torchtitan_npu/models/deepseek_v4/config_registry.py` 中的12+AdamW。`torchtitan_npu/models/deepseek_v4/muon.py` 中的
11`_dsv4_optimizer_config()` 提供常规 DSV4 optimizer schema;13`_dsv4_optimizer_config()` 提供常规 DSV4 optimizer schema;
12`_dsv4_muon_profile()` 提供参数匹配、FlexShard compute layout 和 bucket 元数据。14`_dsv4_muon_profile()` 提供参数匹配、FlexShard compute layout 和 bucket 元数据。
13`--optimizer.name Muon` 才 materialize 出 DistMuon 与 AdamW fallback 两组。15`--optimizer.name Muon` 才 materialize 出 DistMuon 与 AdamW fallback 两组。
@@ -36,7 +38,7 @@ Muon 与 AdamW fallback 当前共用 `--optimizer.lr`,没有独立 `muon_lr`
368 卡的直接启动命令;swap override 也是显式列出,而非 recipe 隐式启用:388 卡的直接启动命令;swap override 也是显式列出,而非 recipe 隐式启用:
37 39 
38```bash40```bash
39-MODULE=torchtitan_npu.models.deepseek_v4 \41+MODULE=torchtitan_npu_recipes.models.deepseek_v4 \
40CONFIG=deepseek_v4_flash_43layers_16experts \42CONFIG=deepseek_v4_flash_43layers_16experts \
41NGPU=8 \43NGPU=8 \
42bash scripts/run_train.sh \44bash scripts/run_train.sh \
@@ -61,7 +63,6 @@ bash scripts/run_train.sh \
61 --optimizer.muon_enable_nesterov \63 --optimizer.muon_enable_nesterov \
62 --optimizer.muon_ns_steps 10 \64 --optimizer.muon_ns_steps 10 \
63 --optimizer.muon_adjust_lr_fn match_rms_adamw \65 --optimizer.muon_adjust_lr_fn match_rms_adamw \
64- --debug.no-moe-force-load-balance \
65 --checkpoint.no-enable \66 --checkpoint.no-enable \
66 --override.imports \67 --override.imports \
67 torchtitan_npu.override.common.rms_norm.asc \68 torchtitan_npu.override.common.rms_norm.asc \
@@ -131,7 +132,6 @@ FlexShard bucket 调度:
131`unredistributed_items` 不进入 storage-to-compute A2A。它们在 caller stream 上执行132`unredistributed_items` 不进入 storage-to-compute A2A。它们在 caller stream 上执行
132`_prepare_local()`、Muon 计算和参数更新,随后沿现有单 tensor 路径提交 D2H。133`_prepare_local()`、Muon 计算和参数更新,随后沿现有单 tensor 路径提交 D2H。
133 134 
134- 
135AdamW 的 `exp_avg`、`exp_avg_sq`(AMSGrad 时还包括 `max_exp_avg_sq`)按 bucket 拼成连续135AdamW 的 `exp_avg`、`exp_avg_sq`(AMSGrad 时还包括 `max_exp_avg_sq`)按 bucket 拼成连续
136flat state。每个 bucket 执行 H2D、`WAIT_DEVICE`、上游 AdamW 更新和 D2H,并在当前 bucket136flat state。每个 bucket 执行 H2D、`WAIT_DEVICE`、上游 AdamW 更新和 D2H,并在当前 bucket
137更新前提交下一个 bucket 的 H2D。137更新前提交下一个 bucket 的 H2D。
@@ -139,7 +139,6 @@ flat state。每个 bucket 执行 H2D、`WAIT_DEVICE`、上游 AdamW 更新和 D
139开启 swap 之后,checkpoint 的存储和加载支持同步模式和基于 CPU snapshot 的异步模式 `async`,暂不支持139开启 swap 之后,checkpoint 的存储和加载支持同步模式和基于 CPU snapshot 的异步模式 `async`,暂不支持
140`async_with_pinned_mem`。140`async_with_pinned_mem`。
141 141 
142- 
143## 能力边界142## 能力边界
144 143 
145当前方案适合 DSV4 单机 8 卡、TP/PP=1、EP/DP-shard 并行的实验和训练。尚未证明:144当前方案适合 DSV4 单机 8 卡、TP/PP=1、EP/DP-shard 并行的实验和训练。尚未证明:
@@ -1,5 +1,7 @@
1# 静默数据损坏检测(SDC)1# 静默数据损坏检测(SDC)
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3SDC(Silent Data Corruption,静默数据损坏)用于检测 Ascend NPU 训练中的 gradient、HCCL 和 matmul checksum 异常,5SDC(Silent Data Corruption,静默数据损坏)用于检测 Ascend NPU 训练中的 gradient、HCCL 和 matmul checksum 异常,
4仅支持 Eager 模式或使用 `torch.compile(backend="inductor")` 的 Compile 模式。该能力默认关闭,按需启用。6仅支持 Eager 模式或使用 `torch.compile(backend="inductor")` 的 Compile 模式。该能力默认关闭,按需启用。
5Eager 模式通过 torch-npu 原生环境变量启用,Compile 模式通过 `--sdc.*` CLI 参数启用。7Eager 模式通过 torch-npu 原生环境变量启用,Compile 模式通过 `--sdc.*` CLI 参数启用。
@@ -25,7 +27,7 @@ Eager 模式由 torch-npu 原生控制:
25```bash27```bash
26NPU_ASD_CONFIG='enable:true,with_checksum:false' \28NPU_ASD_CONFIG='enable:true,with_checksum:false' \
27torchrun --nproc_per_node=8 -m torchtitan_npu.train \29torchrun --nproc_per_node=8 -m torchtitan_npu.train \
28- --module torchtitan_npu.models.deepseek_v4 \30+ --module torchtitan_npu_recipes.models.deepseek_v4 \
29 --config deepseek_v4_flash_43layers_16experts31 --config deepseek_v4_flash_43layers_16experts
30```32```
31 33 
@@ -41,7 +43,7 @@ compiled gradient、checksum 或 typed HCCL 控制。
41 43 
42```bash44```bash
43torchrun --nproc_per_node=8 -m torchtitan_npu.train \45torchrun --nproc_per_node=8 -m torchtitan_npu.train \
44- --module torchtitan_npu.models.deepseek_v4 \46+ --module torchtitan_npu_recipes.models.deepseek_v4 \
45 --config deepseek_v4_flash_43layers_16experts \47 --config deepseek_v4_flash_43layers_16experts \
46 --sdc.gradient-enabled \48 --sdc.gradient-enabled \
47 --sdc.with-checksum \49 --sdc.with-checksum \
@@ -1,5 +1,7 @@
1# Virtual Optimizer - 优化器显存虚拟化特性1# Virtual Optimizer - 优化器显存虚拟化特性
2 2 
3+> **0.4.0 配置迁移说明:** 下文保留历史实现说明与字段 CLI 示例,不能直接作为当前启动命令。训练工厂已迁至 `torchtitan_npu_recipes`;当前启动方式见[快速上手](../user-guides/quickstart.md),专用配置与 golden 应按 [Python 配置组合指南](../developer_guides/python_recipes.md)定义工厂。功能支持以 0.4.0 升级计划为准。
4+ 
3## 背景与挑战5## 背景与挑战
4 6 
5在大规模分布式训练中,模型参数、梯度和优化器状态都会占用大量 NPU 显存。对于 Adam/AdamW,`exp_avg` 和 `exp_avg_sq` 两组 moments 通常与模型参数规模相当,并且在前向和反向计算期间仍会长期驻留在显存中。7在大规模分布式训练中,模型参数、梯度和优化器状态都会占用大量 NPU 显存。对于 Adam/AdamW,`exp_avg` 和 `exp_avg_sq` 两组 moments 通常与模型参数规模相当,并且在前向和反向计算期间仍会长期驻留在显存中。
@@ -57,7 +59,7 @@ Virtual Optimizer 与 `torchtitan_npu.override.common.optimizer.swap_optimizer`
57 59 
58```bash60```bash
59python -m torchtitan_npu.train \61python -m torchtitan_npu.train \
60- --module torchtitan_npu.models.deepseek_v4 \62+ --module torchtitan_npu_recipes.models.deepseek_v4 \
61 --config deepseek_v4_debugmodel \63 --config deepseek_v4_debugmodel \
62 --override.imports torchtitan_npu.override.common.optimizer.virtual \64 --override.imports torchtitan_npu.override.common.optimizer.virtual \
63 --checkpoint.enable \65 --checkpoint.enable \
@@ -8,11 +8,16 @@ 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+| dev_0.4.0 | v0.4.0 | 2.15.0+cpu | 2.15.0.dev20261105 | 9.3.0 | Python 3.12.x | 3.2.1 |
12 12 
13> [!NOTE]13> [!NOTE]
14> 安装所需的 Python 包依赖及版本见 [requirements.txt](../../requirements.txt)14> 安装所需的 Python 包依赖及版本见 [requirements.txt](../../requirements.txt)
15 15 
16+A3 使用 [2026-11-04 CANN 包](https://ascend.devcloud.huaweicloud.com/artifactory/cann-run-mirror/software/legacy/20261104000324968/)中的 Toolkit 和 A3 算子包:
17+ 
18+- `Ascend-cann-toolkit_9.3.0~weekly.20261104.01_linux-aarch64.run`
19+- `Ascend-cann-A3-ops_9.3.0~weekly.20261104.01_linux-aarch64.run`
20+ 
16## 源码安装21## 源码安装
17 22 
18### 1. 安装依赖的软件23### 1. 安装依赖的软件
@@ -61,17 +66,39 @@ torchtitan-npu 支持 Atlas 800T A3 等昇腾训练硬件。软件版本配套
61 66 
62 ```shell67 ```shell
63git clone https://gitcode.com/cann/torchtitan-npu.git68git clone https://gitcode.com/cann/torchtitan-npu.git
69+cd torchtitan-npu
64 ```70 ```
65 71 
66-### 3. 安装 torchtitan-npu72+### 3. 下载 PyTorch 和 torch-npu daily 包
73+ 
74+在 Python 3.12 环境中使用 [2026-11-05.3 daily 包](https://pytorch-package.obs.cn-north-4.myhuaweicloud.com/pta/Daily/master/20261105.3/pytorch_master_py312.tar.gz)。归档包含 aarch64 和 x86_64 wheel,pip 会选择与当前平台匹配的文件。
67 75 
68```shell76```shell
69-cd torchtitan-npu77+TORCH_PACKAGE_DIR=/path/to/pytorch-20261105.3
70-python3 -m pip install -r requirements.txt78+mkdir -p "$TORCH_PACKAGE_DIR"
71-python3 -m pip install -e .79+curl -fL --retry 3 \
80+ https://pytorch-package.obs.cn-north-4.myhuaweicloud.com/pta/Daily/master/20261105.3/pytorch_master_py312.tar.gz \
81+ -o "$TORCH_PACKAGE_DIR/pytorch_master_py312.tar.gz"
82+tar -xzf "$TORCH_PACKAGE_DIR/pytorch_master_py312.tar.gz" \
83+ -C "$TORCH_PACKAGE_DIR" --wildcards '*.whl' '*.whl.sha256'
72```84```
73 85 
74-### 4. 安装 torchao-npu(可选)86+加载已安装的 CANN 环境,并将路径传给训练 launcher:
87+ 
88+```shell
89+export ASCEND_SET_ENV_PATH=/path/to/cann/1104/cann/set_env.sh
90+source "$ASCEND_SET_ENV_PATH"
91+```
92+ 
93+### 4. 安装 torchtitan-npu
94+ 
95+```shell
96+python -m pip install --find-links "$TORCH_PACKAGE_DIR" -r requirements.txt
97+python -m pip install --find-links "$TORCH_PACKAGE_DIR" -e .
98+python -m pip check
99+```
100+ 
101+### 5. 安装 torchao-npu(可选)
75 102 
76仓库已在 `experiments/torchao-npu/torchao_npu` 中内置 TorchAO-NPU 适配代码,103仓库已在 `experiments/torchao-npu/torchao_npu` 中内置 TorchAO-NPU 适配代码,
77默认无需单独克隆 `torchao-npu` 仓库。从 torchtitan-npu 仓库根目录执行:104默认无需单独克隆 `torchao-npu` 仓库。从 torchtitan-npu 仓库根目录执行:
@@ -1,177 +1,42 @@
1# 快速上手1# 快速上手
2 2 
3-参考 [软件安装](./installation.md) 准备环境后,进入 `torchtitan-npu` 仓库根目录。除另有说明外,本文中的相对路径和命令均以仓库根目录为基准。本文先以 DeepSeek V3 说明通用启动方式,再给出 DeepSeek-V4/V4.1 多卡训练和 TorchAO-NPU 低精度训练入口。3+本文介绍如何在 TorchTitan 0.4.0 中以 eager 模式启动 DeepSeek 文本训练。先按[安装指南](installation.md)准备匹配的 torch、torch-npu、TorchTitan 与 CANN 环境,再从仓库根目录运行启动脚本。
4 4 
5-## 数据准备5+## 数据和模型资源
6 6 
7-1. 使用仓库预置的 DeepSeek V3 Tokenizer,目录为 `tests/assets/deepseek_v3/`,单卡默认命令会直接使用该目录,无需额外下载。7+基础调试配置使用 `tests/assets/c4_test/data.json` 作为训练数据,将 `hf_assets_path` 设为 `tests/assets/deepseek_v3`,使用该目录中的 tokenizer。正式模型需要准备与模型匹配的 Hugging Face 资源;调试用 tokenizer 的训练结果不能代替正式模型的数值验证。
8 8 
9-```text9+## 单卡 eager
10-tests/assets/deepseek_v3/10+ 
11-├── tokenizer.json11+```bash
12-└── tokenizer_config.json12+bash examples/deepseek_v4/debug/deepseek_v4_eager_1p.sh
13```13```
14 14 
15-如需使用其他 Tokenizer,修改单卡命令中的 `--hf-assets-path`。15+启动脚本调用配置函数 `torchtitan_npu_recipes.examples.deepseek_v4.deepseek_v4_eager_1p`,其中设置了模型、数据、训练步数和算子组合,默认训练 100 步。DeepSeek 示例默认使用 NPU 融合算子,需要参考实现时显式设置 `USE_GOLDEN=1`。在命令末尾加上 `--print-config` 可以只查看配置,不启动训练。
16 16 
17-2. 准备数据集。17+需要缩短试运行步数或更换优化器时,可以编写 Python 配置函数,通过 `MODULE`、`CONFIG` 指定,见[配置组合指南](../developer_guides/python_recipes.md)。
18 18 
19-已在 `tests/assets/c4_test/` 中预置 `c4_test` 测试数据集,单卡命令直接使用该目录,无需额外下载。19+DeepSeek-V4.1 的文本调试配置可以通过以下命令查看:
20 20 
21-使用其他数据集时,需同时修改单卡命令中的 `--dataloader.dataset` 和 `--dataloader.dataset-path`。21+```bash
22+MODULE=torchtitan_npu_recipes.models.deepseek_v4_1 \
23+CONFIG=deepseek_v4_1_debugmodel_text NGPU=1 \
24+ bash scripts/run_train.sh --print-config
25+```
22 26 
23-## 配置 CANN 环境变量27+去掉 `--print-config` 即可启动训练。该配置默认训练 10000 步;需要减少步数时,在自定义配置函数中设置 `config.training.steps`。
24 28 
25-当 CANN 安装在其他目录时,推荐通过 `ASCEND_SET_ENV_PATH` 指定 `set_env.sh` 的路径,并将其传给脚本:29+CANN 的 `set_env.sh` 不在默认位置时,显式指定环境脚本路径:
26 30 
27```bash31```bash
28ASCEND_SET_ENV_PATH=/path/to/ascend-toolkit/set_env.sh \32ASCEND_SET_ENV_PATH=/path/to/ascend-toolkit/set_env.sh \
29- bash scripts/run_train.sh33+ bash examples/deepseek_v4/debug/deepseek_v4_eager_1p.sh
30```34```
31 35 
32-未设置该变量时,`scripts/run_train.sh` 会自动按以下顺序查找可用的 `set_env.sh`:36+环境脚本的默认搜索位置见 [`scripts/run_train.sh`](../../scripts/run_train.sh)。启动脚本负责加载环境和启动训练进程,训练参数在 Python 配置中设置。
33 37 
34-```text38+## 集成和数值验证
35-/usr/local/Ascend/cann/set_env.sh
36-/usr/local/Ascend/ascend-toolkit/set_env.sh
37-/home/developer/Ascend/ascend-toolkit/set_env.sh
38-```
39 39 
40-无需在当前 shell 中重复执行 `source`。40+集成测试入口及用例定义见[集成测试指南](../../tests/integration_tests/README.md)。训练组合的验证状态以实际执行结果为准;按[数值验证要求](../developer_guides/numerical_alignment.md)比较固定 checkpoint 下未截断的 loss 与 grad_norm。
41 41 
42-## 启动训练任务42+旧示例中的通用字段 CLI 不再适用于 0.4.0。图训练、CP、PP、多模态、LoRA 和其他延期能力的历史说明不表示当前依赖组合已完成支持;具体边界见[升级计划](../../.agents/notes/proposed/upstream/2026-11-04-upgrade-torchtitan-v0.4.0-eager-plan.md)。
43- 
44-DeepSeek V3 单卡训练任务可直接使用 `scripts/run_train.sh` 启动。`scripts/run_train.sh` 默认使用 1 张 NPU 和 `deepseek_v3_debugmodel` 配置,并把额外命令行参数原样透传给训练入口。
45- 
46-### 单卡训练任务
47- 
48-使用默认配置启动训练:
49- 
50-```bash
51-NGPU=1 \
52-bash scripts/run_train.sh \
53- --hf-assets-path tests/assets/deepseek_v3 \
54- --dataloader.dataset c4_test \
55- --dataloader.dataset-path tests/assets/c4_test \
56- --training.local-batch-size 1 \
57- --training.seq-len 2048 \
58- --training.steps 5
59-```
60- 
61-> [!NOTE]
62-> 通用 launcher 配置项说明:
63-> - `ASCEND_SET_ENV_PATH`:可选,自定义 CANN `set_env.sh` 路径;设置后优先加载该文件。
64-> - `MODULE`:模型 Python 模块,默认为 `torchtitan.models.deepseek_v3`。
65-> - `CONFIG`:`torchtitan/models/deepseek_v3/config_registry.py` 中注册的配置函数,默认为 `deepseek_v3_debugmodel`。
66-> - `NGPU`:当前节点参与训练的 NPU 数量,默认为 `1`。
67-> - Tokenizer 和数据集由上述命令中的 CLI 参数指定;`scripts/run_train.sh` 不读取 `HF_ASSETS_PATH`、`DATASET` 或 `DATASET_PATH` 环境变量。
68-> - 脚本后的其他参数会原样传给 `torchtitan_npu.train`,可用于覆盖配置函数中的训练和并行参数。
69- 
70- 
71-### 单机 8 卡 EP8 训练任务
72- 
73-直接复用 DeepSeek-V4 单机 8 卡示例脚本。该脚本默认使用 8 卡、EP8/DP8 并行配置和 `deepseek_v4_flash_43layers_16experts` 模型配置。运行前需准备与 DeepSeek-V4 配套的 Tokenizer,并将下面的 `HF_ASSETS_PATH` 替换为其实际目录:
74- 
75-```bash
76-HF_ASSETS_PATH=/path/to/DeepSeekV4_tokenizer \
77-bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \
78- --training.steps 5
79-```
80- 
81-DeepSeek-V4 的 SMLA 融合路径和 TND 数据约定见 [DeepSeek-V4 TND 适配](../feature_guides/deepseek_v4_tnd.md)。
82- 
83-### DeepSeek-V4 TorchAO-NPU 低精度训练
84- 
85-先按[软件安装](./installation.md#4-安装-torchao-npu可选)安装仓内适配包,或将
86-`torchao_npu` 源码的父目录加入 `PYTHONPATH`。随后在普通训练命令后显式增加量化 CLI:
87- 
88-> [!NOTE]
89-> 当前低精度训练仅支持 A5(Ascend 950)硬件。
90- 
91-```bash
92-HF_ASSETS_PATH=/path/to/DeepSeek-V4-Flash \
93-bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \
94- --training.steps 5 \
95- --extension.quantization.enable-quantized-training \
96- --extension.quantization.recipe all_block_fp8
97-```
98- 
99-源码方式示例:
100- 
101-```bash
102-python3 -m pip install torchao==0.17.0
103-export PYTHONPATH="/path/to/custom/parent${PYTHONPATH:+:${PYTHONPATH}}"
104-```
105- 
106-自定义目录必须直接包含 `torchao_npu/__init__.py`;使用仓内源码时,对应目录为
107-`<torchtitan-npu>/experiments/torchao-npu`。单机和多机示例分别调用
108-`scripts/run_train.sh` 和 `scripts/run_train_multinodes.sh`,脚本只透传量化 CLI。
109-未设置
110-`--extension.quantization.enable-quantized-training` 时,仍使用高精度训练。
111- 
112-该入口复用 torchtitan 的预训练/续训练循环,并不表示已经提供 SFT 专用数据处理或训练入口。
113- 
114-启用低精度训练时,每个节点需使用
115-A5(Ascend 950)硬件,安装相同版本的 `torchao_npu` 及其依赖,并执行相同命令;
116-`NODE_IPS` 的顺序决定节点 rank:
117- 
118-```bash
119-NODE_IPS=your_ip1,your_ip2,... \
120-HF_ASSETS_PATH=/path/to/DeepSeekV4_tokenizer \
121-CKPT_SAVE_LOAD_PATH=/path/to/save_ckpt \
122-CKPT_INIT_LOAD_PATH=/path/to/init_load_ckpt \
123-bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
124- --extension.quantization.enable-quantized-training \
125- --extension.quantization.recipe all_block_fp8 \
126- --training.steps 5
127-```
128- 
129-常用低精度配置如下,均位于 `--extension.quantization` 下;表中参数和布尔开关省略该公共前缀:
130- 
131-| 参数 | 选项 | 用途 |
132-| --- | --- | --- |
133-| `enable-quantized-training` | `--enable-quantized-training` / `--no-enable-quantized-training` | 启用或关闭低精度训练,默认关闭。 |
134-| `recipe` | `all_mxfp8`、`mix`、`all_block_fp8`、`all_hif8` | 选择全 MXFP8、混合 MXFP8/Block FP8、全 Block FP8 或全 HiF8。 |
135-| `enable-mxfp4-qat` | `--enable-mxfp4-qat` / `--no-enable-mxfp4-qat` | 为 routed expert 启用或关闭 MXFP4 QAT 约束,默认关闭。 |
136-| `li-quantization` | `fp8`、`mxfp8`、`mxfp4`、`hif8` | 选择 LI Q/K 的量化类型,默认不启用;DeepSeek-V4.1 仅支持 `mxfp4`。 |
137-| `kv-norm-quantization.format` | `mxfp8` | 启用 DeepSeek-V4 KV Cache 的 MXFP8 量化。 |
138-| `enable-fsdp-prequantize` | `--enable-fsdp-prequantize` / `--no-enable-fsdp-prequantize` | 在 FSDP all-gather 前预量化 Block FP8 权重,减少通信量,默认关闭。 |
139-| `fsdp-prequantize-fqns` | FQN 后缀模式列表(默认 `None`) | 仅在 `enable-fsdp-prequantize` 下生效。白名单内的权重保留预量化、其余显式关闭;`None` 用 recipe 默认白名单,显式空表与开关开启冲突会报 `ValueError`。多个模式写在同一参数内并以英文逗号分隔(如 `.attention.wq_b,.attention.wo_a`)。命中权重的分片若不满足对齐约束,运行时立即报错终止(不静默回退),并给出移除该 FQN 或调整并行度的提示。 |
140-| `enable-hif8-save-quant-codes` | `--enable-hif8-save-quant-codes` / `--no-enable-hif8-save-quant-codes` | 把 HiF8 量化矩乘算子(`npu_quantize`/`npu_dynamic_quant`/`npu_grouped_matmul`/`npu_quant_matmul`)结果保留在 selective activation checkpointing 保存边界内,backward 不再重新推导;仅在 `recipe=all_hif8` 时生效,默认关闭。 |
141-| `save-block-ops-level` | `0`-`3`(默认 `0`) | 把 attention / mHC / MoE-routing 相关 NPU 自定义算子加入 selective activation checkpointing 的 MUST_SAVE 列表,用显存换取 backward 更少重复计算。 |
142- 
143-### DeepSeek-V4.1 TorchAO-NPU 低精度训练
144- 
145-DeepSeek-V4.1 复用上述 TorchAO-NPU 低精度入口,当前面向 A5(Ascend 950)硬件。Lightning Indexer 与稀疏 attention 量化的配置、组合、依赖和限制见[低精度训练特性指南](../feature_guides/low_precision_training.md#deepseek-v41-li-与稀疏-attention-量化)。
146- 
147-DeepSeek-V4.1 使用 `li-quantization=mxfp4` 启用 Lightning Indexer 量化,使用
148-`enable-sparse-attention-quantization` 启用 KV source Compressor 与稀疏 attention 量化。
149-稀疏 attention 量化可单独启用;启用 Lightning Indexer 量化时必须同时启用稀疏 attention
150-量化。标准 A5 融合路径提供 BF16 fallback,`USE_GOLDEN=1` 不提供这些 fallback。启动日志中出现
151-`Applied TorchAO-NPU recipe=...` 表示 recipe 已应用。
152- 
153-DeepSeek-V4.1 模型做 Block FP8 低精度预训练可运行以下脚本:
154- 
155-```bash
156-HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \
157-bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a5.sh
158-```
159- 
160-DeepSeek-V4.1 模型做 QAT 训练可运行以下脚本。该入口同时启用 routed expert MXFP4
161-fake quant、Lightning Indexer 和稀疏 attention/KV source Compressor 量化:
162- 
163-```bash
164-HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \
165-bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_qat_4k_a5.sh
166-```
167- 
168-### 排查启动报错:查看更多 rank 日志
169- 
170-> [!TIP]
171-> `scripts/run_train.sh` 默认只在控制台打印 `LOG_RANK=0`,即 rank 0 的日志。多卡任务异常退出但控制台没有具体 Python 报错时,可指定需要打印的 rank 后重新运行:
172->
173-> ```bash
174-> export LOG_RANK=0,1,2,3
175-> ```
176->
177-> 排查完成后,可执行 `unset LOG_RANK` 恢复默认设置。
@@ -1,8 +1,9 @@
1# examples 规则1# examples 规则
2 2 
3-`examples/` 放置面向用户的 recipe launcher、参数组合和小规模 debug 入口。3+`examples/` 放置面向用户的 recipe launcher 和小规模 debug 入口。
4 4 
5-- launcher 只组合已实现的 module、config 和 `override.imports`,不承载可复用生产逻辑。5+- 每个训练 launcher 选择 `torchtitan_npu_recipes.examples.<model>` 中与脚本同名的完整 Python 工厂。数据、训练预算、优化器、并行、checkpoint、profiling、量化和 `override.imports` 均归 Python 工厂,不在 shell 拼接字段参数。
6+- shell 只保留设备、节点、CANN、网络等启动资源与一条共用 launcher 调用,允许通过 `MODULE` / `CONFIG` 选择自定义工厂。
6- 保留用户传入的额外 CLI 参数;不在 wrapper 中隐式改变 checkpoint、数值或并行语义。7- 保留用户传入的额外 CLI 参数;不在 wrapper 中隐式改变 checkpoint、数值或并行语义。
7- 每个示例的模型、硬件代际、进程数、可选依赖和默认 override 必须可从脚本和相关文档中确认。8- 每个示例的模型、硬件代际、进程数、可选依赖和默认 override 必须可从脚本和相关文档中确认。
8- `debug/` 只表示小规模调试配置,不代表数值或性能已验收。9- `debug/` 只表示小规模调试配置,不代表数值或性能已验收。
@@ -0,0 +1,12 @@
1+#!/usr/bin/env bash
2+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved.
3+#
4+# This source code is licensed under the BSD-style license found in the
5+# LICENSE file in the root directory of this source tree.
6+ 
7+set -euo pipefail
8+ 
9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
10+CONFIG="${CONFIG:-deepseek_v4_eager_1p}" \
11+NGPU="${NGPU:-1}" \
12+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
@@ -4,146 +4,9 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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 a single node.
8-# Append CLI arguments to override the defaults below:
9-# ./examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh --training.steps 5
10-# USE_GOLDEN=1 selects the reference combination (the model's default attention).
11-# For deterministic execution, append
12-# --debug.seed 42 --debug.deterministic to the command line.
13- 
14set -euo pipefail7set -euo pipefail
15 8 
16-NGPU="${NGPU:-8}"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
17-WORLD_SIZE="${NGPU}"10+CONFIG="${CONFIG:-deepseek_v4_flash_8p_cpt_4k_a3_eager}" \
18- 11+NGPU="${NGPU:-8}" \
19-# Model12+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
20-MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
21-CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts_compiled}"
22- 
23-# Dataloader
24-# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe.
25-HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
26- 
27-# Parallelism
28-TP=1
29-PP=1
30-EP=8
31-CP="${CP:-1}"
32-DP_SHARD=8
33-DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
34- 
35-# Training
36-SEQ_LEN=4096
37-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096
38-NUM_TOKENS_PER_TRAIN_STEP=262144
39-STEPS=100
40- 
41-# Debug
42-USE_GOLDEN="${USE_GOLDEN:-0}"
43-DEBUG_ARGS="
44- --debug.no-moe-force-load-balance
45- --debug.print-config
46-"
47- 
48-# HF assets
49-HF_ASSETS_ARGS="
50- --hf-assets-path ${HF_ASSETS_PATH}
51-"
52- 
53-# Parallelism
54-PARALLELISM_ARGS="
55- --parallelism.data-parallel-shard-degree ${DP_SHARD}
56- --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
57- --parallelism.expert-parallel-degree ${EP}
58- --parallelism.tensor-parallel-degree ${TP}
59- --parallelism.context-parallel-degree ${CP}
60- --parallelism.pipeline-parallel-degree ${PP}
61-"
62- 
63-# Compilation policy is declared by the selected Python recipe.
64- 
65-# Training
66-TRAINING_ARGS="
67- --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}
68- --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP}
69- --training.max-context-length ${SEQ_LEN}
70- --training.steps ${STEPS}
71- --training.disable-cuda-graphs
72-"
73- 
74-# Checkpoint policy is declared by the selected Python recipe.
75-CHECKPOINT_ARGS=""
76- 
77-# Profiler
78-PROFILER_ARGS="
79- --profiler.no-enable-profiling
80- --profiler.save-traces-folder profiling_path
81- --profiler.extension.no-enable-online-parse
82- --profiler.extension.profiler-start 6
83- --profiler.extension.profiler-end 7
84- --profiler.extension.profile-ranks 0
85-"
86- 
87-# Communication
88-COMM_ARGS="
89- --comm.init-timeout-seconds 7200
90- --comm.train-timeout-seconds 600
91-"
92- 
93-# Optimizer
94-OPTIMIZER_ARGS="
95- --optim.optimizer.name Muon
96- --optim.optimizer.lr 1.0e-5
97- --optim.optimizer.beta1 0.9
98- --optim.optimizer.beta2 0.95
99- --optim.optimizer.eps 1.0e-8
100- --optim.optimizer.weight_decay 1.0e-1
101- --optim.optimizer.muon_momentum 0.95
102- --optim.optimizer.muon_enable_nesterov
103- --optim.optimizer.muon_ns_steps 10
104- --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
105-"
106-OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
107- 
108-if [[ "${USE_GOLDEN}" == "1" ]]; then
109- DEFAULT_CLI_OVERRIDES=""
110- NPU_OPS_OVERRIDES=(
111- torchtitan_npu.override.common.rope.workaround
112- )
113-else
114- DEFAULT_CLI_OVERRIDES="torchtitan_npu.override.common.rope.asc_complex"
115- NPU_OPS_OVERRIDES=(
116- # Attention / DSA
117- torchtitan_npu.override.common.rms_norm.asc
118- 
119- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc
120- 
121- torchtitan_npu.override.deepseek_v4.sparse_attn.asc
122- # MHC
123- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre
124- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post
125- # MoE token dispatcher
126- torchtitan_npu.override.common.token_dispatcher.asc
127- )
128-fi
129- 
130-# Wrapper defaults extend override.imports after the base targets.
131-CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_CLI_OVERRIDES}}"
132- 
133-DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \
134-MODULE="${MODULE}" \
135-CONFIG="${CONFIG}" \
136-NGPU="${NGPU}" \
137-LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
138-bash scripts/run_train.sh \
139- $HF_ASSETS_ARGS \
140- $PARALLELISM_ARGS \
141- $TRAINING_ARGS \
142- $DEBUG_ARGS \
143- $OPTIMIZER_ARGS \
144- $PROFILER_ARGS \
145- $COMM_ARGS \
146- $CHECKPOINT_ARGS \
147- --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
148- $CLI_OVERRIDES \
149- "$@"
@@ -4,24 +4,12 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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 A3 GraphTrainer with sequence-based MoE EP overlap and NPU auto scheduling.
8set -euo pipefail7set -euo pipefail
9 8 
10-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
11- 10+CONFIG="${CONFIG:-deepseek_v4_flash_8p_cpt_4k_a3_graphtrainer}" \
12-export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash_43layers_16experts}"11+NGPU="${NGPU:-8}" \
13-export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=112+TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER="${TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER:-1}" \
14-export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=013+TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER="${TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER:-0}" \
15-export TORCH_NPU_USE_COMPATIBLE_IMPL=114+TORCH_NPU_USE_COMPATIBLE_IMPL="${TORCH_NPU_USE_COMPATIBLE_IMPL:-1}" \
16- 15+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
17-EP_OVERLAP_ARGS=(
18- --compile.ep_overlap.enabled
19- --compile.ep_overlap.chunk_dim seq
20- --compile.ep_overlap.module_fqn "layers.*.moe"
21- --compile.pass_pipeline mutation-functionalization+npu_auto_overlap
22-)
23- 
24-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
25- --debug.moe-force-load-balance \
26- "${EP_OVERLAP_ARGS[@]}" \
27- "$@"
@@ -4,61 +4,10 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# A5 wrapper around the common DeepSeek-V4 Flash CPT launcher. Keep the shared
8-# model, training, and parallelism defaults in the A3 script; this entrypoint
9-# only supplies A5-specific runtime, quantization, and recompute settings.
10-# Append CLI arguments to override the defaults below:
11-# ./examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5.sh --training.steps 5
12- 
13set -euo pipefail7set -euo pipefail
14 8 
15-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
16- 10+CONFIG="${CONFIG:-deepseek_v4_flash_8p_cpt_4k_a5}" \
17-# Use the command line `npu-smi info -t topo` to query the CPU affinity of the11+NGPU="${NGPU:-8}" \
18-# NPU cards for configuration.12+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
19-export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"13+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
20- 
21-# A5-only fused ops; USE_GOLDEN=1 keeps the pure reference list.
22-if [[ "${USE_GOLDEN:-0}" != "1" ]]; then
23- export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \
24- torchtitan_npu.override.deepseek_v4.compressor.asc \
25- torchtitan_npu.override.common.swiglu_group.asc \
26- torchtitan_npu.override.common.swiglu_group.asc_shared_experts}"
27-fi
28- 
29-# A5 defaults to block-FP8 quantized training. Append
30-# --extension.quantization.no-enable-quantized-training for BF16 training.
31-#
32-# fsdp-prequantize leaves fsdp-prequantize-fqns unset, so the recipe default
33-# whitelist (all Block FP8 projections) applies. The runtime guard requires
34-# each whitelisted weight's dp-sharded dim0 to stay 64-aligned: at this
35-# script's DP_SHARD=8 every default entry is aligned (wkv dim0=512 -> 64
36-# rows/rank). At degrees where an entry breaks alignment (e.g. DP_SHARD=16:
37-# wkv shards to 32 rows) training fails fast at startup with a fix hint;
38-# narrow the whitelist by appending the default patterns minus the offending
39-# one, e.g. excluding wkv (comma-separated in a single argument, matching the
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.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 drop
43-# the .moe.shared_experts.* entries on a model without shared experts.
44-QUANTIZATION_ARGS=(
45- --extension.quantization.enable-quantized-training
46- --extension.quantization.recipe all_block_fp8
47- --extension.quantization.enable-fsdp-prequantize
48- --extension.quantization.li-quantization fp8
49- --extension.quantization.kv-norm-quantization.format mxfp8
50- --extension.quantization.kv-norm-quantization.fqns .attention.kv_norm,.attention.compressor.norm
51- --extension.quantization.kv-norm-quantization.block-size 64
52-)
53- 
54-# Disable swap optimizer for better performance
55-export OPTIMIZER_OVERRIDES=""
56- 
57-# Tyro treats activation-checkpoint:selective as a subcommand, so it must be
58-# the final token after all regular options and override targets.
59-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
60- --training.num-tokens-per-microbatch-per-dp-rank 8192 \
61- "${QUANTIZATION_ARGS[@]}" \
62- --debug.moe-force-load-balance \
63- "$@" \
64- activation-checkpoint:selective
@@ -4,30 +4,13 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# Single-node A5 GraphTrainer debug recipe with sequence-based EP overlap.
8-# Save shared/routed MoE W13 activations with the dsv4-mhc-moe-save policy.
9-# Append CLI arguments to override defaults, for example --training.steps 5.
10set -euo pipefail7set -euo pipefail
11 8 
12-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
13- 10+CONFIG="${CONFIG:-deepseek_v4_flash_8p_cpt_4k_a5_graphtrainer}" \
14-export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash_43layers_16experts}"11+NGPU="${NGPU:-8}" \
15-export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=112+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
16-export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=013+TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER="${TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER:-1}" \
17-export TORCH_NPU_USE_COMPATIBLE_IMPL=114+TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER="${TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER:-0}" \
18- 15+TORCH_NPU_USE_COMPATIBLE_IMPL="${TORCH_NPU_USE_COMPATIBLE_IMPL:-1}" \
19-STEPS="${STEPS:-20}"16+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
20- 
21-EP_OVERLAP_ARGS=(
22- --compile.ep_overlap.enabled
23- --compile.ep_overlap.chunk_dim seq
24- --compile.ep_overlap.module_fqn "layers.*.moe"
25- --compile.pass_pipeline mutation-functionalization+npu_auto_overlap
26-)
27- 
28-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a5.sh" \
29- --debug.moe-force-load-balance \
30- --compile.memory-policy dsv4-mhc-moe-save \
31- --training.steps "${STEPS}" \
32- "${EP_OVERLAP_ARGS[@]}" \
33- "$@"
@@ -4,41 +4,10 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# A5 wrapper around the common DeepSeek-V4 Flash CPT launcher. Keep the shared
8-# model, training, and parallelism defaults in the A3 script; this entrypoint
9-# only supplies A5-specific runtime, quantization, and recompute settings.
10-# Append CLI arguments to override the defaults below:
11-# ./examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a5_hif8.sh --training.steps 5
12- 
13set -euo pipefail7set -euo pipefail
14 8 
15-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
16- 10+CONFIG="${CONFIG:-deepseek_v4_flash_8p_cpt_4k_a5_hif8}" \
17-# Use the command line `npu-smi info -t topo` to query the CPU affinity of the11+NGPU="${NGPU:-8}" \
18-# NPU cards for configuration.12+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
19-export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"13+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
20- 
21-# A5-only fused ops; USE_GOLDEN=1 keeps the pure reference list.
22-if [[ "${USE_GOLDEN:-0}" != "1" ]]; then
23- export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \
24- torchtitan_npu.override.common.swiglu_group.asc \
25- torchtitan_npu.override.common.swiglu_group.asc_shared_experts}"
26-fi
27- 
28-# HiF8 (current tensor scaling) quantized training.
29-# Append --extension.quantization.no-enable-quantized-training for BF16
30-# training.
31- 
32-QUANTIZATION_ARGS=(
33- --extension.quantization.enable-quantized-training
34- --extension.quantization.recipe all_hif8
35- --extension.quantization.li-quantization hif8
36-)
37- 
38-# Tyro treats activation-checkpoint:selective as a subcommand, so it must be
39-# the final token after all regular options and override targets.
40-bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
41- "${QUANTIZATION_ARGS[@]}" \
42- --debug.moe-force-load-balance \
43- "$@" \
44- activation-checkpoint:selective
@@ -6,14 +6,9 @@
6# This source code is licensed under the BSD-style license found in the6# This source code is licensed under the BSD-style license found in the
7# LICENSE file in the root directory of this source tree.7# LICENSE file in the root directory of this source tree.
8 8 
9-# SFT wrapper around the 8p CPT launcher in this directory.
10set -euo pipefail9set -euo pipefail
11 10 
12-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
13-DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}"12+CONFIG="${CONFIG:-deepseek_v4_flash_8p_sft_4k_a3}" \
14- 13+NGPU="${NGPU:-8}" \
15-CONFIG="${CONFIG:-deepseek_v4_flash_43layers_16experts_sft_compiled}" \14+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
16-DSV4_SFT_DATASET="${DATASET_PATH}" \
17-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_8p_cpt_4k_a3.sh" \
18- --checkpointer.no-load-only \
19- "$@"
@@ -4,141 +4,9 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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 a single node.
8-# Append CLI arguments to override the defaults below:
9-# ./examples/deepseek_v4/debug/deepseek_v4_mini_1p_cpt_2k_a3.sh --training.steps 5
10-# USE_GOLDEN=1 selects reference attention, the RoPE workaround and AdamW.
11-# For deterministic execution, append
12-# --debug.seed 42 --debug.deterministic to the command line.
13- 
14set -euo pipefail7set -euo pipefail
15 8 
16-NGPU="${NGPU:-1}"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
17-WORLD_SIZE="${NGPU}"10+CONFIG="${CONFIG:-deepseek_v4_mini_1p_cpt_2k_a3}" \
18- 11+NGPU="${NGPU:-1}" \
19-# Model12+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
20-MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
21-CONFIG="${CONFIG:-deepseek_v4_debugmodel}"
22- 
23-# Dataloader
24-# Dataset selection and source paths belong to the selected MODULE/CONFIG recipe.
25-HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
26- 
27-# Parallelism
28-TP=1
29-PP=1
30-EP=1
31-CP="${CP:-1}"
32-DP_SHARD=1
33-DP_REPLICATE=1
34- 
35-# Training
36-SEQ_LEN=2048
37-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=2048
38-NUM_TOKENS_PER_TRAIN_STEP=-1
39-STEPS=100
40- 
41-# Debug
42-USE_GOLDEN="${USE_GOLDEN:-0}"
43-DEBUG_ARGS="
44- --debug.print-config
45-"
46- 
47-# HF assets
48-HF_ASSETS_ARGS="
49- --hf-assets-path ${HF_ASSETS_PATH}
50-"
51- 
52-# Parallelism
53-PARALLELISM_ARGS="
54- --parallelism.data-parallel-shard-degree ${DP_SHARD}
55- --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
56- --parallelism.expert-parallel-degree ${EP}
57- --parallelism.tensor-parallel-degree ${TP}
58- --parallelism.context-parallel-degree ${CP}
59- --parallelism.pipeline-parallel-degree ${PP}
60-"
61- 
62-# Training
63-TRAINING_ARGS="
64- --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}
65- --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP}
66- --training.max-context-length ${SEQ_LEN}
67- --training.steps ${STEPS}
68- --training.disable-cuda-graphs
69-"
70- 
71-# Checkpoint policy is declared by the selected Python recipe.
72-CHECKPOINT_ARGS=""
73- 
74-# Profiler
75-PROFILER_ARGS="
76- --profiler.no-enable-profiling
77- --profiler.save-traces-folder profiling_path
78- --profiler.extension.no-enable-online-parse
79- --profiler.extension.profiler-start 6
80- --profiler.extension.profiler-end 7
81- --profiler.extension.profile-ranks 0
82-"
83- 
84-# Communication
85-COMM_ARGS="
86- --comm.init-timeout-seconds 7200
87- --comm.train-timeout-seconds 600
88-"
89- 
90-# Optimizer
91-OPTIMIZER_ARGS="
92- --optim.optimizer.name Muon
93- --optim.optimizer.lr 1.0e-5
94- --optim.optimizer.beta1 0.9
95- --optim.optimizer.beta2 0.95
96- --optim.optimizer.eps 1.0e-8
97- --optim.optimizer.weight_decay 1.0e-1
98- --optim.optimizer.muon_momentum 0.95
99- --optim.optimizer.muon_enable_nesterov
100- --optim.optimizer.muon_ns_steps 10
101- --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
102-"
103-OPTIMIZER_OVERRIDES="
104- torchtitan_npu.override.common.optimizer.swap_optimizer
105-"
106- 
107-if [[ "${USE_GOLDEN}" == "1" ]]; then
108- OPTIMIZER_ARGS="--optim.optimizer.name AdamW --optim.optimizer.lr 1.0e-5"
109- OPTIMIZER_OVERRIDES=""
110- NPU_OPS_OVERRIDES=(
111- torchtitan_npu.override.common.rope.workaround
112- )
113-else
114- NPU_OPS_OVERRIDES=(
115- # Attention / DSA
116- torchtitan_npu.override.common.rms_norm.asc
117- torchtitan_npu.override.common.rope.asc_complex
118- 
119- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc
120- 
121- 'torchtitan_npu.override.deepseek_v4.sparse_attn.asc={"num_heads":16,"index_num_heads":8}'
122- # MHC
123- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre
124- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post
125- # MoE token dispatcher
126- torchtitan_npu.override.common.token_dispatcher.asc
127- )
128-fi
129- 
130-MODULE="${MODULE}" \
131-CONFIG="${CONFIG}" \
132-NGPU="${NGPU}" \
133-LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
134-bash scripts/run_train.sh \
135- $HF_ASSETS_ARGS \
136- $PARALLELISM_ARGS \
137- $TRAINING_ARGS \
138- $DEBUG_ARGS \
139- $OPTIMIZER_ARGS \
140- $PROFILER_ARGS \
141- $COMM_ARGS \
142- $CHECKPOINT_ARGS \
143- --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
144- "$@"
@@ -4,177 +4,16 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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.
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 \
10-# ./examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
11-# --checkpointer.initial-load-path /path/to/model_ckpt --training.steps 5
12-# USE_GOLDEN=1 selects the reference combination (the model's default attention).
13-# For deterministic execution, append
14-# --debug.seed 42 --debug.deterministic to the command line.
15- 
16set -euo pipefail7set -euo pipefail
17 8 
18-export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
19-export HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}"10+CONFIG="${CONFIG:-deepseek_v4_pro_32p_cpt_4k_a5}" \
20-export ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}"11+NGPU="${NGPU:-8}" \
21-export HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}"12+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 4}' <<< "${NODE_IPS:-}")}" \
22-# Disable the HCCL watchdog for long checkpoint loading on the A5 setup.13+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
23-export HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}"14+HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}" \
24-# Use the command line `npu-smi info -t topo` to query the CPU Affinity of the NPU cards for configuration.15+HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}" \
25-export CPU_AFFINITY_CONF=1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-19116+ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}" \
26- 17+HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}" \
27-NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}"18+HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" \
28-NGPU="${NGPU:-8}"19+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train_multinodes.sh" "$@"
29-NNODES=$(awk -F, '{print NF}' <<< "${NODE_IPS}")
30-WORLD_SIZE=$((NGPU * NNODES))
31- 
32-# Model
33-MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
34-CONFIG="${CONFIG:-deepseek_v4_pro_61layers_32experts_cpt}"
35- 
36-# Dataloader & Checkpoint
37-HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
38-CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path
39-CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path
40- 
41-# Parallelism
42-TP="${TP:-1}"
43-PP="${PP:-1}"
44-EP="${EP:-32}"
45-CP="${CP:-1}"
46-DP_SHARD="${DP_SHARD:-32}"
47-DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
48- 
49-# Training
50-SEQ_LEN=4096
51-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096
52-NUM_TOKENS_PER_TRAIN_STEP=1048576
53-STEPS="${STEPS:-100}"
54- 
55-# Debug
56-USE_GOLDEN="${USE_GOLDEN:-0}"
57-DEBUG_ARGS="
58- --debug.no-moe-force-load-balance
59- --debug.print-config
60-"
61- 
62-# A5 defaults to block-FP8 quantized training. Append
63-# --extension.quantization.no-enable-quantized-training for BF16 training.
64-QUANTIZATION_ARGS="
65- --extension.quantization.enable-quantized-training
66- --extension.quantization.recipe all_block_fp8
67-"
68- 
69-# HF assets
70-HF_ASSETS_ARGS="
71- --hf-assets-path ${HF_ASSETS_PATH}
72-"
73- 
74-# Parallelism
75-PARALLELISM_ARGS="
76- --parallelism.data-parallel-shard-degree ${DP_SHARD}
77- --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
78- --parallelism.expert-parallel-degree ${EP}
79- --parallelism.tensor-parallel-degree ${TP}
80- --parallelism.context-parallel-degree ${CP}
81- --parallelism.pipeline-parallel-degree ${PP}
82-"
83- 
84-# Training
85-TRAINING_ARGS="
86- --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}
87- --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP}
88- --training.max-context-length ${SEQ_LEN}
89- --training.steps ${STEPS}
90- --training.disable-cuda-graphs
91-"
92- 
93-# Checkpoint
94-# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
95-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
96-# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
97-# from `CKPT_INIT_LOAD_PATH`.
98-CHECKPOINT_ARGS="
99- --checkpointer.load-only
100- --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
101- --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
102- --checkpointer.initial-load-in-hf
103-"
104- 
105-# Profiler
106-PROFILER_ARGS="
107- --profiler.no-enable-profiling
108- --profiler.save-traces-folder profiling_path
109- --profiler.extension.no-enable-online-parse
110- --profiler.extension.profiler-start 6
111- --profiler.extension.profiler-end 7
112- --profiler.extension.profile-ranks 0
113-"
114- 
115-# Communication
116-COMM_ARGS="
117- --comm.init-timeout-seconds 7200
118- --comm.train-timeout-seconds 600
119-"
120- 
121-# Optimizer
122-OPTIMIZER_ARGS="
123- --optim.optimizer.name Muon
124- --optim.optimizer.lr 1.0e-5
125- --optim.optimizer.beta1 0.9
126- --optim.optimizer.beta2 0.95
127- --optim.optimizer.eps 1.0e-8
128- --optim.optimizer.weight_decay 1.0e-1
129- --optim.optimizer.muon_momentum 0.95
130- --optim.optimizer.muon_enable_nesterov
131- --optim.optimizer.muon_ns_steps 10
132- --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
133-"
134-OPTIMIZER_OVERRIDES="
135- torchtitan_npu.override.common.optimizer.swap_optimizer
136-"
137- 
138-if [[ "${USE_GOLDEN}" == "1" ]]; then
139- NPU_OPS_OVERRIDES=(
140- torchtitan_npu.override.common.rope.workaround
141- )
142-else
143- NPU_OPS_OVERRIDES=(
144- # Attention / DSA
145- torchtitan_npu.override.common.rms_norm.asc
146- torchtitan_npu.override.common.rope.asc_partial
147- torchtitan_npu.override.deepseek_v4.compressor.asc
148- 
149- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc
150- 
151- 'torchtitan_npu.override.deepseek_v4.sparse_attn.asc={"num_heads":128}'
152- # MHC
153- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre
154- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post
155- # MoE token dispatcher
156- torchtitan_npu.override.common.token_dispatcher.asc
157- # MoE SwiGLU Group
158- torchtitan_npu.override.common.swiglu_group.asc
159- torchtitan_npu.override.common.swiglu_group.asc_shared_experts
160- )
161-fi
162- 
163-DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \
164-MODULE="${MODULE}" \
165-CONFIG="${CONFIG}" \
166-NODE_IPS="${NODE_IPS}" \
167-NGPU="${NGPU}" \
168-LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
169-bash scripts/run_train_multinodes.sh \
170- $HF_ASSETS_ARGS \
171- $PARALLELISM_ARGS \
172- $TRAINING_ARGS \
173- $DEBUG_ARGS \
174- $QUANTIZATION_ARGS \
175- $OPTIMIZER_ARGS \
176- $PROFILER_ARGS \
177- $COMM_ARGS \
178- $CHECKPOINT_ARGS \
179- --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
180- "$@"
@@ -4,159 +4,15 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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- 
8set -euo pipefail7set -euo pipefail
9 8 
10-export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
11-export HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}"10+CONFIG="${CONFIG:-deepseek_v4_pro_8p_cpt_4k_a5_cpuoffload}" \
12-export ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}"11+NGPU="${NGPU:-8}" \
13-export HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}"12+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
14-# Disable the HCCL watchdog for long checkpoint loading on the A5 setup.13+HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}" \
15-export HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}"14+HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}" \
16-# Use the command line `npu-smi info -t topo` to query the CPU Affinity of the NPU cards for configuration.15+ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}" \
17-export CPU_AFFINITY_CONF=1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-19116+HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}" \
18- 17+HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" \
19-NGPU="${NGPU:-8}"18+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../../scripts/run_train.sh" "$@"
20-WORLD_SIZE="${NGPU}"
21- 
22-# Model
23-MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
24-CONFIG="${CONFIG:-deepseek_v4_pro_61layers_12experts_cpt}"
25- 
26-# Dataloader & Checkpoint
27-HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_tokenizer}" # your tokenizer path
28-CKPT_SAVE_LOAD_PATH="${CKPT_SAVE_LOAD_PATH:-/path/to/save_ckpt}" # your model save/load ckpt path
29-CKPT_INIT_LOAD_PATH="${CKPT_INIT_LOAD_PATH:-/path/to/init_load_ckpt}" # your model initial load ckpt path
30- 
31-# Parallelism
32-TP="${TP:-1}"
33-PP="${PP:-1}"
34-EP="${EP:-4}"
35-CP="${CP:-1}"
36-DP_SHARD="${DP_SHARD:-8}"
37-DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
38- 
39-# Training
40-SEQ_LEN=4096
41-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096
42-NUM_TOKENS_PER_TRAIN_STEP=262144
43-STEPS="${STEPS:-100}"
44- 
45-# Debug
46-USE_GOLDEN="${USE_GOLDEN:-0}"
47-DEBUG_ARGS="
48- --debug.no-moe-force-load-balance
49- --debug.print-config
50-"
51- 
52-# HF assets
53-HF_ASSETS_ARGS="
54- --hf-assets-path ${HF_ASSETS_PATH}
55-"
56- 
57-# Parallelism
58-PARALLELISM_ARGS="
59- --parallelism.data-parallel-shard-degree ${DP_SHARD}
60- --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
61- --parallelism.expert-parallel-degree ${EP}
62- --parallelism.tensor-parallel-degree ${TP}
63- --parallelism.context-parallel-degree ${CP}
64- --parallelism.pipeline-parallel-degree ${PP}
65-"
66- 
67-# Training
68-TRAINING_ARGS="
69- --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}
70- --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP}
71- --training.max-context-length ${SEQ_LEN}
72- --training.steps ${STEPS}
73- --training.disable-cuda-graphs
74- --training.enable-cpu-offload
75-"
76- 
77-# Checkpoint
78-# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
79-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
80-# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
81-# from `CKPT_INIT_LOAD_PATH`.
82-CHECKPOINT_ARGS="
83- --checkpointer.load-only
84- --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
85- --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
86- --checkpointer.initial-load-in-hf
87-"
88- 
89-# Profiler
90-PROFILER_ARGS="
91- --profiler.no-enable-profiling
92- --profiler.save-traces-folder profiling_path
93- --profiler.extension.no-enable-online-parse
94- --profiler.extension.profiler-start 6
95- --profiler.extension.profiler-end 7
96- --profiler.extension.profile-ranks 0
97-"
98- 
99-# Communication
100-COMM_ARGS="
101- --comm.init-timeout-seconds 7200
102- --comm.train-timeout-seconds 600
103-"
104- 
105-# Optimizer
106-OPTIMIZER_ARGS="
107- --optim.optimizer.name Muon
108- --optim.optimizer.lr 1.0e-5
109- --optim.optimizer.beta1 0.9
110- --optim.optimizer.beta2 0.95
111- --optim.optimizer.eps 1.0e-8
112- --optim.optimizer.weight_decay 1.0e-1
113- --optim.optimizer.muon_momentum 0.95
114- --optim.optimizer.muon_enable_nesterov
115- --optim.optimizer.muon_ns_steps 10
116- --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
117-"
118-OPTIMIZER_OVERRIDES="
119- torchtitan_npu.override.common.optimizer.swap_optimizer
120-"
121- 
122-if [[ "${USE_GOLDEN}" == "1" ]]; then
123- NPU_OPS_OVERRIDES=(
124- torchtitan_npu.override.common.rope.workaround
125- )
126-else
127- NPU_OPS_OVERRIDES=(
128- # Attention / DSA
129- torchtitan_npu.override.common.rms_norm.asc
130- torchtitan_npu.override.common.rope.asc_partial
131- torchtitan_npu.override.deepseek_v4.compressor.asc
132- 
133- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc
134- 
135- 'torchtitan_npu.override.deepseek_v4.sparse_attn.asc={"num_heads":128}'
136- # MHC
137- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre
138- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post
139- # MoE token dispatcher
140- torchtitan_npu.override.common.token_dispatcher.asc
141- # MoE SwiGLU Group
142- torchtitan_npu.override.common.swiglu_group.asc
143- torchtitan_npu.override.common.swiglu_group.asc_shared_experts
144- )
145-fi
146- 
147-DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \
148-MODULE="${MODULE}" \
149-CONFIG="${CONFIG}" \
150-NGPU="${NGPU}" \
151-LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
152-bash scripts/run_train.sh \
153- $HF_ASSETS_ARGS \
154- $PARALLELISM_ARGS \
155- $TRAINING_ARGS \
156- $DEBUG_ARGS \
157- $OPTIMIZER_ARGS \
158- $PROFILER_ARGS \
159- $COMM_ARGS \
160- $CHECKPOINT_ARGS \
161- --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
162- "$@"
@@ -6,14 +6,10 @@
6# This source code is licensed under the BSD-style license found in the6# This source code is licensed under the BSD-style license found in the
7# LICENSE file in the root directory of this source tree.7# LICENSE file in the root directory of this source tree.
8 8 
9-# Eight-node SFT wrapper around the common DeepSeek-V4 Flash SFT launcher.
10set -euo pipefail9set -euo pipefail
11 10 
12-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
13- 12+CONFIG="${CONFIG:-deepseek_v4_flash_8node_sft_4k_a3}" \
14-NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \13+NGPU="${NGPU:-16}" \
15- xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}"14+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 8}' <<< "${NODE_IPS:-}")}" \
16-NGPU="${NGPU:-16}"15+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
17-export NODE_IPS NGPU
18- 
19-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_sft_4k_a3.sh" "$@"
@@ -4,23 +4,16 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# 1M sequence specialization. Reuse the A5 4K wrapper and override only the
8-# Trainer configuration that differs from the 4K setup. User CLI arguments are
9-# appended last and therefore can override these defaults.
10- 
11set -euo pipefail7set -euo pipefail
12 8 
13-# Quantization defaults are inherited from the A5 4K wrapper.9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
14- 10+CONFIG="${CONFIG:-deepseek_v4_flash_cpt_1024k_a5}" \
15-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"11+NGPU="${NGPU:-8}" \
16- 12+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 16}' <<< "${NODE_IPS:-}")}" \
17-CONFIG="${CONFIG:-deepseek_v4_flash_cp_cpt}" \13+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
18-DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-16384}" \14+HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}" \
19-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \15+HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}" \
20- --training.max-context-length 1048576 \16+ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}" \
21- --training.num-tokens-per-microbatch-per-dp-rank 1048576 \17+HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}" \
22- --training.num-tokens-per-train-step 8388608 \18+HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" \
23- --parallelism.context-parallel-degree 128 \19+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
24- --parallelism.data-parallel-shard-degree 1 \
25- --parallelism.data-parallel-replicate-degree 1 \
26- "$@"
@@ -4,164 +4,10 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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.
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 \
10-# ./examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
11-# --checkpointer.initial-load-path /path/to/model_ckpt --training.steps 5
12-# USE_GOLDEN=1 selects the reference combination (the model's default attention).
13-# For deterministic execution, append
14-# --debug.seed 42 --debug.deterministic to the command line.
15- 
16set -euo pipefail7set -euo pipefail
17 8 
18-NODE_IPS="${NODE_IPS:-xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, \9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
19- xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx, xx.xx.xx.xx}"10+CONFIG="${CONFIG:-deepseek_v4_flash_cpt_4k_a3}" \
20-NGPU="${NGPU:-16}"11+NGPU="${NGPU:-16}" \
21-NNODES=$(awk -F, '{print NF}' <<< "${NODE_IPS}")12+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 8}' <<< "${NODE_IPS:-}")}" \
22-WORLD_SIZE=$((NGPU * NNODES))13+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
23- 
24-# Model
25-MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4}"
26-CONFIG="${CONFIG:-deepseek_v4_flash_cpt}"
27- 
28-# Dataloader & Checkpoint
29-HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV4_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- 
33-# Parallelism
34-TP=1
35-PP=1
36-EP=128
37-CP="${CP:-1}"
38-DP_SHARD=128
39-DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
40- 
41-# Training
42-SEQ_LEN=4096
43-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096
44-NUM_TOKENS_PER_TRAIN_STEP=4194304
45-STEPS=100
46- 
47-# Debug
48-USE_GOLDEN="${USE_GOLDEN:-0}"
49-DEBUG_ARGS="
50- --debug.no-moe-force-load-balance
51- --debug.print-config
52-"
53- 
54-# HF assets
55-HF_ASSETS_ARGS="
56- --hf-assets-path ${HF_ASSETS_PATH}
57-"
58- 
59-# The Grain dataset is configured by the recipe or an explicit override.
60- 
61-# Parallelism
62-PARALLELISM_ARGS="
63- --parallelism.data-parallel-shard-degree ${DP_SHARD}
64- --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
65- --parallelism.expert-parallel-degree ${EP}
66- --parallelism.tensor-parallel-degree ${TP}
67- --parallelism.context-parallel-degree ${CP}
68- --parallelism.pipeline-parallel-degree ${PP}
69-"
70- 
71-# Compilation policy is declared by the selected Python recipe.
72- 
73-# Training
74-TRAINING_ARGS="
75- --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}
76- --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP}
77- --training.max-context-length ${SEQ_LEN}
78- --training.steps ${STEPS}
79- --training.disable-cuda-graphs
80-"
81- 
82-# Checkpoint
83-# `checkpointer.folder` is the output/resume root (`CKPT_SAVE_LOAD_PATH`). If it
84-# already contains a valid step-* checkpoint, upstream TorchTitan resumes from
85-# it and ignores `initial-load-path`; use a new/empty folder when cold-starting
86-# from `CKPT_INIT_LOAD_PATH`.
87-CHECKPOINT_ARGS="
88- --checkpointer.load-only
89- --checkpointer.folder ${CKPT_SAVE_LOAD_PATH}
90- --checkpointer.initial-load-path ${CKPT_INIT_LOAD_PATH}
91- --checkpointer.initial-load-in-hf
92-"
93- 
94-# Profiler
95-PROFILER_ARGS="
96- --profiler.no-enable-profiling
97- --profiler.save-traces-folder profiling_path
98- --profiler.extension.no-enable-online-parse
99- --profiler.extension.profiler-start 6
100- --profiler.extension.profiler-end 7
101- --profiler.extension.profile-ranks 0
102-"
103- 
104-# Communication
105-COMM_ARGS="
106- --comm.init-timeout-seconds 7200
107- --comm.train-timeout-seconds 600
108-"
109- 
110-# Optimizer
111-OPTIMIZER_ARGS="
112- --optim.optimizer.name Muon
113- --optim.optimizer.lr 1.0e-5
114- --optim.optimizer.beta1 0.9
115- --optim.optimizer.beta2 0.95
116- --optim.optimizer.eps 1.0e-8
117- --optim.optimizer.weight_decay 1.0e-1
118- --optim.optimizer.muon_momentum 0.95
119- --optim.optimizer.muon_enable_nesterov
120- --optim.optimizer.muon_ns_steps 10
121- --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
122-"
123-OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
124- 
125-if [[ "${USE_GOLDEN}" == "1" ]]; then
126- DEFAULT_CLI_OVERRIDES=""
127- NPU_OPS_OVERRIDES=(
128- torchtitan_npu.override.common.rope.workaround
129- )
130-else
131- DEFAULT_CLI_OVERRIDES="torchtitan_npu.override.common.rope.asc_complex"
132- NPU_OPS_OVERRIDES=(
133- # Attention / DSA
134- torchtitan_npu.override.common.rms_norm.asc
135- 
136- torchtitan_npu.override.deepseek_v4.lightning_indexer.asc
137- 
138- torchtitan_npu.override.deepseek_v4.sparse_attn.asc
139- # MHC
140- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_pre
141- torchtitan_npu.override.deepseek_v4.mhc.asc_hc_post
142- # MoE token dispatcher
143- torchtitan_npu.override.common.token_dispatcher.asc
144- )
145-fi
146- 
147-# Wrapper defaults extend override.imports after the base targets.
148-CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_CLI_OVERRIDES}}"
149- 
150-DSV4_PER_DOC_ALIGNMENT="${DSV4_PER_DOC_ALIGNMENT:-$((128 * CP))}" \
151-MODULE="${MODULE}" \
152-CONFIG="${CONFIG}" \
153-NODE_IPS="${NODE_IPS}" \
154-NGPU="${NGPU}" \
155-LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
156-bash scripts/run_train_multinodes.sh \
157- $HF_ASSETS_ARGS \
158- $PARALLELISM_ARGS \
159- $TRAINING_ARGS \
160- $DEBUG_ARGS \
161- $OPTIMIZER_ARGS \
162- $PROFILER_ARGS \
163- $COMM_ARGS \
164- $CHECKPOINT_ARGS \
165- --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
166- $CLI_OVERRIDES \
167- "$@"
@@ -4,67 +4,16 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# A5 wrapper around the common DeepSeek-V4 Flash CPT launcher. Keep model,
8-# training, and parallelism differences as CLI overrides so user-supplied
9-# arguments remain the final source of truth.
10- 
11set -euo pipefail7set -euo pipefail
12 8 
13-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
14- 10+CONFIG="${CONFIG:-deepseek_v4_flash_cpt_4k_a5}" \
15-export HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}"11+NGPU="${NGPU:-8}" \
16-export HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}"12+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 16}' <<< "${NODE_IPS:-}")}" \
17-export ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}"13+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
18-export HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}"14+HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}" \
19-# Disable the HCCL watchdog for long checkpoint loading on the A5 setup.15+HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}" \
20-export HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}"16+ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}" \
21-# Override this for the host topology reported by `npu-smi info -t topo`.17+HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}" \
22-export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"18+HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" \
23- 19+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
24-# A5-only fused ops; USE_GOLDEN=1 keeps the pure reference list.
25-if [[ "${USE_GOLDEN:-0}" != "1" ]]; then
26- export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \
27- torchtitan_npu.override.deepseek_v4.compressor.asc \
28- torchtitan_npu.override.common.swiglu_group.asc \
29- torchtitan_npu.override.common.swiglu_group.asc_shared_experts}"
30-fi
31- 
32-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, \
33- 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}"
34-NGPU="${NGPU:-8}"
35-export NODE_IPS NGPU
36- 
37-# A5 defaults to block-FP8 quantized training. A trailing
38-# --extension.quantization.no-enable-quantized-training selects BF16 instead.
39-#
40-# The runtime guard requires each pre-quantized weight's dp-sharded dim0 to
41-# stay 64-aligned, and the base script runs DP_SHARD=128 (dim0 must be a
42-# multiple of 64*128=8192). For the default deepseek_v4_flash config that
43-# breaks the evenly-sharded dense projections -- wq_a (1024 -> 8 rows/rank),
44-# wkv (512 -> 4), wo_b (4096 -> 32) and shared_experts w1/w3 (2048 -> 16) and
45-# w2 (4096 -> 32) -- which fail fast at startup with a fix hint instead of
46-# silently falling back to BF16 communication. fsdp-prequantize-fqns below
47-# therefore narrows the whitelist to the projections that stay aligned: the
48-# per-head/per-group BlockShard projections (wq_b, wo_a, indexer.wq_b) and
49-# the expert-axis-sharded routed experts. At lower DP_SHARD degrees (e.g. 8,
50-# where every default entry is aligned) drop that line to restore the recipe
51-# default whitelist (all Block FP8 projections).
52-QUANTIZATION_ARGS=(
53- --extension.quantization.enable-quantized-training
54- --extension.quantization.recipe all_block_fp8
55- --extension.quantization.enable-fsdp-prequantize
56- --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 fp8
58- --extension.quantization.kv-norm-quantization.format mxfp8
59- --extension.quantization.kv-norm-quantization.fqns .attention.kv_norm,.attention.compressor.norm
60- --extension.quantization.kv-norm-quantization.block-size 64
61-)
62- 
63-# Disable swap optimizer for better performance
64-export OPTIMIZER_OVERRIDES=""
65- 
66-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \
67- --training.num-tokens-per-microbatch-per-dp-rank 8192 \
68- "${QUANTIZATION_ARGS[@]}" \
69- "$@" \
70- activation-checkpoint:selective
@@ -4,30 +4,19 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# Full-model A5 GraphTrainer recipe with sequence-based EP overlap.
8-# Run this script on each participating node, as with the A5 eager recipe.
9-# Append CLI arguments to override defaults, for example --training.steps 5.
10set -euo pipefail7set -euo pipefail
11 8 
12-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
13- 10+CONFIG="${CONFIG:-deepseek_v4_flash_cpt_4k_a5_graphtrainer}" \
14-export CONFIG="${CONFIG:-graph_trainer_deepseek_v4_flash_cpt}"11+NGPU="${NGPU:-8}" \
15-export TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER=112+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 16}' <<< "${NODE_IPS:-}")}" \
16-export TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER=013+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
17-export TORCH_NPU_USE_COMPATIBLE_IMPL=114+HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}" \
18- 15+HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}" \
19-STEPS="${STEPS:-20}"16+ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}" \
20- 17+HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}" \
21-EP_OVERLAP_ARGS=(18+HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" \
22- --compile.ep_overlap.enabled19+TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER="${TORCHINDUCTOR_USE_TORCH_PROFILER_BENCHMARKER:-1}" \
23- --compile.ep_overlap.chunk_dim seq20+TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER="${TORCHINDUCTOR_USE_EXPERIMENTAL_BENCHMARKER:-0}" \
24- --compile.ep_overlap.module_fqn "layers.*.moe"21+TORCH_NPU_USE_COMPATIBLE_IMPL="${TORCH_NPU_USE_COMPATIBLE_IMPL:-1}" \
25- --compile.pass_pipeline mutation-functionalization+npu_auto_overlap22+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
26-)
27- 
28-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \
29- --training.num-tokens-per-train-step 2097152 \
30- --training.steps "${STEPS}" \
31- --debug.moe-force-load-balance \
32- "${EP_OVERLAP_ARGS[@]}" \
33- "$@"
@@ -4,18 +4,10 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# LoRA wrapper around the common DeepSeek-V4 Flash CPT launcher. Keep model,
8-# training, and parallelism differences as CLI overrides so user-supplied
9-# arguments remain the final source of truth.
10- 
11set -euo pipefail7set -euo pipefail
12 8 
13-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
14- 10+CONFIG="${CONFIG:-deepseek_v4_flash_lora_4k_a3}" \
15-export CONFIG="${CONFIG:-deepseek_v4_flash_lora_compiled}"11+NGPU="${NGPU:-16}" \
16- 12+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 8}' <<< "${NODE_IPS:-}")}" \
17-# LoRA uses periodic native adapter checkpoints and final PEFT export.13+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
18-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh" \
19- --checkpointer.no-load-only \
20- --checkpointer.save-training-state \
21- "$@"
@@ -4,30 +4,16 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# QAT wrapper around the DeepSeek-V4 Flash CPT A5 launcher. Inherit the A5
8-# environment and training defaults, and override only quantization arguments.
9- 
10- 
11set -euo pipefail7set -euo pipefail
12 8 
13-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
14- 10+CONFIG="${CONFIG:-deepseek_v4_flash_qat_4k_a5}" \
15-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, \11+NGPU="${NGPU:-8}" \
16- 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}"12+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 16}' <<< "${NODE_IPS:-}")}" \
17-NGPU="${NGPU:-8}"13+CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}" \
18-export NODE_IPS NGPU14+HCCL_CONNECT_TIMEOUT="${HCCL_CONNECT_TIMEOUT:-7200}" \
19- 15+HCCL_EXEC_TIMEOUT="${HCCL_EXEC_TIMEOUT:-17330}" \
20-#Introduction of relevant parameters, please refer to docs/user-guides/quickstart.md.16+ACL_DEVICE_SYNC_TIMEOUT="${ACL_DEVICE_SYNC_TIMEOUT:-2147480}" \
21-QUANTIZATION_ARGS=(17+HCCL_EVENT_TIMEOUT="${HCCL_EVENT_TIMEOUT:-2147480}" \
22- --extension.quantization.enable-quantized-training18+HCCL_ASYNC_ERROR_HANDLING="${HCCL_ASYNC_ERROR_HANDLING:-0}" \
23- --extension.quantization.recipe all_block_fp819+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
24- --extension.quantization.enable-mxfp4-qat
25- --extension.quantization.li-quantization mxfp4
26-)
27- 
28-# Disable swap optimizer for better performance
29-export OPTIMIZER_OVERRIDES=""
30- 
31-exec bash "${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a5.sh" \
32- "${QUANTIZATION_ARGS[@]}" \
33- "$@"
@@ -6,15 +6,10 @@
6# This source code is licensed under the BSD-style license found in the6# This source code is licensed under the BSD-style license found in the
7# LICENSE file in the root directory of this source tree.7# LICENSE file in the root directory of this source tree.
8 8 
9-# Reuse the CPT launcher with an SFT JSONL or JSON file.
10set -euo pipefail9set -euo pipefail
11 10 
12-SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4}" \
13-CPT_SCRIPT="${CPT_SCRIPT:-${SCRIPT_DIR}/deepseek_v4_flash_cpt_4k_a3.sh}"12+CONFIG="${CONFIG:-deepseek_v4_flash_sft_4k_a3}" \
14-DATASET_PATH="${DATASET_PATH:-/path/to/train.jsonl}"13+NGPU="${NGPU:-16}" \
15- 14+NNODES="${NNODES:-$(awk -F, '{print NF ? NF : 8}' <<< "${NODE_IPS:-}")}" \
16-CONFIG="${CONFIG:-deepseek_v4_flash_sft_compiled}" \15+exec bash "$(dirname -- "${BASH_SOURCE[0]}")/../../scripts/run_train_multinodes.sh" "$@"
17-DSV4_SFT_DATASET="${DATASET_PATH}" \
18-exec bash "${CPT_SCRIPT}" \
19- --checkpointer.no-load-only \
20- "$@"
@@ -1,6 +1,8 @@
1# DeepSeek-V4 training examples1# DeepSeek-V4 training examples
2 2 
3-本目录只保留少量稳定入口,模型规模、序列长度、并行策略和量化方式优先通过 CLI 覆盖,不为每一种组合新增独立脚本。3+本目录提供选择完整 Python recipe 的启动入口。模型规模、序列长度、并行策略和量化方式由 `torchtitan_npu_recipes.examples.deepseek_v4` 中的配置函数定义,自定义组合使用 `MODULE` / `CONFIG` 选择,见[Python 配置指南](../../docs/developer_guides/python_recipes.md)。
4+ 
5+示例默认使用非 golden 的 NPU 融合算子组合,参考组合需显式设置 `USE_GOLDEN=1`。A3 使用 CANN 1104 和 torch-npu 1105.3,下载与安装见[安装指南](../../docs/user-guides/installation.md)。
4 6 
5## 入口关系7## 入口关系
6 8 
@@ -19,17 +21,15 @@ deepseek_v4_flash_cpt_4k_a3.sh
19 21 
20## 编译配置22## 编译配置
21 23 
22-编译和 checkpoint 的启用状态在 Python recipe 中定义。Flash A3/A5 默认选择24+编译和 checkpoint 的启用状态在 Python recipe 中定义。A3 8P Flash CPT debug
23-`deepseek_v4_flash_cpt`,8P debug 默认选择 `deepseek_v4_flash_43layers_16experts_compiled`;25+默认选择 `deepseek_v4_flash_8p_cpt_4k_a3_eager`,使用 `compile=None` 关闭模型编译。
24-二者均使用 `CompileConfig(components=[], model=ModelCompileConfig())`,只编译 model。26+其他 Flash 配置函数保留各自的编译配置;配置存在不表示当前 NPU trainer 支持该编译路径。
25-当前固定上游仍允许对已存在的配置传入 `--compile.model.backend aot_eager` 等普通字段。27+更改编译 backend、启用或关闭组件时直接修改 recipe,不使用通用字段 CLI。
26-从 `None` 启用组件、关闭组件或设置空列表时,直接修改 recipe;CLI 不再自动创建这些对象。
27 28 
28例如将以下函数保存为仓库根目录的 `my_recipes.py`,再通过 `MODULE=my_recipes CONFIG=my_run` 选择:29例如将以下函数保存为仓库根目录的 `my_recipes.py`,再通过 `MODULE=my_recipes CONFIG=my_run` 选择:
29 30 
30```python31```python
31-from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash_cpt32+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_cpt
32- 
33 33 
34def my_run():34def my_run():
35 config = deepseek_v4_flash_cpt()35 config = deepseek_v4_flash_cpt()
@@ -95,17 +95,45 @@ token 预算使用 `--training.num-tokens-per-microbatch-per-dp-rank` 和
95 95 
96### 8P Flash 16-expert Debug96### 8P Flash 16-expert Debug
97 97 
98-```sh98+默认使用 43 层、16 个专家、4K 上下文、Muon 优化器和非 golden 融合算子,以 eager 模式运行。
99-bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh \99+训练预算与 `upstream/dev_0.4.0` 的 A3 8P 脚本一致:每卡每个 microbatch 4096 个 token,
100- --training.steps 10100+每步 262144 个 token,共 100 步,并启用全量激活重计算。
101-```101+`USE_GOLDEN` 只切换算子组合,不改变优化器或文档打包上限。
102- 102+参考组合不提供 indexer 训练梯度,使用 Muon 会报 `missing gradients`;需要该组合时,
103-需要采集 profile 时显式追加:103+应在自定义配置中显式选择 AdamW,不能作为本用例的 Muon 训练对照。
104 104 
105```sh105```sh
106---profiler.enable-profiling106+bash examples/deepseek_v4/debug/deepseek_v4_flash_8p_cpt_4k_a3.sh
107```107```
108 108 
109+在 A3、CANN 1104 与 torch-npu 1105.3 上,修复前的完整 4K 配置已完成 50 步训练,
110+峰值显存约 `40.19 GiB`,未出现 OOM。与 `upstream/dev_0.4.0` 固定版本
111+`775fdcd5036de8c3311fb2eeaa45e1258f387227` 的 eager 运行比较时,使用同一份
112+FP32 初始权重、相同输入、seed 42、严格确定性检查,并关闭 HF32。
113+10 步比较中,loss 和 grad_norm 的最大相对误差分别为 `0.117694%` 和 `0.239883%`,
114+两项均满足仓库的数值近似阈值,比特一致未通过。进一步的完整 50 步比较中,
115+两项的最大相对误差分别为 `0.575068%` 和 `4.943348%`,平均绝对误差分别为
116+`0.02604002` 和 `0.12830677`,均未通过数值近似阈值。8 个 rank 每侧各消费
117+400 个 microbatch,输入全部一致;grad_norm、loss 分别从第 17、36 步开始逐步超限。
118+首个前向差异已定位到 Q head 归一化:旧版使用融合 RMSNorm,当前上游使用
119+BF16 算式,中间舍入不同。这些 50 步数据属于修复前版本,不能作为修复后的精度结论。
120+ 
121+当前已恢复可配置的 Q head 归一化节点,由非 golden 组合启用融合 RMSNorm;
122+同时修正 Muon 的两处迁移遗漏:`wo_a` 按每组 `o_lora_rank` 分块,
123+`compressor_128` 的投影与 APE 参数使用与旧版相同的 Muon 配置。
124+修复后以相同的完整配置比较第 1 步,loss 均为 `12.281325340270996`,
125+grad_norm 均为 `9.061148643493652`;8 个 rank 各 1199 个优化器参数的梯度
126+与更新后值逐字节一致。参数比较仅统一新旧名称,并移除 attention sink 新增的尾部单维。
127+捕获的第 0 层 attention 输出梯度仍有正负零的位表示差异,数值差为 0;
128+因此该结论限定为首步训练指标、参数梯度和参数更新,不表示所有中间张量的原始位模式相同。
129+修复后的 10/50 步尚未验证,不能由首步结果推断多步精度或完整收敛。
130+此前关闭激活重计算的 4K 配置曾出现 OOM,该记录不适用于当前全量重计算配置。
131+训练步数、上下文长度和 token 预算统一在自定义 Python 配置中设置,
132+本入口不再读取 `STEPS`、`MAX_CONTEXT_LENGTH`、`TOKENS_PER_MICROBATCH`、
133+`TOKENS_PER_STEP` 或 `MAX_NUM_DOCUMENTS`。
134+ 
135+运行前按安装指南设置 `ASCEND_SET_ENV_PATH` 指向 1104 CANN。需要 profiling 时在自定义 Python 配置函数中设置 `config.profiler.enable_profiling=True`。
136+ 
109### 32P Pro 32-expert Debug137### 32P Pro 32-expert Debug
110 138 
111Pro 32-expert 是独立的裁剪模型 debug/performance 入口,不与 8P Flash launcher 强制复用:139Pro 32-expert 是独立的裁剪模型 debug/performance 入口,不与 8P Flash launcher 强制复用:
@@ -113,7 +141,6 @@ Pro 32-expert 是独立的裁剪模型 debug/performance 入口,不与 8P Flas
113```sh141```sh
114NODE_IPS="${NODE_IPS}" \142NODE_IPS="${NODE_IPS}" \
115bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \143bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
116- --debug.moe-force-load-balance \
117 --training.steps 20144 --training.steps 20
118```145```
119 146 
@@ -127,7 +154,6 @@ bash examples/deepseek_v4/debug/deepseek_v4_pro_32p_cpt_4k_a5.sh \
127 --training.max-context-length 131072 \154 --training.max-context-length 131072 \
128 --training.num-tokens-per-microbatch-per-dp-rank 131072 \155 --training.num-tokens-per-microbatch-per-dp-rank 131072 \
129 --training.num-tokens-per-train-step 1048576 \156 --training.num-tokens-per-train-step 1048576 \
130- --debug.moe-force-load-balance \
131 --training.steps 20157 --training.steps 20
132```158```
133 159 
@@ -139,8 +165,7 @@ debug 默认关闭 checkpoint。先在 `my_recipes.py` 中定义需要 checkpoin
139 165 
140```python166```python
141from torchtitan.components.checkpointer import CheckpointManager167from torchtitan.components.checkpointer import CheckpointManager
142-from torchtitan_npu.models.deepseek_v4.config_registry import deepseek_v4_flash_43layers_16experts_compiled168+from torchtitan_npu_recipes.models.deepseek_v4 import deepseek_v4_flash_43layers_16experts_compiled
143- 
144 169 
145def debug_checkpoint():170def debug_checkpoint():
146 config = deepseek_v4_flash_43layers_16experts_compiled()171 config = deepseek_v4_flash_43layers_16experts_compiled()
@@ -189,7 +214,6 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
189```sh214```sh
190NODE_IPS="${NODE_IPS}" \215NODE_IPS="${NODE_IPS}" \
191bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \216bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
192- --debug.moe-force-load-balance \
193 --training.steps 20217 --training.steps 20
194```218```
195 219 
@@ -205,7 +229,6 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
205 --training.max-context-length 65536 \229 --training.max-context-length 65536 \
206 --training.num-tokens-per-microbatch-per-dp-rank 131072 \230 --training.num-tokens-per-microbatch-per-dp-rank 131072 \
207 --training.num-tokens-per-train-step 8388608 \231 --training.num-tokens-per-train-step 8388608 \
208- --debug.moe-force-load-balance \
209 --training.steps 20232 --training.steps 20
210```233```
211 234 
@@ -216,7 +239,6 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a5.sh \
216```sh239```sh
217NODE_IPS="${NODE_IPS}" \240NODE_IPS="${NODE_IPS}" \
218bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \241bash examples/deepseek_v4/deepseek_v4_flash_cpt_1024k_a5.sh \
219- --debug.moe-force-load-balance \
220 --training.steps 20242 --training.steps 20
221```243```
222 244 
@@ -4,162 +4,12 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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 a single node.
8-# Append CLI arguments to override the defaults below:
9-# ./examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh --training.steps 5
10-# USE_GOLDEN=1 selects Golden. For deterministic execution, append
11-# --debug.seed 42 --debug.deterministic to the command line.
12- 
13set -euo pipefail7set -euo pipefail
14-export TORCHTITAN_ENGRAM_TABLE_ROWS="${TORCHTITAN_ENGRAM_TABLE_ROWS:-100000}"
15 8 
16-NGPU="${NGPU:-8}"9+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
17-WORLD_SIZE="${NGPU}"
18 10 
19-# Model11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4_1}" \
20-MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"12+CONFIG="${CONFIG:-deepseek_v4_1_flash_8p_cpt_4k_a3}" \
21-CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal_compiled}"13+NGPU="${NGPU:-8}" \
22- 14+NNODES="${NNODES:-1}" \
23-# Dataloader15+exec bash "${SCRIPT_DIR}/../../../scripts/run_train.sh" "$@"
24-DATASET="${DATASET:-cc12m-test}"
25-DATASET_PATH="${DATASET_PATH:-}" # optional; unset keeps the upstream dataset source
26-HF_ASSETS_PATH="${HF_ASSETS_PATH:-/path/to/DeepSeekV41_tokenizer}" # your tokenizer path
27- 
28-# Parallelism
29-TP=1
30-PP=1
31-EP=8
32-CP=1
33-DP_SHARD=8
34-DP_REPLICATE=$((WORLD_SIZE / (DP_SHARD * CP * TP * PP)))
35- 
36-# Training
37-# Retain the validated eager / Muon / FullAC resource crop.
38-SEQ_LEN=4096
39-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=4096
40-NUM_TOKENS_PER_TRAIN_STEP=32768
41-STEPS=40
42- 
43-# Debug
44-USE_GOLDEN="${USE_GOLDEN:-0}"
45-DEBUG_ARGS="
46- --debug.print-config
47- --debug.moe-force-load-balance
48-"
49- 
50-# HF assets
51-HF_ASSETS_ARGS="
52- --hf-assets-path ${HF_ASSETS_PATH}
53-"
54- 
55-# Native Grain dataset configuration is selected when the recipe is constructed.
56-export DATASET DATASET_PATH
57-export PACKING_BUFFER_SIZE="${PACKING_BUFFER_SIZE:-0}"
58- 
59-# Parallelism
60-PARALLELISM_ARGS="
61- --parallelism.data-parallel-shard-degree ${DP_SHARD}
62- --parallelism.data-parallel-replicate-degree ${DP_REPLICATE}
63- --parallelism.expert-parallel-degree ${EP}
64- --parallelism.tensor-parallel-degree ${TP}
65- --parallelism.context-parallel-degree ${CP}
66- --parallelism.pipeline-parallel-degree ${PP}
67- --parallelism.fsdp-reshard-after-forward always
68- --parallelism.enable-sequence-parallel
69-"
70- 
71-# Compilation policy is declared by the selected Python recipe.
72- 
73-# Training
74-TRAINING_ARGS="
75- --training.num-tokens-per-microbatch-per-dp-rank ${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}
76- --training.num-tokens-per-train-step ${NUM_TOKENS_PER_TRAIN_STEP}
77- --training.max-context-length ${SEQ_LEN}
78- --training.steps ${STEPS}
79- --training.disable-cuda-graphs
80- --metrics.log-freq 1
81-"
82- 
83-# LR scheduler
84-LR_SCHEDULER_ARGS="
85- --optim.lr-scheduler.warmup-steps 2
86- --optim.lr-scheduler.total-steps ${STEPS}
87- --optim.lr-scheduler.decay-ratio 1.0
88- --optim.lr-scheduler.decay-type cosine
89- --optim.lr-scheduler.min-lr-factor 0.01
90-"
91- 
92-# Checkpoint policy is declared by the selected Python recipe.
93-CHECKPOINT_ARGS=""
94- 
95-# Profiler
96-PROFILER_ARGS="
97- --profiler.no-enable-profiling
98- --profiler.profile-freq 10
99- --profiler.profiler-active 10
100- --profiler.profiler-warmup 0
101-"
102- 
103-# Communication
104-COMM_ARGS="
105- --comm.init-timeout-seconds 7200
106- --comm.train-timeout-seconds 600
107-"
108- 
109-# Optimizer
110-# AdamW hyperparameters come from the recipe, not from CLI flags.
111-OPTIMIZER_ARGS="
112- --optim.optimizer.name Muon
113- --optim.optimizer.lr 1.0e-5
114- --optim.optimizer.beta1 0.9
115- --optim.optimizer.beta2 0.95
116- --optim.optimizer.eps 1.0e-8
117- --optim.optimizer.weight-decay 1.0e-1
118- --optim.optimizer.muon_momentum 0.95
119- --optim.optimizer.muon_enable_nesterov
120- --optim.optimizer.muon_ns_steps 10
121- --optim.optimizer.muon_adjust_lr_fn match_rms_adamw
122-"
123-OPTIMIZER_OVERRIDES="${OPTIMIZER_OVERRIDES-torchtitan_npu.override.common.optimizer.swap_optimizer}"
124- 
125-# The text-rope entry is a hardware choice: A3 defaults to asc_complex; the A5
126-# wrapper supplies asc_partial through the same CLI_OVERRIDES channel. The fused
127-# sparse attention and its selector also ride this channel, so a wrapper that
128-# already names them does not add a second copy. Set the defaults in both branches
129-# so `set -u` never sees them unbound.
130-if [[ "${USE_GOLDEN}" == "1" ]]; then
131- NPU_OPS_OVERRIDES=(torchtitan_npu.override.common.rope.workaround)
132- DEFAULT_TEXT_ROPE_OVERRIDE=""
133- DEFAULT_FUSED_OVERRIDES=""
134-else
135- DEFAULT_TEXT_ROPE_OVERRIDE="torchtitan_npu.override.common.rope.asc_complex"
136- DEFAULT_FUSED_OVERRIDES="torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc"
137- MHC_POST_OVERRIDE="${MHC_POST_OVERRIDE:-torchtitan_npu.override.deepseek_v4_1.mhc.asc_hc_post}"
138- NPU_OPS_OVERRIDES=(
139- torchtitan_npu.override.common.rms_norm.asc
140- torchtitan_npu.override.common.rope.asc_half_rotation
141- torchtitan_npu.override.common.token_dispatcher.asc
142- ${MHC_POST_OVERRIDE}
143- )
144-fi
145- 
146-# Wrapper defaults extend override.imports after the base targets.
147-CLI_OVERRIDES="${CLI_OVERRIDES:-${DEFAULT_TEXT_ROPE_OVERRIDE} ${DEFAULT_FUSED_OVERRIDES}}"
148- 
149-MODULE="${MODULE}" \
150-CONFIG="${CONFIG}" \
151-NGPU="${NGPU}" \
152-LOG_PREFIX="${LOG_PREFIX:-${CONFIG}}" \
153-bash scripts/run_train.sh \
154- $HF_ASSETS_ARGS \
155- $PARALLELISM_ARGS \
156- $TRAINING_ARGS \
157- $DEBUG_ARGS \
158- $OPTIMIZER_ARGS \
159- $LR_SCHEDULER_ARGS \
160- $PROFILER_ARGS \
161- $COMM_ARGS \
162- $CHECKPOINT_ARGS \
163- --override.imports "${NPU_OPS_OVERRIDES[@]}" $OPTIMIZER_OVERRIDES \
164- $CLI_OVERRIDES ${DATALOADER_OVERRIDES:-} \
165- "$@"
@@ -4,51 +4,13 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# A5 wrapper around the common DeepSeek-V4.1 Flash CPT launcher. Keep the shared
8-# training and parallelism defaults in the A3 script; this entrypoint selects
9-# 24 experts and supplies A5-specific runtime and fused-operator settings.
10-# Append CLI arguments to override the defaults below:
11-# ./examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a5.sh --training.steps 5
12- 
13set -euo pipefail7set -euo pipefail
14 8 
15SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
16- 
17-export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_24experts_multimodal_compiled}"
18- 
19-# Use the command line `npu-smi info -t topo` to query the CPU affinity of the
20-# NPU cards for configuration.
21export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"10export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"
22 11 
23-# A5-only fused ops; USE_GOLDEN=1 keeps the pure reference list.12+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4_1}" \
24-# USE_TILELANG=1 swaps the mHC pre/post entries to the TileLang overrides13+CONFIG="${CONFIG:-deepseek_v4_1_flash_8p_cpt_4k_a5}" \
25-# (swiglu/sparse-attn keep the asc fused path; the PR730/731 tilelang swiglu14+NGPU="${NGPU:-8}" \
26-# and topk adapters are single-rank-validated and reject the EP>1 DTensor15+NNODES="${NNODES:-1}" \
27-# weights this 8p recipe produces).16+exec bash "${SCRIPT_DIR}/../../../scripts/run_train.sh" "$@"
28-if [[ "${USE_GOLDEN:-0}" != "1" ]]; then
29- if [[ "${USE_TILELANG:-0}" == "1" ]]; then
30- export MHC_POST_OVERRIDE=torchtitan_npu.override.deepseek_v4_1.tilelang.tilelang_hc_post
31- export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \
32- torchtitan_npu.override.deepseek_v4_1.tilelang.tilelang_hc_pre \
33- torchtitan_npu.override.common.swiglu_group.asc \
34- torchtitan_npu.override.common.swiglu_group.asc_shared_experts \
35- torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc \
36- torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc}"
37- else
38- export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \
39- torchtitan_npu.override.common.swiglu_group.asc \
40- torchtitan_npu.override.common.swiglu_group.asc_shared_experts \
41- torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc \
42- torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc \
43- torchtitan_npu.override.deepseek_v4_1.mhc.asc_sinkhorn}"
44- fi
45-fi
46- 
47-QUANTIZATION_ARGS=(
48- --extension.quantization.enable-quantized-training
49- --extension.quantization.recipe all_block_fp8
50-)
51- 
52-exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" \
53- "${QUANTIZATION_ARGS[@]}" \
54- "$@" \
@@ -4,38 +4,13 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# A5 wrapper around the common DeepSeek-V4.1 Flash CPT launcher. Keep the shared
8-# model, training, and parallelism defaults in the A3 script; this entrypoint
9-# only supplies A5-specific runtime and fused-operator settings.
10-# This entry enables routed-expert MXFP4 fake quant, V4.1 QLI/QSLI, and
11-# sparse-attention/KV-source Compressor quantization.
12-# Append CLI arguments to override the defaults below:
13-# ./examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_qat_4k_a5.sh --training.steps 5
14- 
15set -euo pipefail7set -euo pipefail
16 8 
17SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
10+export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"
18 11 
19-# The quantized sparse attention (torchao_npu's QuantV41SparseAttention) is its own backend:12+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4_1}" \
20-# its converter-installed config builds the attention entry, so this entry launches no per-layer13+CONFIG="${CONFIG:-deepseek_v4_1_flash_8p_qat_4k_a5}" \
21-# metadata operator. It replaces the node `sparse_attn.asc` targets, so that override (kept14+NGPU="${NGPU:-8}" \
22-# below for the unquantized variants of this list) is a no-op here.15+NNODES="${NNODES:-1}" \
23-# The override list is the non-tilelang fused branch of16+exec bash "${SCRIPT_DIR}/../../../scripts/run_train.sh" "$@"
24-# deepseek_v4_1_flash_8p_cpt_4k_a5.sh -- keep the two lists in sync.
25-export CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rope.asc_partial \
26- torchtitan_npu.override.common.swiglu_group.asc \
27- torchtitan_npu.override.common.swiglu_group.asc_shared_experts \
28- torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc \
29- torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc}"
30- 
31-QUANTIZATION_ARGS=(
32- --extension.quantization.enable-quantized-training
33- --extension.quantization.recipe all_block_fp8
34- --extension.quantization.enable-mxfp4-qat
35- --extension.quantization.li-quantization mxfp4
36- --extension.quantization.enable-sparse-attention-quantization
37-)
38- 
39-exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a5.sh" \
40- "${QUANTIZATION_ARGS[@]}" \
41- "$@" \
@@ -4,11 +4,12 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# Vision-language SFT wrapper around the 8p CPT launcher in this directory.
8set -euo pipefail7set -euo pipefail
9 8 
10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
11-export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"
12-export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_16experts_multimodal_sft_compiled}"
13 10 
14-exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" "$@"11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4_1}" \
12+CONFIG="${CONFIG:-deepseek_v4_1_flash_8p_sft_4k_a3}" \
13+NGPU="${NGPU:-8}" \
14+NNODES="${NNODES:-1}" \
15+exec bash "${SCRIPT_DIR}/../../../scripts/run_train.sh" "$@"
@@ -4,11 +4,13 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# Vision-language SFT wrapper around the 8p A5 CPT launcher in this directory.
8set -euo pipefail7set -euo pipefail
9 8 
10SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"9SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
11-export DSV41_SFT_DATASET="${DSV41_SFT_DATASET:-${DATASET_PATH:-/path/to/train.jsonl}}"10+export CPU_AFFINITY_CONF="${CPU_AFFINITY_CONF:-1,npu0:288-311,npu1:312-335,npu2:336-359,npu3:360-383,npu4:96-119,npu5:120-143,npu6:144-167,npu7:168-191}"
12-export CONFIG="${CONFIG:-deepseek_v4_1_flash_40layers_24experts_multimodal_sft_compiled}"
13 11 
14-exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a5.sh" "$@"12+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4_1}" \
13+CONFIG="${CONFIG:-deepseek_v4_1_flash_8p_sft_4k_a5}" \
14+NGPU="${NGPU:-8}" \
15+NNODES="${NNODES:-1}" \
16+exec bash "${SCRIPT_DIR}/../../../scripts/run_train.sh" "$@"
@@ -4,69 +4,12 @@
4# This source code is licensed under the BSD-style license found in the4# This source code is licensed under the BSD-style license found in the
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-# Single-card DeepSeek-V4.1 with the fused ds41 LightningIndexer.
8-#
9-# The flavor behind this wrapper (`deepseek_v4_1_stripped`) is the flash model with six
10-# layers instead of forty; ``dim``, the attention heads and both released geometries are
11-# untouched, because the MLA attention and the ds41 indexer are both fixed by their kernels.
12-# See ``_stripped`` in ``torchtitan_npu/models/deepseek_v4_1/__init__.py``.
13-#
14-# Six layers is the smallest count that still reaches all three branches of the fused
15-# selector: layer 2 is Full Mode at ratio 2 with the pool off, layer 3 is the Full Mode pool
16-# source at ratio 1, and layer 4 is the Reindex Mode searcher that reads what layer 3 built.
17-# The candidate pool is a ratio-1 mechanism in the released model too -- its source sits at
18-# the first ratio-1 layer -- so this shape does not invent a combination the model lacks.
19-#
20-# Run from the repository root:
21-# NGPU=1 bash examples/deepseek_v4_1/debug/deepseek_v4_1_mini_1p_cpt_a5.sh --training.steps 5
22-#
23-# Append CLI arguments to override the defaults below. `QUANTIZATION_ARGS` enables
24-# the all_block_fp8 training recipe.
25- 
26set -euo pipefail7set -euo pipefail
27 8 
28-export NGPU="${NGPU:-1}"9+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
29-export MODULE="${MODULE:-torchtitan_npu.models.deepseek_v4_1}"
30-export CONFIG="${CONFIG:-deepseek_v4_1_stripped}"
31-export PYTHONUNBUFFERED=1
32-export TORCHTITAN_ENGRAM_TABLE_ROWS="${TORCHTITAN_ENGRAM_TABLE_ROWS:-100000}"
33 10 
34-# The fused operators this flavor exists to exercise. `sparse_attn.asc` is not optional11+MODULE="${MODULE:-torchtitan_npu_recipes.examples.deepseek_v4_1}" \
35-# alongside `lightning_indexer.asc`: the indexer is trained purely through the teacher that12+CONFIG="${CONFIG:-deepseek_v4_1_mini_1p_cpt_a5}" \
36-# SMLA's backward emits, and the model refuses a half-fused stack rather than training an13+NGPU="${NGPU:-1}" \
37-# indexer that never receives a gradient.14+NNODES="${NNODES:-1}" \
38-#15+exec bash "${SCRIPT_DIR}/../../../scripts/run_train.sh" "$@"
39-LIGHTNING_INDEXER_OVERRIDE="torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc"
40- 
41-# Enable block FP8 quantized training.
42-QUANTIZATION_ARGS=(
43- --extension.quantization.enable-quantized-training
44- --extension.quantization.recipe all_block_fp8
45-)
46- 
47-CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rms_norm.asc \
48- torchtitan_npu.override.common.rope.asc_complex \
49- torchtitan_npu.override.deepseek_v4_1.mhc.asc_hc_post \
50- ${LIGHTNING_INDEXER_OVERRIDE} \
51- torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc}"
52- 
53-SEQ_LEN=2048
54-NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK=2048
55-NUM_TOKENS_PER_TRAIN_STEP=2048
56- 
57-exec bash scripts/run_train.sh \
58- --hf-assets-path "${HF_ASSETS_PATH:-tests/assets/deepseek_v3}" \
59- --training.num-tokens-per-microbatch-per-dp-rank "${NUM_TOKENS_PER_MICROBATCH_PER_DP_RANK}" \
60- --training.num-tokens-per-train-step "${NUM_TOKENS_PER_TRAIN_STEP}" \
61- --training.max-context-length "${SEQ_LEN}" \
62- --training.steps "${STEPS:-5}" \
63- --parallelism.data-parallel-shard-degree 1 \
64- --parallelism.data-parallel-replicate-degree 1 \
65- --parallelism.expert-parallel-degree 1 \
66- --parallelism.tensor-parallel-degree 1 \
67- --parallelism.pipeline-parallel-degree 1 \
68- --parallelism.context-parallel-degree 1 \
69- --metrics.log-freq 1 \
70- --override.imports ${CLI_OVERRIDES} \
71- "${QUANTIZATION_ARGS[@]}" \
72- "$@"
Rtests/unit_tests/models/test_deepseek_v32_mtp_model.py→tests/unit_tests/models/deepseek_v3_2/test_deepseek_v32_mtp_model.py+0-0
Rtests/unit_tests/models/test_deepseek_v4_mtp_model.py→tests/unit_tests/models/deepseek_v4/test_deepseek_v4_mtp_model.py+192-229