Repository navigation
Conversation
hf1s
force-pushed
the
feat/deepseek-v32
branch
3 times, most recently
from
October 28, 2026 07:31
703ed6a to
3bd95fe
Compare
- 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
force-pushed
the
feat/deepseek-v32
branch
from
November 9, 2026 06:44
3bd95fe to
57a9e18
Compare
Owner
Author
|
已 rebase 到 master 分支已强推(
rebase 后的验证(本地 macOS CPU,torch 2.14.1 + transformers 5.20.2)
|
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).
Owner
Author
|
新增 2 个提交(
验证(本地 macOS CPU,torch 2.14.1 + transformers 5.20.2)
|
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.
Owner
Author
|
按 review 叠加 4 个提交(
验证(本地 CPU):DeepSeek-V3.2 的 UT、Gloo ST 和 DSA 算子 UT 共 13 passed / 4 subtests。去掉第 1 个修复后,cp_size=1 的 ST 报 TypeError;去掉 FSDP2 后,ST 在 |
…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.
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.
…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.
Owner
Author
|
单卡 200 步对齐结果(910B3 / CANN 9.2)。 代码与配置
结果
整体接近,但仍有小幅非零差。下图为原始 200 步曲线及 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 一致)。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/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 按 Megatronseq_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_loss_coeff选项,设置框架 DSA 已有的 indexer KL loss 系数。deepseek_v32_ep_compute_fn(与 Qwen3-MoE 的写法相同,组合框架的build_ep_compute),直接使用 router 返回的专家与门控值(topk_router_module):框架内置的 DeepSeek-V3 工厂会从 logits 重新推导路由,丢掉挂在门控值上的负载均衡 loss(实测 TP2+EP2 用例在负载均衡系数 0.1 时梯度不一致、为 0 时一致)。external_stateprovider 在分片后绑定 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)。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 打包。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。tests/common/dsa_reference_kernels.py,模拟 CANN 入口)。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: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 上所有有梯度的参数和专家负载都与单进程模型一致:DeepseekV32PackedSequence)TypeError: 'module' object is not callable)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 参数。TextTrainer.train()运行:from_config+ meta 初始化构建 Transformers 类,第 1 层 router 为训练版,inv_freq有限且非零,foundation_loss11.77 / 11.78,router_aux_loss≈ 1.00,每个优化步 router bias 按 ±1e-3 更新(Online 数据集按 train_iters × global_batch_size 取 6 条记录,拼行后在 drop_last 下够 2 步)。dsa_loss_coeff非 0 时构建阶段报NotImplementedError;KL 为 0 或单进程时正常。未在本机验证(需要 NPU):NPU 上的 FSDP 分片、GroupedExperts、RMSNorm 和 DSA 融合算子(含只有 CANN 实现的 indexer KL loss)、512 卡显存,以及与 MindSpeed-LLM 的 loss 对比。
Self-checklist:(请自检,在[ ]内打上x,我们将检视你的完成情况,否则会导致pr无法合入)