Skip to content

feat(deepseek_v32): TP/CP/EP/FSDP integration with MoE balancing and indexer training - #320

Open
hf1s wants to merge 20 commits into
masterfrom
feat/deepseek-v32
Open

hf1s wants to merge 20 commits into
masterfrom
feat/deepseek-v32

Conversation

@hf1s

@hf1s hf1s commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

What type of PR is this?
/kind feature


What does this PR do / why do we need it:

在 master 已有的 DeepSeek-V3.2 DSA 替换和 CP wrapper 基础上,补齐 512 卡训练配方、拼行文档的边界传递和单卡裁剪示例,并按 MindSpeed-LLM 的 DeepSeek-V3.2 预训练脚本(examples/mcore/deepseek32/pretrain_deepseek32_671b_4k_A3_ptd.sh)补齐 MTP 以外的训练目标:序列级负载均衡 loss、专家 bias 更新、indexer KL,并给出与 MindSpeed-LLM 做 loss 对比的配置。模型直接用 Transformers 的 DeepseekV32ForCausalLM,训练相关逻辑都以 adapter 的模块替换和 provider 接入,全部在 hyper_parallel/models/deepseek_v32/ 和 examples/training_demo/deepseek_v32/;不修改框架代码(components/、distributed/、core/、trainer/ 与 master 一致)。

  • 修复(CP wrapper):hyper_parallel.components.functional 按子模块同名懒导出 dsa_indexer / dsa_sparse_attention。master 的 DSA CP wrapper 直接 import 这两个子模块,包里同名属性随之变成模块对象;解析配方会先 import CP wrapper,DSA 模块随后从包里拿到的就是模块,cp_size=1 时第一次 DSA 前向报 TypeError: 'module' object is not callable(master 的配方同样受影响)。CP wrapper 改为从包导入。
  • adapter:
    • 训练版 router:adapter/aux_loss.py 与 DeepSeek-V4.1 的 adapter/aux_loss.py 同名同接口(sequence_load_balancing_loss、在 backward 中计数的 accumulate_router_load、update_correction_bias);router 替换模块在 adapter/conversion/router.py,按 DeepseekV41TopKRouter 的方式经 _apply_router_training_state 接入,配方里替换 *.mlp.gate,参数写在替换条目里。专家选择直接沿用 Transformers router 的 forward(sigmoid + bias、分组 top-k);序列级负载均衡 loss 按 Megatron seq_aux_loss,统计实际选中的专家(公式与 V4.1 相同;V4.1 统计不含 bias 的 top-k),分数用不含 bias 的归一化 sigmoid,CP 下跨 rank 归约;每个 micro-batch 的专家负载在 backward 中只计一次(重计算不重复),Trainer 的 MoE monitor 每个优化步执行 bias += rate * sign(mean_load - load)。
    • DSA 替换增加 dsa_loss_coeff 选项,设置框架 DSA 已有的 indexer KL loss 系数。
    • EP 用 adapter 自己的 deepseek_v32_ep_compute_fn(与 Qwen3-MoE 的写法相同,组合框架的 build_ep_compute),直接使用 router 返回的专家与门控值(topk_router_module):框架内置的 DeepSeek-V3 工厂会从 logits 重新推导路由,丢掉挂在门控值上的负载均衡 loss(实测 TP2+EP2 用例在负载均衡系数 0.1 时梯度不一致、为 0 时一致)。
    • external_state provider 在分片后绑定 router 的 CP 通信组和 loss parallel 下的 TP 份数;TP>1 且开启 indexer KL 时直接报错(KL teacher 需要全部注意力头,TP 会把头切到不同 rank)。
    • materialization:meta 初始化后重算 RoPE 的 inv_freq / original_inv_freq(与 Qwen3.5 的写法相同),修复之前列为已知问题的 NaN / 全 0。
    • DeepseekV32PackedSequence 把拼行文档的全局 cu_seq_lens 以 cu_seq_lens_q/k 传给 DSA(DSA 只检查稠密 mask 的形状、不读内容,没有它会跨文档做 attention)。
  • recipe:recipes/train.yaml 为 512 卡主线配方。dense 区域 dp_shard 512;专家区域 ep 64、edp_shard 4 × 副本 2,每卡每个 MoE 层 1 个专家;EP 作用于 3-60 层;FP32 参数、BF16 计算、FP32 规约;训练目标默认开启:负载均衡 loss 1e-4、专家 bias 1e-3、indexer KL 1.0。数据用 FixedBatchDataLoader(默认 wikitext-2 逐行,只用于跑通流程)。配方随 wheel 打包。
  • MindSpeed-LLM 对比配置 recipes/align_mindspeed.yaml:index_topk 1024、KL 1.0、负载均衡 loss 1e-4、专家 bias 1e-3、AdamW lr 1e-5 cosine 到 1e-7 无 warmup、weight decay 0.01、RMSNorm 权重 FP32;两边读同一份 Megatron .bin/.idx(seed 1234、split 100,0,0、seq 4096)。不训练 MTP,MindSpeed 侧需去掉 --mtp-num-layers / --mtp-loss-scaling-factor;MindSpeed 的 indexer Hadamard 旋转是正交变换,不改变打分。examples/training_demo/README.md 写明两边需要一致的准备(FP8 权重先反量化为 BF16、权重转换的并行布局、数据、确定性开关)和日志指标的对应关系。
  • 单卡示例:examples/training_demo/deepseek_v32/ 只有 train_single_card.yaml 和 run_single_card.sh。YAML 用 HyperAutoModelForCausalLM.from_config,通过 AutoConfig.from_pretrained 的覆盖项把官方 config 裁成 2 层(1 dense + 1 MoE)和 16 个路由专家(保持官方 n_group=8 / topk_group=4 / top-8 路由的最小专家数),共 3.40B 参数;启动脚本需要传入模型目录和文本 JSONL。
  • 测试:
    • CPU 参考 DSA kernel(tests/common/dsa_reference_kernels.py,模拟 CANN 入口)。
    • adapter 契约 UT;router UT:选择与负载均衡 loss/梯度对照逐样本参考实现、bias 更新与重计算不重复计数。
    • CPU/Gloo 并行一致性 ST:走 Trainer 链路(plan_overrides → 模块替换 → ShardingPlanner → apply_sharding_plan → external-state → FSDP2),router 替换来自 plan_overrides,比较 loss、全部梯度和专家负载。
  • 文档:feature_status 列出该模型,并行策略分析 skill 补充 DSA 参数,examples/training_demo/README.md 补充单卡示例和 MindSpeed-LLM 对比说明。

不包含 PP:Trainer 目前不支持流水线并行,recipe 保持 pp_size: 1。不包含 SP:DSA 暂不支持 sequence parallel,recipe 保持 sequence_parallel: false。不包含 MTP:Transformers 的 DeepSeek-V3.2 加载时忽略第 61 层 MTP,本 PR 不训练 MTP。


Which issue(s) this PR fixes:

无


Test Plan and Test result:What scenarios were tested, and what were the verification results(Function, performance, reliability, etc.):

本地 macOS CPU(torch 2.14.1、transformers 5.20.2),基于 master 342923d5:

  • ST tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py(CPU/Gloo,DSA 用 CPU 参考 kernel,FSDP2 实际生效):4/4 通过。模型为 Transformers 的 DeepSeek-V3.2 加训练版 router(负载均衡系数 0.1、开启专家 bias),loss、每个 rank 上所有有梯度的参数和专家负载都与单进程模型一致:
    • CP2 + DSA
    • CP2 + DSA + 拼行文档(文档跨 CP 切分点,边界来自 DeepseekV32PackedSequence)
    • TP2 + loss parallel + EP2 + DSA(cp_size=1,走 DSA 本体前向;CP wrapper 改回直接 import 子模块时实测报 TypeError: 'module' object is not callable)
    • TP2 × CP2 + EP4 + DSA
  • UT:DeepSeek-V3.2 UT 6 个通过(2 个 subtest)。tests/ut/auto_models、components、trainer、distributed、models 等合跑:827 通过;1 个失败(deepseek_v41/test_checkpoint_mapping.py 的 macOS /private 路径比较)和 21 个收集错误(本机缺 PIL、matplotlib 等)在改动前同样存在。
  • 单卡示例的裁剪:用官方 config.json 按 YAML 的覆盖项构建(meta 设备):2 层,层类型 [dense, sparse],16 个路由专家,3.40B 参数。
  • Trainer 冒烟:单卡 YAML 的结构(官方 config 缩小宽度 + 官方 tokenizer,CPU 参考 kernel;去掉只能在 NPU 上运行的 RMSNorm / GroupedExperts 替换,KL 只有 CANN 实现因此系数置 0),经 TextTrainer.train() 运行:from_config + meta 初始化构建 Transformers 类,第 1 层 router 为训练版,inv_freq 有限且非零,foundation_loss 11.77 / 11.78,router_aux_loss ≈ 1.00,每个优化步 router bias 按 ±1e-3 更新(Online 数据集按 train_iters × global_batch_size 取 6 条记录,拼行后在 drop_last 下够 2 步)。
  • TP 与 KL:TP2 且 dsa_loss_coeff 非 0 时构建阶段报 NotImplementedError;KL 为 0 或单进程时正常。
  • 配方:三个 YAML(主线配方、MindSpeed 对比配置、单卡示例)都能被 Trainer 解析。

未在本机验证(需要 NPU):NPU 上的 FSDP 分片、GroupedExperts、RMSNorm 和 DSA 融合算子(含只有 CANN 实现的 indexer KL loss)、512 卡显存,以及与 MindSpeed-LLM 的 loss 对比。


Self-checklist:(请自检,在[ ]内打上x,我们将检视你的完成情况,否则会导致pr无法合入)

  • 设计:PR对应的方案是否已经经过Maintainer评审,方案检视意见是否均已答复并完成方案修改
  • 测试:PR中的代码是否已有UT/ST测试用例进行充分的覆盖,新增测试用例是否随本PR一并上库或已经上库
  • 验证:PR描述信息中是否已包含对该PR对应的Feature、Refactor、Bugfix的预期目标达成情况的详细验证结果描述
  • 接口:是否涉及对外接口变更,相应变更已得到接口评审组织的通过,API对应的注释信息已经刷新正确
  • 文档:是否涉及官网文档修改,如果涉及请及时提交资料到Doc仓

@hf1s
hf1s force-pushed the feat/deepseek-v32 branch 3 times, most recently from 703ed6a to 3bd95fe Compare October 28, 2026 07:31
@hf1s hf1s changed the title feat(deepseek_v32): complete TP/SP/CP/EP/FSDP integration feat(deepseek_v32): complete TP/CP/EP/FSDP integration Oct 28, 2026
- add the DeepSeek-V3.2 EP compute factory on the router's own top-k
  decision, the packed-document runtime input adapter and the q_a/kv_a TP
  roles; reject the DSA indexer KL loss together with TP
- ship a 512-card recipe with CP/EP plan overrides scoped to MoE layers,
  the FP32-main precision policy and the packaged-recipe wheel entry
- add CPU reference DSA kernels, adapter contract UT and CPU/Gloo
  TP/CP/EP parity ST
- list the model in the READMEs and feature status and document the DSA
  parameters for the parallel-strategy analyzer
@hf1s
hf1s force-pushed the feat/deepseek-v32 branch from 3bd95fe to 57a9e18 Compare November 9, 2026 06:44
@hf1s

hf1s commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

已 rebase 到 master 342923d5(2026-11-09)

分支已强推(3bd95fe1 → 57a9e185),仍是单个提交,相对 master 共改 14 个文件。master 期间的变化需要的适配都已并入该提交:

  • plan_overrides 改用 master 的 replace: 写法(b3393208)。
    • 三条模块替换改为 kind: module,module_type 与 master 一样去掉。
    • CP 条目沿用 master 的写法:*.self_attn.forward + kind: method + dense_warmup: null(12bf9f48)。
    • 两条 EP 条目改为 model.layers.[3-9].mlp.forward / model.layers.[1-9][0-9].mlp.forward + kind: method。region_dispatch: false 现在是 forward 方法替换的默认值,不再显式写。
    • 并行 ST 的 _plan_overrides 同步改写。
  • master 的 DSA 模块和 CP wrapper 固定走 backend="cann"(12bf9f48),所以 tests/common/dsa_reference_kernels.py 改为模拟 CANN 入口:
    • indexer:ops-transformer LI V2 的 lightning_indexer / lightning_indexer_metadata。
    • 稀疏 attention 前向:torch_npu.npu_sparse_flash_attention。
    • 稀疏 attention 反向:sparse_flash_attention_grad,用 autograd 重算前向,K/V 共用一个张量时两份梯度合并到 key。
    • CANN 封装在调用时才 import,所以替身模块在 context 期间留在 sys.modules,退出时清理并恢复。
    • 旧的 torch.ops.custom.*_enhance 替身已删除。
  • README / README.en 的改动已去掉:master docs: add supported models and acknowledgements mindspore-ai/hyper-parallel#1415 新增的支持模型表已经收录 DeepSeek-V3.2。

rebase 后的验证(本地 macOS CPU,torch 2.14.1 + transformers 5.20.2)

  • tests/ut/auto_models/models/deepseek_v32:6 passed / 2 subtests。适配前有 3 个 DSA 用例报 ModuleNotFoundError: cann_ops_transformer。
  • tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py(Gloo):4 passed。
  • 相邻用例(tests/ut/components/functional/test_dsa_*、test_shared_compressed_dsa_attention.py、test_models_skeleton.py、test_inline_adapters.py、test_plan_overrides.py)和本 PR 用例放在同一进程里,正反两种顺序各跑一遍:48 passed / 31 passed。
  • 没有重跑 UT 全量。描述里“UT 全量 47 failed / 48 errors”是 rebase 前在 932c7b8a 上的结果。
  • label-check 失败是推送新提交后的预期行为(等 CI 打新的通过标签),与代码无关。

hf1s added 2 commits November 9, 2026 01:28
The CANN DSA wrappers import torch_npu and cann_ops_transformer at call time, so the stand-ins stay in sys.modules for the whole reference_dsa_kernels context. A Transformers integration imported lazily inside the context probes importlib.util.find_spec("torch_npu"), which raised ValueError on a stand-in without __spec__. Give every stand-in a ModuleSpec so such probes see a device-less package.
examples/training_demo/deepseek_v32 builds DeepSeek-V3.2 from the released config with from_config and random weights, cropped to two layers (one dense, one MoE) and 16 routed experts, the fewest that keep the released n_group/topk_group/top-8 routing (3.40B parameters). The per-layer mlp_layer_types/layer_types lists are re-derived for the cropped depth and the FP8 quantization_config is dropped. The launcher generates documents that split into full 4096-token windows (indexer top-k active) and short tails that pack into one row (packed boundaries through DeepseekV32PackedSequence).
@hf1s

hf1s commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

新增 2 个提交(512000ab、9d258643)

  1. 512000ab test(deepseek_v32): give DSA reference stand-ins module specs
    • CANN 封装在调用时才 import,所以替身模块在 context 期间一直留在 sys.modules 里。
    • context 内第一次 import 的 Transformers 集成模块会调用 importlib.util.find_spec("torch_npu")。替身没有 __spec__ 时会报 ValueError: torch_npu.__spec__ is None,在 context 内解析单卡 YAML 时就遇到了。
    • 修复:给每个替身补上 ModuleSpec。
  2. 9d258643 feat(deepseek_v32): add single-card cropped training example
    • examples/training_demo/deepseek_v32/cropped_deepseek_v32.py:读官方 config,用 from_config 随机初始化,裁成 2 层(1 dense + 1 MoE)和 16 个路由专家,共 3.40B 参数。
      • mlp_layer_types / layer_types 由 DeepseekV32Config.__post_init__ 按层数派生。直接改 num_hidden_layers 会留下官方 61 层的列表,第 1 层就成了 dense,所以按裁剪后的层数重新派生。
      • 去掉 FP8 quantization_config。
      • 专家数不满足分组路由时直接报错。
    • train_single_card.yaml:模块替换和拼行数据路径与完整配方一致,不带 CP/EP 条目。
    • run_single_card.sh 和 prepare_single_card_data.py:只读官方目录里的 config.json 和 tokenizer。生成的每条记录切成两个完整的 4096 token 窗口和一个 1049 token 的尾巴:
      • 完整窗口是单文档,长度超过 index_topk=2048,会走 indexer 的稀疏选择。
      • 3 条尾巴拼成一行,会走拼行文档边界。
    • tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py:检查裁剪后第 1 层是 16 专家的 MoE、宽度不变、FP8 配置被去掉;8 个和 12 个专家会报错。把派生字段改回沿用官方列表的写法后,该用例会失败。
    • examples/training_demo/README.md 补充说明;完整配方头部注释指向单卡示例。

验证(本地 macOS CPU,torch 2.14.1 + transformers 5.20.2)

  • DeepSeek-V3.2 UT、Gloo 并行 ST 和 DSA 算子 UT:15 passed / 4 subtests。
  • 用官方 config.json 裁剪:3.40B 参数;第 0 层是 DeepseekV32MLP,第 1 层是 16 专家的 DeepseekV32MoE;yarn RoPE 参数保留。
  • 单卡 YAML 经 Trainer 配置解析器解析通过:3 条模块替换,单卡下没有生效的切分规则。
  • 端到端冒烟:同一份 YAML 走 TextTrainer.train() 跑 3 步。
    • loss 依次为 11.7729、11.7731、11.7533(约等于 ln 129280,符合随机初始化),grad_norm 有限。
    • RoPE inv_freq 有限,且与 HF 计算的一致。
    • DSA indexer 收到 8 次单文档 4096 token 的行,以及 4 次 3 文档拼接的行 cu_seqlens=[0, 1049, 2098, 3147]。
    • 为了能在 CPU 上跑,做了这些改动:宽度缩小到 hidden 64(层数、路由、indexer、词表、RoPE 与官方相同);去掉只能在 NPU 上跑的 RMSNorm / GroupedExperts 替换;跳过 FSDP(fully_shard 不支持 CPU);DSA 用 CPU 参考算子。
  • 未执行:NPU 真机(CANN 9.2 + ops-transformer)。约 51 GiB 的显存估算没有实测。

hf1s added 4 commits November 9, 2026 02:38
hyper_parallel.components.functional exports dsa_indexer, dsa_sparse_attention, dsa_kl_loss, dsa_sparse_attention_rescale and aggregate_hidden under their submodules' names. Once such a submodule is imported first, the package attribute is the module object. Parsing the DeepSeek-V3.2 recipe imports the CP wrapper, which imports the dsa_indexer and dsa_sparse_attention submodules, so DeepseekV32DSAAttention then bound the modules and its first forward at cp_size=1 raised TypeError: 'module' object is not callable. Import these functions from their submodules.
tests/ut/rl/conftest.py puts hyper_parallel/rl on sys.path, where examples is a regular package. Importing examples.training_demo by name bound whichever examples package a pytest session imported first, breaking either the RL tests or this test.
…ing note

TokenBatchLoader packed several short wikitext lines into one row while the Online dataset holds train_iters x global_batch_size records, so the recipe ran 1 of 3 steps (0 with cp_size=2). Use FixedBatchDataLoader: every rank now gets one record per micro-batch and all 3 steps run. edp_shard_size 8 split 4 local experts over 8 ranks and left half of them holding padding; edp_shard_size 4 gives one expert per MoE layer per rank. Correct the memory note (about 2.55B expert params, about 41 GB), the TP example (dp_shard_size must follow dp) and the divisibility rules, point EP at the built-in DeepSeek-V3 factory (identical router), and drop the redundant create_attention_mask_in_dataloader flag. feature_status states what is verified.
… every gradient through FSDP

Remove deepseek_v32_ep_compute_fn and its unused expert_parallel provider: the built-in deepseekv3_ep_compute_fn routes identically. Remove the indexer-KL/TP guard (no shipped config enables the KL loss) and the q_a_proj/kv_a_proj_with_mqa TP rule, which only served the sequence-parallel test on Transformers attention; that test goes too, since DSA does not support SP.

The Gloo parity worker now applies the real FSDP2 manager (device patched to CPU), backpropagates the raw loss and compares every gradient, including gradient presence, for CP2, CP2 with packed documents straddling the CP split, TP2+EP2+loss parallel and TP2xCP2xEP4. The previous worker divided the loss by tp only under SP and skipped gradients for TP+DSA. reference_dsa_kernels no longer pre-imports the DSA modules, so the tests run the real import order (the cp_size=1 case fails without the previous fix), and it restores lazily imported packages on exit.
@hf1s

hf1s commented Nov 9, 2026

Copy link
Copy Markdown
Owner Author

按 review 叠加 4 个提交(9d258643..775c3002)

  1. 02cfbab4 fix(dsa):dsa_attention.py 从各自的子模块 import 同名的 DSA 函数。之前解析配方会先 import CP wrapper,cp_size=1 时第一次 DSA 前向报 TypeError: 'module' object is not callable,master 的配方同样受影响。
  2. c97bdb0a test:单卡裁剪 UT 改为按文件路径加载示例代码。原来的写法和 tests/ut/rl 的 examples 包同名冲突,一起跑时会有一方收集失败。
  3. b6e26fb7 fix(recipe):
    • 换成 FixedBatchDataLoader。原来 3 步只跑 1 步,开 cp_size=2 时一步优化器更新都没有。
    • edp_shard_size 由 8 改为 4。原来一半的 rank 只存补齐用的空数据。
    • 修正显存注释(专家约 2.55B 参数 / 约 41 GB)、TP 示例和整除约束。
    • EP 改用内置的 deepseekv3_ep_compute_fn。
    • 缩小 feature_status 里的说法。
  4. 775c3002 refactor + test:
    • 删掉 deepseek_v32_ep_compute_fn 及其 provider、KL+TP 检查、q_a/kv_a 切分规则,以及只为它服务的 SP + HF attention 用例。
    • 并行 ST 改为套用真实的 FSDP2(device 打补丁到 CPU)、反传原始 loss、比较全部梯度(包括梯度是否存在),并新增 CP2 + 拼行文档用例。
    • dsa_reference_kernels 不再预先 import DSA 模块,测试走真实的 import 顺序;退出时也会还原在 context 内首次 import 的包。

验证(本地 CPU):DeepSeek-V3.2 的 UT、Gloo ST 和 DSA 算子 UT 共 13 passed / 4 subtests。去掉第 1 个修复后,cp_size=1 的 ST 报 TypeError;去掉 FSDP2 后,ST 在 embed_tokens 的梯度上失败。tests/ut 的 auto_models、components、rl、trainer 合跑,与改动前相比没有新增失败。中间提交 b6e26fb7 也单独跑过,全部通过。

hf1s added 5 commits November 9, 2026 02:50
…ents

Drop delivery and process notes from the recipe header ("only delivered recipe", "no second config to maintain", "verify on the target cluster", "planner gives a clear error") and state the default data plainly. Generalize the dsa_attention import comment instead of naming one caller.
…lel heads

- index_rotate_activation applies the orthonormal Sylvester Hadamard rotation
  to indexer queries and keys after RoPE, as DeepSeek-V3.2 and MindSpeed-LLM
  (--use-fused-lightning-indexer) score them.
- The KL teacher sums attention over all heads. Under tensor parallelism the
  sparse and dense KL paths gather the head shards (queries, rotary parts and
  softmax statistics) over kl_head_group; a TP-sharded module without the group
  raises instead of training against a partial teacher.
- The KL loss is divided by kl_loss_tp_replicas, the TP ranks whose identical
  gradients loss parallelism sums, and last_indexer_loss records it for logging.
DeepseekV32TrainingForCausalLM extends the Transformers model with the
objectives of DeepSeek-V3.2 pretraining, following Megatron-LM semantics:

- Router: the released sigmoid group-limited selection with the load bias;
  the sequence-wise balance loss is computed per sample on the selected
  experts with bias-free normalized scores, reduced over context-parallel
  ranks. Routers count expert loads (not during recomputation) and the
  Trainer's MoE monitor applies bias += rate * sign(mean_load - load).
- MTP: num_nextn_predict_layers depths built from the shared MTP layer on
  the pre-final-norm hidden states; inputs and targets roll one position per
  depth across context-parallel ranks; the weighted mean loss is returned
  under foundation_loss/mtp. Released layer-61 MTP weights load through the
  registered checkpoint mapping.
- build_model binds the context-parallel and tensor-parallel groups the
  losses reduce over and divides replicated loss-parallel gradients.
- RoPE inverse frequencies are rebuilt after meta initialization.
- EP compute accepts router_fn so the training router drives dispatch.

The recipe and the single-card example build the training model; the
single-card crop keeps MTP off. CPU tests compare routing, balance loss,
bias updates, MTP rolling and checkpoint loading with references; the Gloo
tests check CP, packed CP, TP+EP+loss-parallel and TPxCPxEP against one
device, including all gradients and expert loads.
align_mindspeed.yaml reproduces the objectives and optimizer of MindSpeed-LLM
pretrain_deepseek32_671b_4k_A3_ptd.sh (index top-k 1024, KL weight 1.0 with
the Hadamard rotation, balance loss 1e-4, expert bias 1e-3, one MTP depth at
0.3, AdamW 1e-5 cosine to 1e-7, FP32 RMSNorm weights) on the same Megatron
indexed dataset. The README lists the shared preparation, the determinism
settings and how the logged losses correspond.
…cture

Transformers writes the class name into config.json architectures. A
checkpoint saved from DeepseekV32TrainingForCausalLM therefore named an
architecture with no registered model, so HyperAutoModel fell back to the
Transformers class and rejected the training options, and inference engines
do not recognize it. The training model is now DeepseekV32ForCausalLM, like
the released checkpoint; the round-trip test checks the saved architecture
and that every weight is saved under its released name.

The MTP hidden-state hook now only records during a training forward that
reads it, so evaluation forwards keep no activation alive.
@hf1s hf1s changed the title feat(deepseek_v32): complete TP/CP/EP/FSDP integration feat(deepseek_v32): TP/CP/EP/FSDP integration with MTP, MoE balancing and indexer training Nov 9, 2026
hf1s added 5 commits November 9, 2026 04:44
MindSpeed-LLM's DeepSeek-V3.2 conversion script targets TP 1 with no-op
layers 61-63, while its pretraining script runs TP 4, VPP 2 and no-op layers
7, 62 and 63; the README now gives the conversion flags that match the
training script. The data note states which settings determine the sample
order instead of claiming identical order, and the configuration header
names the README section and the DSA-internal norms that stay in BF16.
The DeepSeek-V3 archetype factory re-derives the routing decision from the
gate logits, which drops the balance loss the training router attaches to
its gate values: with that factory the TP2+EP2 parity case fails on the
gradients at a balance-loss weight of 0.1 and passes at 0.

Instead of adding a router_fn option to the generic factory, the adapter
composes build_ep_compute with the topk_router_module adapter, as Qwen3-MoE
does, and adds the shared experts like DeepseekV32MoE.forward. The generic
EP recipes are unchanged from master.
… groups in the adapter

The registered custom class already makes HyperAutoModelForCausalLM.from_config
and from_pretrained build the training model, with the training options passed
to its constructor, so the recipes and the cropped example call the framework
entry points again and the model-package build_model is removed.

Its other task, binding the CP/TP groups of the MTP halo exchange, the balance
loss and the indexer KL loss, moves to the adapter's external-state provider:
the framework calls it after sharding with the run's MeshContext, and it
returns no external state. The Gloo worker runs that build stage instead of
binding the groups itself.
…framework DSA module

components/modules/dsa_attention.py is back to master. The training options
move to DeepseekV32TrainingDSAAttention in the adapter, which the replacement
factory now builds:

- index_rotate_activation: Hadamard rotation of the indexer query and key;
- the sparse-path KL teacher over all heads when TP shards them, divided by
  the loss-parallel TP replicas;
- last_indexer_loss for the dsa_indexer_loss metric.

The dense warm-up path keeps the released behaviour; with the KL loss on it
rejects TP-sharded heads instead of training against a partial teacher.

The module-object import failure is fixed where it starts: the CP wrapper
imported dsa_indexer and dsa_sparse_attention from their submodules, which
leaves the submodule objects under those names in the lazily exporting
package that DeepseekV32DSAAttention imports from. With those imports the
TP2+EP2 parity case (cp_size=1) fails with "TypeError: 'module' object is not
callable"; importing through the package, it passes.
…er replacements

The model is the Transformers DeepseekV32ForCausalLM again, as for
Qwen3-MoE; modeling_deepseek_v32.py, MTP and its checkpoint mapping are
removed.

- The training router (sequence-wise balance loss, expert-load counts for the
  bias update) is a module replacement of *.mlp.gate configured in the recipe;
  the DSA replacement takes the indexer KL weight as dsa_loss_coeff.
- The adapter's external-state provider binds the routers' CP group and
  loss-parallel replicas after sharding, and rejects the KL loss with TP>1.
- The DSA subclass is removed: the Hadamard rotation is orthogonal and leaves
  the indexer scores unchanged, and the KL loss is no longer logged.
- examples/training_demo/deepseek_v32 keeps the single-card YAML, which crops
  the released config through AutoConfig overrides under
  HyperAutoModelForCausalLM.from_config, and its launcher, which now takes the
  JSONL path; the cropped builder, the data generator and their test are
  removed, and the MindSpeed-LLM comparison config moves to the recipes.
- The Gloo parity cases build the Transformers model with training routers and
  apply the router replacement from plan_overrides.
@hf1s hf1s changed the title feat(deepseek_v32): TP/CP/EP/FSDP integration with MTP, MoE balancing and indexer training feat(deepseek_v32): TP/CP/EP/FSDP integration with MoE balancing and indexer training Nov 10, 2026
hf1s added 3 commits November 10, 2026 00:53
…training router

The training router re-implemented the sigmoid, bias, group-limited top-k
selection of DeepseekV32TopkRouter. It now calls the inherited forward and
only adds the training statistics: the balance loss on the sigmoid of the
returned logits and the expert-load counts.
… adapters

Model adapters name their balancing and loss modules after the loss
(deepseek_v41/adapter/aux_loss.py, kimi_k26/adapter/loss.py), so
adapter/router.py becomes adapter/aux_loss.py and its test follows.
…eepSeek-V4.1

adapter/aux_loss.py now provides the helpers of
deepseek_v41/adapter/aux_loss.py under the same names and contracts:
sequence_load_balancing_loss (scores, selected experts, sequence ids,
partition groups), accumulate_router_load, which counts a microbatch's
expert loads once in backward even under recomputation, and
update_correction_bias, the integer sign update that also handles a sharded
bias.

The router replacement moves to adapter/conversion/router.py, the
documented place for module conversions, and applies them through
_apply_router_training_state as DeepseekV41TopKRouter does. It differs where
DeepSeek-V3.2 training differs: the balance loss counts the experts actually
selected, as Megatron-Core's seq_aux_loss and MindSpeed-LLM do (V4.1 counts
the unbiased top-k), there are no modality or token masks, and the loss is
divided by the loss-parallel TP replicas. The load counter stays an
attribute: the replacement executor rejects new registered buffer names
without checkpoint transforms.
@hf1s

hf1s commented Nov 11, 2026

Copy link
Copy Markdown
Owner Author

单卡 200 步对齐结果(910B3 / CANN 9.2)。

代码与配置

  • Hyper-Parallel:本 PR 的 feat/deepseek-v32 完整源码;以 align_mindspeed.yaml 为底,实验副本显式配置 low_level_dataset=GPTDataset、optimizer.swap.enabled=true。
  • MindSpeed-LLM:Ascend/MindSpeed-LLM master;MindSpeed master、FSDPTurbo main、Megatron-LM core_v0.12.1。官方 HF→MG 转换后加载,显式使用 --norm-topk-prob,并用 --finetune 将 iteration / consumed samples 归零,确保完整 200 步。
  • 共同输入:同一份 BF16 初始 checkpoint(2 层 dense→sparse、16 路由专家、3.4007B 参数)和同一份 Megatron .bin/.idx;seq 4096、micro/global batch 1、seed 1234、split 100,0,0。AdamW 1e-5 → 1e-7 cosine,aux loss 1e-4、expert bias 1e-3、indexer KL 1.0、index top-k 1024,无 MTP。未修改训练源码。
  • 运行环境:HP torch/torch_npu 2.12;MindSpeed torch/torch_npu 2.10;Transformers 均为 5.13.1。

结果

指标 第 1 步:HP / MS 第 200 步:HP / MS 平均绝对差 最大绝对差
Loss 13.2622 / 13.26433 7.71924 / 7.729819 0.009833 0.049476(step 153)
Grad norm 13.5638 / 13.561 4.15963 / 4.210 0.057883 0.3837(step 193)

整体接近,但仍有小幅非零差。下图为原始 200 步曲线及 HP − MS 差值:

DeepSeek-V3.2 single-card loss comparison

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant