From 57a9e18534f60a001cccbbb0c8e2ac899c45f334 Mon Sep 17 00:00:00 2001 From: hf1s Date: Tue, 27 Oct 2026 21:28:50 -0500 Subject: [PATCH 01/20] feat(deepseek_v32): complete TP/CP/EP/FSDP integration - 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 --- .../references/known-models.md | 12 + docs/feature_status.md | 1 + .../adapter/conversion/module_replacement.py | 18 +- .../deepseek_v32/adapter/data/__init__.py | 15 + .../deepseek_v32/adapter/data/runtime.py | 62 ++++ .../adapter/distributed/expert_parallel.py | 104 ++++++ .../deepseek_v32/adapter/policies/sharding.py | 11 +- .../deepseek_v32/adapter/registration.py | 10 + .../models/deepseek_v32/recipes/train.yaml | 93 ++++- setup.py | 1 + tests/common/dsa_reference_kernels.py | 322 ++++++++++++++++++ .../_test_deepseek_v32_parallel.py | 295 ++++++++++++++++ .../test_deepseek_v32_parallel.py | 47 +++ .../test_deepseek_v32_adapter_contracts.py | 239 +++++++++++++ 14 files changed, 1214 insertions(+), 16 deletions(-) create mode 100644 hyper_parallel/models/deepseek_v32/adapter/data/__init__.py create mode 100644 hyper_parallel/models/deepseek_v32/adapter/data/runtime.py create mode 100644 hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py create mode 100644 tests/common/dsa_reference_kernels.py create mode 100644 tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py create mode 100644 tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py create mode 100644 tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py diff --git a/.agent/skills/parallel-strategy-analyzer/references/known-models.md b/.agent/skills/parallel-strategy-analyzer/references/known-models.md index 365b6cfdea..725ca12b48 100644 --- a/.agent/skills/parallel-strategy-analyzer/references/known-models.md +++ b/.agent/skills/parallel-strategy-analyzer/references/known-models.md @@ -53,6 +53,18 @@ Compresses KV cache into a low-rank latent vector instead of storing per-head K/ **Impact on parallel strategy**: MLA compresses KV cache ~32× (512-dim vs 128×128=16384 for standard MHA). For CP ring attention, use `kv_lora_rank` instead of `n_kv × d_head` when estimating KV transfer volume — makes CP nearly free for MLA models. +### DSA (DeepSeek Sparse Attention) — DeepSeek V3.2 + +V3.2 keeps MLA and adds a Lightning Indexer that selects `index_topk` keys per query for sparse attention: + +| Parameter | V3.2 | +|-----------|------| +| index_n_heads | 64 | +| index_head_dim | 128 | +| index_topk | 2048 | + +**Impact on parallel strategy**: attention score memory and compute scale with `s × index_topk` instead of `s²` once `s > index_topk`; the indexer itself still scores `s²` pairs with `index_n_heads × index_head_dim`. Under CP the indexer keys (`index_head_dim` per token) are all-gathered alongside the MLA latent KV. The indexer heads stay replicated under TP, and the trainable indexer KL loss needs every attention head on one rank, so it is incompatible with `tp_size > 1`. + ### GQA (Grouped Query Attention) — LLaMA-2/3, Qwen3/3.5 `n_kv < n_h`: multiple query heads share one KV head. Reduces CP communication by `n_kv/n_h` ratio. diff --git a/docs/feature_status.md b/docs/feature_status.md index f88b01ef4d..ea1c28398b 100644 --- a/docs/feature_status.md +++ b/docs/feature_status.md @@ -5,6 +5,7 @@ ## 支持模型 - [x] Qwen3-30B-A3B +- [x] DeepSeek-V3.2(DSA + MoE,TP/CP/EP/FSDP) ## HyperShard diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py index c24a926ef4..b2a016581d 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py @@ -42,7 +42,23 @@ def replace_deepseek_v32_dsa_attention( module_fqn: str, context: Mapping[str, Any], ) -> nn.Module: - """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module.""" + """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module. + + The indexer KL loss distils the attention distribution summed over every + head. Tensor parallelism leaves each rank a subset of the heads and the + fused KL operator has no cross-rank reduction, so the trainable-indexer + loss is rejected together with ``tp_size > 1``. + """ + config = module.config + indexer_loss = getattr(config, "dsa_loss_coeff", 0.0) and not getattr( + config, "freeze_DSA", getattr(config, "freeze_dsa", False) + ) + if indexer_loss and context.get("tp", False): + raise ValueError( + f"{module_fqn}: the DeepSeek-V3.2 indexer KL loss (dsa_loss_coeff=" + f"{config.dsa_loss_coeff}) needs every attention head on one rank; " + "train it with tp_size=1 or set dsa_loss_coeff=0 / freeze_dsa=true" + ) from hyper_parallel.components.modules import DeepseekV32DSAAttention # pylint: disable=C0415 return DeepseekV32DSAAttention(module=module, module_fqn=module_fqn, context=context) diff --git a/hyper_parallel/models/deepseek_v32/adapter/data/__init__.py b/hyper_parallel/models/deepseek_v32/adapter/data/__init__.py new file mode 100644 index 0000000000..94fcbf9235 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/data/__init__.py @@ -0,0 +1,15 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 runtime-input adapters.""" diff --git a/hyper_parallel/models/deepseek_v32/adapter/data/runtime.py b/hyper_parallel/models/deepseek_v32/adapter/data/runtime.py new file mode 100644 index 0000000000..0d02c2bd07 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/data/runtime.py @@ -0,0 +1,62 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Packed-document runtime inputs for DeepSeek-V3.2 DSA attention.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import torch # pylint: disable=forbidden-backend-import + +from hyper_parallel.data.batching.runtime_input import ( + RuntimeInputAdapter, + RuntimeInputContext, +) + + +class DeepseekV32PackedSequence(RuntimeInputAdapter): + """Pass packed-document boundaries to the DSA attention. + + DSA derives its causal structure from cumulative sequence lengths and + never reads a dense attention mask. When documents packed into one row + must not attend to each other, this adapter forwards the global + leading-zero ``cu_seq_lens`` of the ``[batch, sequence]`` token stream as + ``cu_seq_lens_q``/``cu_seq_lens_k``. The non-CP attention consumes them + directly and the CP wrapper projects them onto its local query shard and + gathered KV prefix. Rows without this adapter are independent causal + sequences. + """ + + def runtime_input_fields(self) -> tuple[str, ...]: + """Declare the packed-boundary fields owned by this adapter.""" + return ("cu_seq_lens_q", "cu_seq_lens_k") + + def build_runtime_inputs( + self, + *, + batch: Mapping[str, Any], + context: RuntimeInputContext, + ) -> Mapping[str, Any]: + """Return the global packed boundaries for both query and key/value.""" + del context + cu_seq_lens = batch.get("cu_seq_lens") + if cu_seq_lens is None: + raise ValueError("DeepSeek-V3.2 packed attention requires cu_seq_lens in the batch") + boundaries = cu_seq_lens.to(dtype=torch.int32) + return {"cu_seq_lens_q": boundaries, "cu_seq_lens_k": boundaries} + + +__all__ = ["DeepseekV32PackedSequence"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py b/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py new file mode 100644 index 0000000000..919de52f61 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py @@ -0,0 +1,104 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 expert-parallel compute factory. + +``DeepseekV32TopkRouter`` already returns the complete DeepSeek routing +decision ``(router_logits, topk_weights, topk_indices)``: sigmoid scores, the +``e_score_correction_bias`` used only for selection, group-limited top-k, +normalisation and ``routed_scaling_factor``. The factory consumes that decision +through the generic ``topk_router_module`` adapter instead of re-deriving it, so +the EP block evaluates the router once and selects exactly the experts and +weights of the non-EP block. Token dispatch, the local expert GEMMs and the +combine come from the generic EP skeleton; the shared experts are added to the +routed output as ``DeepseekV32MoE.forward`` does. +""" + +from typing import Any, Callable, Optional + +import torch # pylint: disable=forbidden-backend-import + +from hyper_parallel.distributed.expert_parallel.recipes import build_ep_compute +from hyper_parallel.distributed.recipe_spec import local_compute + + +@local_compute +def deepseek_v32_ep_compute_fn( + *, + module: Any, + mesh: Any, + tp_mesh: Any, + cp_mesh: Any, + ep_mesh: Any, + use_grouped_gemm: bool = False, + overlap_shared_expert: bool = False, + fix_router: bool = False, + capacity_factor: Optional[float] = None, +) -> Callable: + """Build the EP forward of one ``DeepseekV32MoE`` block. + + Expected module interface: ``gate`` returning ``(logits, weights, + indices)``, batched ``experts`` and ``shared_experts``. + + Args: + module: DeepSeek-V3.2 MoE block. + mesh: Unused; part of the local-compute factory signature. + tp_mesh: Unused. + cp_mesh: Unused. + ep_mesh: Expert mesh whose ``ep`` axis owns the routed experts. + use_grouped_gemm: Run local experts through the grouped-GEMM path. + Required when ``experts`` is the ``GroupedExperts`` replacement, + whose weights use the transposed grouped-GEMM layout. + overlap_shared_expert: Evaluate ``shared_experts`` while the dispatch + exchange is in flight. The shared branch reads only + ``hidden_states``, so the result is unchanged. + fix_router: Benchmark-only balanced routing. Loss, gradient norm and + expert-load statistics are meaningless in that mode. + capacity_factor: Per-expert slot bound of the overlapped dispatch path; + ``None`` keeps dropless routing. + + Returns: + ``compute_fn(module, hidden_states)`` with the block forward signature. + """ + del mesh, tp_mesh, cp_mesh + + def combine( + module: Any, + hidden_states: torch.Tensor, + routed: torch.Tensor, + overlapped: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """Add the shared-experts branch to the routed output.""" + shared = module.shared_experts(hidden_states) if overlapped is None else overlapped + return routed + shared + + def overlap_shared(module: Any, hidden_states: torch.Tensor) -> torch.Tensor: + """Run the shared-experts branch behind the dispatch exchange.""" + return module.shared_experts(hidden_states) + + return build_ep_compute( + module, + ep_mesh, + router_fn="topk_router_module", + fix_router=fix_router, + archetype_key="deepseek_v32_topk_router_shared", + expected_attrs=["gate", "experts", "shared_experts"], + combine=combine, + use_grouped_gemm=use_grouped_gemm, + capacity_factor=capacity_factor, + overlap_fn=overlap_shared if overlap_shared_expert else None, + ) + + +__all__ = ["deepseek_v32_ep_compute_fn"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py b/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py index 8628d6ef4a..6b846c615d 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py +++ b/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py @@ -18,13 +18,20 @@ def build_parameter_sharding_rules() -> list[tuple[list[str], Any]]: - """Return DSA and MLA tensor-parallel naming-rule overrides.""" + """Return DSA and MLA tensor-parallel naming-rule overrides. + + The latent projections (``q_a_proj``/``kv_a_proj_with_mqa``, or their + fused ``linear_qkv`` form after the DSA replacement) feed every attention + head, so each TP rank keeps them whole; the head-major up-projections are + column-parallel. The indexer scores all of its heads on every TP rank so + each rank selects the same top-k tokens. + """ from hyper_parallel.distributed.tensor_parallel.param_role import ( # pylint: disable=C0415 ParamRole, ) return [ - (["linear_qkv"], ParamRole.REPLICATED), + (["q_a_proj", "kv_a_proj_with_mqa", "linear_qkv"], ParamRole.REPLICATED), (["q_b_proj", "kv_b_proj"], ParamRole.COLWISE), ( [ diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index a7a8a67454..13d03b04cd 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -39,11 +39,21 @@ def _load_context_parallel(): return context_parallel +def _load_expert_parallel(): + """Return the DeepSeek-V3.2 EP compute factory provider lazily.""" + from hyper_parallel.models.deepseek_v32.adapter.distributed import ( # pylint: disable=C0415 + expert_parallel, + ) + + return expert_parallel + + DEEPSEEK_V32_ADAPTER_SPEC = ModelAdapterSpec( architecture="DeepseekV32ForCausalLM", model_type="deepseek_v32", replacements=_load_replacements, context_parallel=_load_context_parallel, + expert_parallel=_load_expert_parallel, sharding_rules=build_parameter_sharding_rules, ) register_model_adapter(DEEPSEEK_V32_ADAPTER_SPEC) diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index 015610bce4..c3ca9bb7bc 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -1,14 +1,26 @@ -# DeepSeek-V3.2 single-device Trainer recipe. +# DeepSeek-V3.2 完整训练配方(唯一对外交付的 DeepSeek-V3.2 recipe)。 # -# The model configuration, tokenizer, and weights come from the official -# Hugging Face checkpoint. Parallel topology sections are intentionally -# omitted, so Trainer defaults keep TP/CP/EP/PP and FSDP degrees at 1. The -# conditional CP override remains available and is activated only when a user -# explicitly sets accelerator.cp_size greater than 1. +# 主线拓扑:64 节点 / 512 卡 Ascend NPU(hccl backend)。 +# dense 区域:tp 1 × cp 1 × dp 512,FSDP 在 512 卡上切分; +# 专家区域:ep 64 × edp 8(edp = dp*cp*tp/ep),edp 维度再做 FSDP 切分。 +# 显存估算(未在本配方上实测,按需在目标集群确认):FP32 参数 + FP32 main grad +# + AdamW 两个 FP32 动量 ≈ 16 B/param;256 个路由专家(约 654B 参数)由 +# ep 64 × edp_shard 8 摊到每卡约 1.28B 参数(≈ 20 GB),dense 部分约 18B 参数在 +# 512 卡上可忽略,再加 4K 序列全重计算激活,单卡约 30 GB。 # -# DeepSeek-V3.2 is a very large model; running this recipe requires a device -# with enough memory for the selected checkpoint and optimizer states. Local -# or offline assets can be selected with dotted overrides, for example: +# 其它并行维度都通过 CLI dotted override 打开,无需维护第二份配置: +# TP/loss parallel:--accelerator.tp_size=2 --accelerator.loss_parallel=true;DSA 暂不支持 +# sequence parallel。 +# MoE 层在 TP 下走 TP-extend-EP(专家只按 ep 切),因此 tp_size>1 时 ep_size +# 必须 >1;fused gate_up 专家不能直接做 TP 切分(planner 会给出明确报错)。 +# CP:--accelerator.cp_size=2,下方 `when: cp` 的 DSA CP wrapper 自动生效; +# EP:--accelerator.ep_size 与 --fsdp_config.edp_shard_size 一起调整。 +# 修改拓扑时保持 world_size = tp*cp*dp、dp*cp 可被 dp_shard_size 整除、 +# dp*cp*tp/ep 可被 edp_shard_size 整除、256 个专家可被 ep_size 整除,且 +# global_batch_size 可被 micro_batch_size*dp 整除。 +# +# 默认加载公开 Hugging Face 资源(模型、tokenizer、dataset)。本地或离线资源 +# 用命令行覆盖,例如: # scripts/train_lm.py \ # --model.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 \ # --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 @@ -17,13 +29,16 @@ model: _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained pretrained_model_name_or_path: deepseek-ai/DeepSeek-V3.2 torch_dtype: bfloat16 - attn_implementation: eager + # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 + attn_implementation: sdpa force_hf: true +model_init_dtype: float32 + training: train_iters: 3 train_samples: null - global_batch_size: 1 + global_batch_size: 512 micro_batch_size: 1 backend: hccl init_device: meta @@ -32,6 +47,29 @@ training: seed: 42 enable_full_determinism: true +accelerator: + tp_size: 1 + cp_size: 1 + ep_size: 64 + pp_size: 1 + sequence_parallel: false + loss_parallel: false + +fsdp_config: + dp_shard_size: 512 + edp_shard_size: 8 + replicate_params: [] + mix_precision: + param_dtype: bfloat16 + reduce_dtype: float32 + cast_forward_inputs: false + reshard_after_forward: true + reshard_after_backward: true + requires_grad_sync: true + forward_prefetch_depth: 1 + backward_prefetch_depth: 1 + comm_fusion: false + plan_overrides: - match: - "*.input_layernorm" @@ -42,18 +80,24 @@ plan_overrides: implementation: _target_: >- hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_rms_norm + # MLA + Lightning-indexer DSA。q_a/kv_a 融合为 linear_qkv(权重由 make_transforms 拼接), + # 稀疏注意力与 indexer 走 NPU 融合算子;TP 下主注意力头按 q_b/kv_b 列切,indexer 头复制。 - match: "*.self_attn" replace: kind: module implementation: _target_: >- hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + # 专家始终使用同一个 grouped-GEMM 实现;EP 只改变该边界外的 token 分发与合并。 - match: "*.mlp.experts" replace: kind: module implementation: _target_: >- hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_grouped_experts + # CP:本 rank 保留本地 query,异步 all-gather indexer key 与 MLA 压缩 KV, + # 只消费到本地 query 结尾的因果前缀;打包边界由 runtime input 的 + # cu_seq_lens 投影到本地。 - match: "*.self_attn.forward" when: cp replace: @@ -62,6 +106,25 @@ plan_overrides: _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper # null follows dsa_dense_warm_up; true/false forces one path for the full run. dense_warmup: null + # EP:只匹配 MoE 层。DeepSeek-V3.2 的 first_k_dense_replace=3,层 0-2 为稠密 MLP, + # 层 3-60 为 MoE;fnmatch 不支持数值区间,因此分两条 glob 覆盖 3-9 与 10-99。 + # 裁剪模型改变稠密层数时需要同步调整这两条 glob。 + - match: "model.layers.[3-9].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn + use_grouped_gemm: true + overlap_shared_expert: true + - match: "model.layers.[1-9][0-9].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn + use_grouped_gemm: true + overlap_shared_expert: true mixed_precision: enabled: false @@ -97,7 +160,7 @@ dataset: config_name: wikitext-2-raw-v1 cache_dir: null labels_are_shifted: true - create_attention_mask_in_dataloader: true + create_attention_mask_in_dataloader: false create_ltor_fields_in_dataloader: false _target_: hyper_parallel.data.text.build_dataset.build_online_text_mapping_dataset data_path: Salesforce/wikitext @@ -110,7 +173,10 @@ dataloader: get_batch: _target_: hyper_parallel.data.batching.TextParallelBatch source_type: online - attention_mode: dense + # DSA 从累计序列长度推导因果与文档边界,不需要 [S, S] 稠密 mask。 + attention_mode: compressed + runtime_input_adapter: + _target_: hyper_parallel.models.deepseek_v32.adapter.data.runtime.DeepseekV32PackedSequence sampler_type: single data_rearrange_map: null data_sharding: false @@ -122,6 +188,7 @@ dataloader: optimizer: _target_: hyper_parallel.components.optim.AdamW + fp32_main_params: true no_decay_params: [bias, norm, ln_] adamw_config: lr: 1.0e-5 diff --git a/setup.py b/setup.py index 5c1f2b479a..db6faaddf4 100644 --- a/setup.py +++ b/setup.py @@ -256,6 +256,7 @@ def has_ext_modules(self) -> bool: 'hyper_parallel.models.qwen3_moe': [ 'recipes/*.yaml', 'generated/*.json', 'generated/*.diff', ], + 'hyper_parallel.models.deepseek_v32': ['recipes/*.yaml'], 'hyper_parallel.models.deepseek_v41': [ 'generated/*.json', 'generated/*.diff', ], diff --git a/tests/common/dsa_reference_kernels.py b/tests/common/dsa_reference_kernels.py new file mode 100644 index 0000000000..a8db998279 --- /dev/null +++ b/tests/common/dsa_reference_kernels.py @@ -0,0 +1,322 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""CPU reference kernels standing in for the NPU DeepSeek sparse-attention operators. + +``DeepseekV32DSAAttention`` and its CP wrapper call the CANN DSA operators +through the HyperParallel functional wrappers: the ops-transformer Lightning +indexer, ``torch_npu.npu_sparse_flash_attention`` with its ops-transformer +gradient, and ``npu_rotary_mul``. This helper implements their TND contracts +with plain PyTorch so the replacement, its weight conversion, and its TP/CP +orchestration run on CPU against the Transformers attention. The DSA KL-loss +operator is deliberately absent: tests keep the indexer loss disabled, and +calling it raises. +""" +# Test helper for CPU workers; torch is required here by design. +# pylint: disable=forbidden-backend-import + +from __future__ import annotations + +import contextlib +import sys +import types +from collections.abc import Iterator + +import torch + +_STUB_MODULES = ("torch_npu", "omni_training_custom_ops", "cann_ops_transformer", "cann_ops_transformer.ops") +_DSA_MODULES = ( + "hyper_parallel.components.modules.dsa_attention", + "hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel", +) +# Lazy export packages cache resolved symbols in their globals. +_LAZY_PACKAGES = ("hyper_parallel.components.functional", "hyper_parallel.components.modules") + + +def _sequence_spans(cumulative: torch.Tensor) -> list[tuple[int, int]]: + """Convert cumulative ends without a leading zero into half-open spans.""" + spans, start = [], 0 + for end in cumulative.tolist(): + spans.append((start, int(end))) + start = int(end) + return spans + + +def _causal_allowed(query_length: int, key_length: int, device: torch.device) -> torch.Tensor: + """Bottom-right aligned causal mask (sparse_mode=3): the last query sees the last key.""" + query = torch.arange(query_length, device=device).unsqueeze(1) + (key_length - query_length) + key = torch.arange(key_length, device=device).unsqueeze(0) + return key <= query + + +def lightning_indexer( + query: torch.Tensor, + key: torch.Tensor, + weights: torch.Tensor, + sparse_count: int, + *, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + layout_q: str = "TND", + layout_k: str = "TND", + mask_mode: int = 3, + cmp_ratio: int = 1, + **_: object, +) -> tuple[torch.Tensor, torch.Tensor]: + """Select ``sparse_count`` causal keys per query by ``sum_h w_h * relu(q_h . k)``. + + ``cu_seqlens_*`` start with a leading zero. Indices are relative to the + start of each packed key sequence; slots without a causal candidate hold + ``-1``. + """ + if mask_mode != 3 or cmp_ratio != 1 or layout_q != "TND" or layout_k != "TND": + raise NotImplementedError("reference indexer supports uncompressed causal TND inputs only") + tokens = query.shape[0] + indices = torch.full((tokens, 1, sparse_count), -1, dtype=torch.int32, device=query.device) + values = torch.full((tokens, 1, sparse_count), float("-inf"), dtype=torch.float32, device=query.device) + query_spans = _sequence_spans(cu_seqlens_q[1:]) + key_spans = _sequence_spans(cu_seqlens_k[1:]) + for (q_start, q_end), (k_start, k_end) in zip(query_spans, key_spans): + query_length, key_length = q_end - q_start, k_end - k_start + if query_length == 0 or key_length == 0: + continue + scores = torch.relu(torch.einsum( + "qnd,kd->qnk", query[q_start:q_end].float(), key[k_start:k_end, 0].float() + )) + scores = torch.einsum("qn,qnk->qk", weights[q_start:q_end].float(), scores) + scores = scores.masked_fill(~_causal_allowed(query_length, key_length, query.device), float("-inf")) + count = min(sparse_count, key_length) + top_values, top_indices = scores.topk(count, dim=-1) + top_indices = top_indices.masked_fill(torch.isinf(top_values), -1) + indices[q_start:q_end, 0, :count] = top_indices.to(torch.int32) + values[q_start:q_end, 0, :count] = top_values + return indices, values + + +def lightning_indexer_metadata(*args: object, **kwargs: object) -> torch.Tensor: + """Return placeholder tiling metadata; the reference indexer reads none.""" + del args, kwargs + return torch.empty(0, dtype=torch.int32) + + +def sparse_flash_attention( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + sparse_indices: torch.Tensor, + scale_value: float, + *, + actual_seq_lengths_query: torch.Tensor, + actual_seq_lengths_kv: torch.Tensor, + query_rope: torch.Tensor, + key_rope: torch.Tensor, + sparse_mode: int = 3, + layout_query: str = "TND", + layout_kv: str = "TND", + **_: object, +) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Attend each query to its selected latent keys (MLA absorbed form). + + Scores are ``(q . k + q_rope . k_rope) * scale`` over the selected keys and + the output is the softmax-weighted latent value. Returns the output plus + the per-head softmax maximum and sum. + """ + if sparse_mode != 3 or layout_query != "TND" or layout_kv != "TND": + raise NotImplementedError("reference sparse attention supports causal TND inputs only") + outputs, maxima, sums = [], [], [] + query_spans = _sequence_spans(actual_seq_lengths_query) + key_spans = _sequence_spans(actual_seq_lengths_kv) + for (q_start, q_end), (k_start, _) in zip(query_spans, key_spans): + if q_end == q_start: + continue + selected = sparse_indices[q_start:q_end, 0].long() + valid = selected >= 0 + rows = k_start + selected.clamp_min(0) + scores = torch.einsum("qnd,qkd->qnk", query[q_start:q_end], key[rows, 0]) + scores = scores + torch.einsum("qnd,qkd->qnk", query_rope[q_start:q_end], key_rope[rows, 0]) + scores = (scores * scale_value).float().masked_fill(~valid.unsqueeze(1), float("-inf")) + maximum = scores.amax(dim=-1) + probabilities = torch.softmax(scores, dim=-1) + outputs.append(torch.einsum("qnk,qkd->qnd", probabilities.to(value.dtype), value[rows, 0])) + maxima.append(maximum) + sums.append(torch.exp(scores - maximum.unsqueeze(-1)).sum(dim=-1)) + return torch.cat(outputs), torch.cat(maxima), torch.cat(sums) + + +def sparse_flash_attention_grad( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor | None, + sparse_indices: torch.Tensor, + grad_output: torch.Tensor, + *saved: object, + query_rope: torch.Tensor, + key_rope: torch.Tensor, + actual_seq_qlen: torch.Tensor, + actual_seq_kvlen: torch.Tensor, + layout: str = "TND", + sparse_mode: int = 3, + **_: object, +) -> tuple[torch.Tensor, torch.Tensor, None, torch.Tensor, torch.Tensor, None]: + """Differentiate the reference forward with ``key`` as the shared K/V tensor. + + As in the CANN GradV2 call, ``value`` is ``None`` and the key gradient + merges its key and value roles. ``saved`` carries the forward output, the + softmax statistics and an unused optional operand, then the scale and the + sparse block size; the forward is recomputed instead of read back. + """ + if value is not None: + raise NotImplementedError("reference gradient supports the shared K/V layout only") + *_, scale_value, _ = saved + inputs = tuple(tensor.detach().requires_grad_() for tensor in (query, key, query_rope, key_rope)) + with torch.enable_grad(): + output, _, _ = sparse_flash_attention( + inputs[0], inputs[1], inputs[1], sparse_indices, scale_value, + actual_seq_lengths_query=actual_seq_qlen, actual_seq_lengths_kv=actual_seq_kvlen, + query_rope=inputs[2], key_rope=inputs[3], sparse_mode=sparse_mode, + layout_query=layout, layout_kv=layout, + ) + grad_query, grad_key, grad_query_rope, grad_key_rope = torch.autograd.grad(output, inputs, grad_output) + return grad_query, grad_key, None, grad_query_rope, grad_key_rope, None + + +def _unsupported_indexer_loss(*args: object, **kwargs: object) -> None: + """Reject the KL-loss operator, whose reference is out of scope.""" + del args, kwargs + raise NotImplementedError("the CPU DSA reference does not implement the indexer KL loss") + + +def rotary_mul( + tensor: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + rotary_mode: str = "half", +) -> torch.Tensor: + """Reference ``torch_npu.npu_rotary_mul`` for the half and interleave layouts.""" + if rotary_mode == "half": + first, second = tensor.chunk(2, dim=-1) + rotated = torch.cat((-second, first), dim=-1) + elif rotary_mode == "interleave": + rotated = torch.stack((-tensor[..., 1::2], tensor[..., 0::2]), dim=-1).flatten(-2) + else: + raise NotImplementedError(f"unsupported rotary_mode {rotary_mode!r}") + return tensor * cos + rotated * sin + + +def _stub_modules() -> dict[str, types.ModuleType]: + """Build import stand-ins exposing only what the DSA path calls.""" + torch_npu = types.ModuleType("torch_npu") + torch_npu.npu_rotary_mul = rotary_mul + torch_npu.npu_sparse_flash_attention = sparse_flash_attention + torch_npu.npu_sparse_lightning_indexer_grad_kl_loss = _unsupported_indexer_loss + ops = types.ModuleType("cann_ops_transformer.ops") + ops.lightning_indexer = lightning_indexer + ops.lightning_indexer_metadata = lightning_indexer_metadata + ops.sparse_flash_attention_grad = sparse_flash_attention_grad + cann_ops_transformer = types.ModuleType("cann_ops_transformer") + cann_ops_transformer.ops = ops + return { + "torch_npu": torch_npu, + "omni_training_custom_ops": types.ModuleType("omni_training_custom_ops"), + "cann_ops_transformer": cann_ops_transformer, + "cann_ops_transformer.ops": ops, + } + + +def _binds_stub(module: types.ModuleType, stubs: dict[str, types.ModuleType]) -> bool: + """Return whether a module captured one of the stand-in modules at import.""" + stub_ids = {id(stub) for stub in stubs.values()} + return any(id(value) in stub_ids for value in vars(module).values()) + + +def _is_refreshed(name: str) -> bool: + """Return whether a module must be imported afresh against the stand-ins.""" + return name in _STUB_MODULES or name in _DSA_MODULES or ( + name.startswith(_LAZY_PACKAGES) and name not in _LAZY_PACKAGES + ) + + +def _forget_cached_dsa_modules(packages: dict[str, dict]) -> None: + """Drop cached NPU-dependent modules and the symbols lazy packages resolved from them.""" + for name in [name for name in sys.modules if _is_refreshed(name)]: + del sys.modules[name] + for name in packages: + package = vars(sys.modules[name]) + for attribute, value in list(package.items()): + origin = value.__name__ if isinstance(value, types.ModuleType) else getattr(value, "__module__", "") + if isinstance(origin, str) and origin.startswith(f"{name}."): + del package[attribute] + + +def _restore_modules( + previous_modules: dict[str, types.ModuleType], + previous_packages: dict[str, dict], + stubs: dict[str, types.ModuleType], +) -> None: + """Evict modules bound to the stand-ins and restore the previous import state.""" + for name, module in list(sys.modules.items()): + if name not in previous_modules and (name in _DSA_MODULES or _binds_stub(module, stubs)): + del sys.modules[name] + parent, _, child = name.rpartition(".") + if getattr(sys.modules.get(parent), child, None) is module: + delattr(sys.modules[parent], child) + for name, module in previous_modules.items(): + if _is_refreshed(name) and sys.modules.get(name) is not module: + sys.modules[name] = module + parent, _, child = name.rpartition(".") + if parent in sys.modules: + setattr(sys.modules[parent], child, module) + for name, contents in previous_packages.items(): + package = vars(sys.modules[name]) + package.clear() + package.update(contents) + + +@contextlib.contextmanager +def reference_dsa_kernels() -> Iterator[None]: + """Run the DSA replacement and its CP wrapper on CPU reference kernels. + + The NPU-dependent modules are imported afresh against stand-in + ``torch_npu``, custom-operator and ``cann_ops_transformer`` modules, so a + stand-in left behind by another test cannot leak into them. The CANN + wrappers import their operators when called, so the stand-ins stay in + ``sys.modules`` until the context exits. On exit every module that + captured a stand-in is evicted and the previous modules and lazily cached + package symbols are restored. + """ + previous_modules = dict(sys.modules) + previous_packages = { + name: dict(vars(sys.modules[name])) for name in _LAZY_PACKAGES if name in sys.modules + } + stubs = _stub_modules() + _forget_cached_dsa_modules(previous_packages) + sys.modules.update(stubs) + try: + for module_name in _DSA_MODULES: + __import__(module_name) + yield + finally: + for name in _STUB_MODULES: + sys.modules.pop(name, None) + _restore_modules(previous_modules, previous_packages, stubs) + + +__all__ = [ + "lightning_indexer", + "lightning_indexer_metadata", + "reference_dsa_kernels", + "rotary_mul", + "sparse_flash_attention", + "sparse_flash_attention_grad", +] diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py new file mode 100644 index 0000000000..7bb3b6dc88 --- /dev/null +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -0,0 +1,295 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""CPU/Gloo DeepSeek-V3.2 TP/SP/CP/EP parity against a single-process reference. + +Each case builds one small DeepSeek-V3.2 with fixed weights, converts a copy +through the Trainer chain (recipe ``plan_overrides`` -> module replacement -> +``ShardingPlanner`` -> ``apply_sharding_plan``) and runs one forward/backward +on the same tokens. The DSA cases run the NPU sparse-attention replacement on +the CPU reference kernels of ``tests.common.dsa_reference_kernels``. + +FSDP is NPU/GPU-only, so the gradient reductions it owns are emulated: the +dense DP+CP domain averages, and only parameters whose final value needs no +TP-replicate reduction are compared (TP-sharded weights under sequence +parallelism and EP-sharded experts when no other rank feeds them tokens). +""" +# Distributed worker: torch and hyper_parallel imports are required here. +# pylint: disable=forbidden-backend-import + +import contextlib +import copy +import tempfile +from pathlib import Path +from typing import Any + +import torch +import torch.distributed as dist +import torch.distributed.nn.functional as dist_nn +import yaml +from transformers import DeepseekV32Config, DeepseekV32ForCausalLM + +from tests.common.dsa_reference_kernels import reference_dsa_kernels + +_ADAPTER = "hyper_parallel.models.deepseek_v32.adapter" +_SEQ_LEN = 16 +_BATCH = 2 + + +class _GlooAllGather(torch.autograd.Function): + """Differentiable all-gather whose backward is valid on every Gloo subgroup. + + ``torch.distributed.nn.functional.all_gather`` emulates its backward + reduce-scatter on Gloo with ``scatter`` calls that address global rank 0, + which fails on TP or CP subgroups that do not contain it. + """ + + @staticmethod + def forward(ctx: Any, group: Any, tensor: torch.Tensor) -> tuple: # pylint: disable=arguments-differ + """Gather every rank's shard.""" + tensor = tensor.contiguous() + ctx.group = group + gathered = [torch.empty_like(tensor) for _ in range(dist.get_world_size(group))] + dist.all_gather(gathered, tensor, group=group) + return tuple(gathered) + + @staticmethod + def backward(ctx: Any, *grads: torch.Tensor) -> tuple: # pylint: disable=arguments-differ + """Sum every rank's output gradient and keep this rank's slot.""" + stacked = torch.stack([grad.contiguous() for grad in grads]) + dist.all_reduce(stacked, group=ctx.group) + return None, stacked[dist.get_rank(ctx.group)] + + +def _config() -> DeepseekV32Config: + """Return one dense layer followed by two MoE layers.""" + config = DeepseekV32Config.from_dict({ + "vocab_size": 128, "hidden_size": 64, "intermediate_size": 96, "moe_intermediate_size": 32, + "num_hidden_layers": 3, "first_k_dense_replace": 1, "num_attention_heads": 4, + "num_key_value_heads": 4, "n_shared_experts": 1, "n_routed_experts": 8, "n_group": 2, + "topk_group": 1, "num_experts_per_tok": 2, "kv_lora_rank": 16, "q_lora_rank": 24, + "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 6, + "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, "attn_implementation": "sdpa", + }) + config.architectures = ["DeepseekV32ForCausalLM"] + return config + + +def _reference_model() -> DeepseekV32ForCausalLM: + """Build the unsharded model with nonzero expert-selection biases.""" + torch.manual_seed(7) + model = DeepseekV32ForCausalLM(_config()).float().train() + with torch.no_grad(): + for name, buffer in model.named_buffers(): + if name.endswith("e_score_correction_bias"): + buffer.copy_(torch.randn_like(buffer) * 0.05) + return model + + +def _plan_overrides(dsa: bool) -> list: + """Return the recipe parallel entries; NPU-only norm and expert kernels stay native.""" + entries = [] + if dsa: + entries.append({ + "match": "*.self_attn", + "replace": { + "kind": "module", + "implementation": { + "_target_": f"{_ADAPTER}.conversion.module_replacement.replace_deepseek_v32_dsa_attention", + }, + }, + }) + entries.append({ + "match": "*.self_attn.forward", "when": "cp", + "replace": { + "kind": "method", + "implementation": { + "_target_": f"{_ADAPTER}.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper", + }, + }, + }) + entries.append({ + "match": "model.layers.[1-9].mlp.forward", "when": "ep", + "replace": { + "kind": "method", + "implementation": {"_target_": f"{_ADAPTER}.distributed.expert_parallel.deepseek_v32_ep_compute_fn"}, + }, + }) + return entries + + +def _parse_trainer_config(tp, cp, ep, sequence_parallel, loss_parallel, dsa): + """Resolve a minimal Trainer YAML so plan_overrides follow the recipe path.""" + from hyper_parallel.trainer.config.parser import parse_training_args # pylint: disable=import-outside-toplevel + + recipe = { + "model": {"_target_": "transformers.AutoConfig.from_pretrained"}, + "optimizer": {"_target_": "hyper_parallel.components.optim.AdamW", "adamw_config": {"lr": 1.0e-4}}, + "training": {"backend": "gloo", "global_batch_size": 1, "micro_batch_size": 1}, + "accelerator": {"tp_size": tp, "cp_size": cp, "ep_size": ep, "pp_size": 1, + "sequence_parallel": sequence_parallel, "loss_parallel": loss_parallel}, + "fsdp_config": {"dp_shard_size": 1, "edp_shard_size": 1}, + "plan_overrides": _plan_overrides(dsa), + } + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "recipe.yaml" + path.write_text(yaml.safe_dump(recipe), encoding="utf-8") + return parse_training_args([str(path)]) + + +def _build_parallel_model(reference, config, dsa): + """Run replacement, planning and sharding on a copy of the reference weights.""" + # pylint: disable=import-outside-toplevel + from hyper_parallel.components.checkpoint.weight_conversion import get_model_conversion_mapping + from hyper_parallel.distributed.apply import apply_sharding_plan + from hyper_parallel.models._transformers.model_builder import ( + _maybe_apply_module_replacements, + instantiate_infrastructure, + ) + from hyper_parallel.trainer.config import normalize_distributed_setup_overrides + from hyper_parallel.trainer.runtime.distributed import create_distributed_setup_from_config + + setup = create_distributed_setup_from_config(config) + normalize_distributed_setup_overrides(setup, config) + mesh = setup.mesh_context + model = copy.deepcopy(reference) + model, _ = _maybe_apply_module_replacements( + model, None, setup, None, False, get_model_conversion_mapping(model) + ) + if dsa: + for replaced, source in zip(model.model.layers, reference.model.layers): + with torch.no_grad(): + replaced.self_attn.linear_qkv.weight.copy_(torch.cat([ + source.self_attn.q_a_proj.weight, source.self_attn.kv_a_proj_with_mqa.weight, + ])) + planner, _ = instantiate_infrastructure(distributed_setup=setup, device=torch.device("cpu")) + plan = planner.plan( + model, mesh.device_mesh, tp_size=mesh.tp_size, cp_size=mesh.cp_size, ep_size=mesh.ep_size, + sequence_parallel=mesh.sequence_parallel, loss_parallel=mesh.loss_parallel, + ) + model, source_shard_info = apply_sharding_plan(model, plan, mesh) + return model, mesh, source_shard_info or {} + + +def _reference_gradient(reference, name): + """Return the reference gradient of one parallel-model parameter name.""" + named = dict(reference.named_parameters()) + if name.endswith("linear_qkv.weight"): + prefix = name[: -len("linear_qkv.weight")] + return torch.cat([named[prefix + "q_a_proj.weight"].grad, named[prefix + "kv_a_proj_with_mqa.weight"].grad]) + return named[name].grad + + +def _compared_gradients(model, reference, mesh, source_shard_info, *, check_experts): + """Yield (name, local gradient, expected local gradient) for locally exact parameters. + + TP-replicated weights are compared only without TP, where the emulated + DP+CP average is their complete reduction. + """ + from hyper_parallel import distribute_tensor # pylint: disable=import-outside-toplevel + + dense_group = mesh.dp_cp_mesh.get_group() if mesh.dp_cp_mesh is not None and mesh.dp_cp_mesh.size() > 1 else None + for name, parameter in model.named_parameters(): + if parameter.grad is None: + continue + placements, source_mesh = source_shard_info.get(name, ((), None)) + sharded = any(not placement.is_replicate() for placement in placements) + is_expert = source_mesh is not None and "ep" in (source_mesh.mesh_dim_names or ()) + if (not sharded and mesh.tp_size > 1) or (is_expert and not check_experts): + continue + grad = parameter.grad.clone() + if not is_expert and dense_group is not None: + dist.all_reduce(grad, op=dist.ReduceOp.AVG, group=dense_group) + expected = _reference_gradient(reference, name) + if sharded: + expected = distribute_tensor(expected, source_mesh, placements, src_data_rank=None).to_local() + yield name, grad, expected + + +def _run_case(*, tp=1, cp=1, ep=1, sequence_parallel=False, loss_parallel=False, dsa=False, + check_gradients=True, check_experts=True): + """Compare one parallel topology against the single-process model.""" + # pylint: disable=import-outside-toplevel + dist.init_process_group("gloo") + original_all_gather = dist_nn.all_gather + dist_nn.all_gather = lambda tensor, group=dist.group.WORLD: _GlooAllGather.apply(group, tensor) + kernels = reference_dsa_kernels() if dsa else contextlib.nullcontext() + try: + with kernels: + from hyper_parallel.core.tensor_parallel import loss_parallel as loss_parallel_context + from hyper_parallel.models._transformers.loss_parallel import causal_lm_loss_parallel + + reference = _reference_model() + config = _parse_trainer_config(tp, cp, ep, sequence_parallel, loss_parallel, dsa) + model, mesh, source_shard_info = _build_parallel_model(reference, config, dsa) + if loss_parallel: + model.loss_function = causal_lm_loss_parallel + + torch.manual_seed(11) + tokens = torch.randint(1, 128, (_BATCH, _SEQ_LEN + 1)) + inputs, labels = tokens[:, :-1].contiguous(), tokens[:, 1:].contiguous() + positions = torch.arange(_SEQ_LEN).unsqueeze(0).expand(_BATCH, -1) + expected = reference(input_ids=inputs, labels=labels, shift_labels=labels, + position_ids=positions, use_cache=False) + expected.loss.backward() + + local = slice(mesh.cp_rank * _SEQ_LEN // cp, (mesh.cp_rank + 1) * _SEQ_LEN // cp) + extra = {} if dsa else {"attention_mask": torch.ones(1, 1, _SEQ_LEN, _SEQ_LEN, dtype=torch.bool).tril()} + forward_context = ( + loss_parallel_context(mesh=mesh.device_mesh["tp"]) if loss_parallel else contextlib.nullcontext() + ) + with forward_context: + output = model( + input_ids=inputs[:, local].contiguous(), labels=labels[:, local].contiguous(), + shift_labels=labels[:, local].contiguous(), position_ids=positions[:, local], + use_cache=False, **extra, + ) + # Trainer loss rule: equal token counts cancel the DP*CP factor; SP divides by TP. + (output.loss / (tp if sequence_parallel else 1)).backward() + + loss = output.loss.detach().reshape(()).clone() + if cp > 1: + dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=mesh.device_mesh["cp"].get_group()) + torch.testing.assert_close(loss, expected.loss.detach(), rtol=1e-5, atol=1e-6) + if check_gradients: + compared = 0 + for name, grad, reference_grad in _compared_gradients( + model, reference, mesh, source_shard_info, check_experts=check_experts): + torch.testing.assert_close(grad, reference_grad, rtol=1e-4, atol=1e-6, msg=name) + compared += 1 + assert compared, "no parallel gradient was compared" + finally: + dist_nn.all_gather = original_all_gather + dist.destroy_process_group() + + +def test_tp2_sp_ep2_transformers_attention(): + """TP2 + sequence parallel + EP2 on the Transformers attention and experts.""" + _run_case(tp=2, ep=2, sequence_parallel=True) + + +def test_cp2_dsa(): + """CP2 through the DSA all-gather wrapper; every gradient is compared.""" + _run_case(cp=2, dsa=True) + + +def test_tp2_ep2_dsa_loss_parallel(): + """TP2 + loss parallel + EP2 on the DSA replacement (forward parity).""" + _run_case(tp=2, ep=2, loss_parallel=True, dsa=True, check_gradients=False) + + +def test_tp2_cp2_ep4_dsa(): + """TP2 x CP2 with EP4 over the DSA replacement on four ranks (forward parity).""" + _run_case(tp=2, cp=2, ep=4, dsa=True, check_gradients=False) diff --git a/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py new file mode 100644 index 0000000000..115a317d86 --- /dev/null +++ b/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py @@ -0,0 +1,47 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Framework-free launchers for DeepSeek-V3.2 TP/SP/CP/EP parity on CPU/Gloo.""" + +from pathlib import Path +from unittest.mock import patch + +import pytest + +from tests.common.distributed_launcher import torchrun_case +from tests.common.mark_utils import arg_mark + +_WORKER = str(Path(__file__).with_name("_test_deepseek_v32_parallel.py")) + + +@pytest.mark.parametrize( + ("case_name", "num_proc"), + [ + ("test_tp2_sp_ep2_transformers_attention", 2), + ("test_cp2_dsa", 2), + ("test_tp2_ep2_dsa_loss_parallel", 2), + ("test_tp2_cp2_ep4_dsa", 4), + ], +) +@arg_mark(plat_marks=["cpu_linux"], level_mark="level0", + card_mark="allcards", essential_mark="essential") +def test_deepseek_v32_parallel_parity_gloo(case_name: str, num_proc: int) -> None: + """ + Feature: DeepSeek-V3.2 parallel integration. + Description: Run TP/SP/loss-parallel, DSA CP and EP topologies on CPU ranks through the Trainer chain. + Expectation: The loss and every locally exact gradient match the single-process model. + """ + # CPU workers need no accelerator backend, including torch's entry-point loading. + with patch.dict("os.environ", {"TORCH_DEVICE_BACKEND_AUTOLOAD": "0"}): + torchrun_case(_WORKER, case_name, num_proc=num_proc) diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py new file mode 100644 index 0000000000..4525477282 --- /dev/null +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py @@ -0,0 +1,239 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 adapter contracts: TP roles, recipe topology and DSA math.""" + +import copy +import fnmatch +import unittest +from pathlib import Path + +import torch +from transformers import DeepseekV32Config, DeepseekV32ForCausalLM + +from hyper_parallel.distributed._builder.planner import ShardingPlanner +from hyper_parallel.distributed.recipe_spec import TP +from hyper_parallel.core.dtensor.placement_types import Replicate, Shard +from hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement import ( + replace_deepseek_v32_dsa_attention, +) +from hyper_parallel.models.deepseek_v32.adapter.data.runtime import DeepseekV32PackedSequence +from tests.common.dsa_reference_kernels import reference_dsa_kernels +from tests.common.mark_utils import arg_mark +from tests.ut.auto_models.distributed.conftest import FakeDeviceMesh + +_RECIPE = Path(__file__).resolve().parents[5] / "hyper_parallel/models/deepseek_v32/recipes/train.yaml" + + +def _tiny_config(**overrides) -> DeepseekV32Config: + """Return a small DeepSeek-V3.2 configuration with one dense and two MoE layers.""" + values = { + "vocab_size": 96, "hidden_size": 48, "intermediate_size": 64, "moe_intermediate_size": 16, + "num_hidden_layers": 3, "first_k_dense_replace": 1, "num_attention_heads": 4, + "num_key_value_heads": 4, "n_shared_experts": 1, "n_routed_experts": 8, "n_group": 2, + "topk_group": 1, "num_experts_per_tok": 2, "kv_lora_rank": 16, "q_lora_rank": 24, + "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 4, + "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, "attn_implementation": "sdpa", + } + values.update(overrides) + config = DeepseekV32Config.from_dict(values) + config.architectures = ["DeepseekV32ForCausalLM"] + return config + + +def _attention_inputs(model, batch_size=2, seq_len=12, seed=3): + """Return hidden states, rotary embeddings and position IDs for layer 0.""" + generator = torch.Generator().manual_seed(seed) + hidden = torch.randn(batch_size, seq_len, model.config.hidden_size, generator=generator) + positions = torch.arange(seq_len).unsqueeze(0).expand(batch_size, -1) + return hidden, model.model.rotary_emb(hidden, positions), positions + + +def _dsa_from(attention): + """Replace one Transformers attention and copy its fused latent projection.""" + replacement = replace_deepseek_v32_dsa_attention( + module=copy.deepcopy(attention), module_fqn="model.layers.0.self_attn", context={} + ) + with torch.no_grad(): + replacement.linear_qkv.weight.copy_( + torch.cat([attention.q_a_proj.weight, attention.kv_a_proj_with_mqa.weight]) + ) + return replacement + + +class TestDeepseekV32TensorParallelRoles(unittest.TestCase): + """The planner must own every DeepSeek-V3.2 attention parameter under TP.""" + + @staticmethod + def _attention_placements(model): + """Plan TP2 and return the TP placement of every layer-0 attention parameter.""" + plan = ShardingPlanner().plan(model, FakeDeviceMesh((2,), ("tp",)), tp_size=2, sequence_parallel=True) + spec = plan.modules["model.layers.0.self_attn"] + return {name: placement[TP] for name, placement in spec.params.items()} + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_reference_attention_roles_cover_mla_and_indexer(self): + """Feature: DeepSeek-V3.2 TP roles on the Transformers attention. + + Description: Plan TP2 for a dense-only model without any replacement. + Expectation: Latent and indexer projections replicate and head projections shard. + """ + with torch.device("meta"): + model = DeepseekV32ForCausalLM(_tiny_config(num_hidden_layers=2, first_k_dense_replace=2)) + placements = self._attention_placements(model) + expected = { + "q_a_proj.weight": Replicate(), "kv_a_proj_with_mqa.weight": Replicate(), + "q_b_proj.weight": Shard(0), "kv_b_proj.weight": Shard(0), "o_proj.weight": Shard(1), + "indexer.wq_b.weight": Replicate(), "indexer.wk.weight": Replicate(), + "indexer.weights_proj.weight": Replicate(), + } + self.assertEqual(placements, expected) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_dsa_replacement_keeps_fused_latent_projection_replicated(self): + """Feature: DeepSeek-V3.2 TP roles on the DSA replacement. + + Description: Plan TP2 after fusing q_a_proj and kv_a_proj_with_mqa into linear_qkv. + Expectation: linear_qkv replicates while head-major projections shard. + """ + with reference_dsa_kernels(): + with torch.device("meta"): + model = DeepseekV32ForCausalLM(_tiny_config(num_hidden_layers=2, first_k_dense_replace=2)) + for layer in model.model.layers: + layer.self_attn = replace_deepseek_v32_dsa_attention( + module=layer.self_attn, module_fqn="", context={} + ) + placements = self._attention_placements(model) + self.assertEqual(placements["linear_qkv.weight"], Replicate()) + self.assertEqual(placements["q_b_proj.weight"], Shard(0)) + self.assertEqual(placements["kv_b_proj.weight"], Shard(0)) + self.assertEqual(placements["o_proj.weight"], Shard(1)) + self.assertNotIn("q_a_proj.weight", placements) + + +class TestDeepseekV32RecipeTopology(unittest.TestCase): + """Recipe parallel entries must target exactly the intended modules.""" + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_ep_entries_target_exactly_the_moe_layers(self): + """Feature: DeepSeek-V3.2 EP plan overrides. + + Description: Activate the recipe at EP>1 and match its MLP globs against the released depth. + Expectation: Only MoE layers receive the EP compute; CP and EP stay off at size one. + """ + released = DeepseekV32Config() + mlps = [f"model.layers.{index}.mlp" for index in range(released.num_hidden_layers)] + sparse = [name for name, kind in zip(mlps, released.mlp_layer_types) if kind == "sparse"] + with reference_dsa_kernels(): + from hyper_parallel.trainer.config import ( # pylint: disable=import-outside-toplevel + entries_to_plan_overrides, + ) + from hyper_parallel.trainer.config.parser import ( # pylint: disable=import-outside-toplevel + parse_training_args, + ) + entries = parse_training_args([str(_RECIPE)]).plan_overrides + self.assertEqual(entries_to_plan_overrides(entries), {}) + active = entries_to_plan_overrides(entries, cp_size=2, ep_size=2) + ep_globs = [key for key, spec in active.items() if spec.local_compute_fn is not None] + matched = [name for name in mlps if any(fnmatch.fnmatchcase(name, glob) for glob in ep_globs)] + self.assertEqual(matched, sparse) + self.assertIsNotNone(active["*.self_attn"].inner_wrapper) + + +class TestDeepseekV32DSAAttention(unittest.TestCase): + """The DSA replacement must reproduce Transformers DeepSeek-V3.2 attention.""" + + def _assert_matches_reference(self, attention, dsa, hidden, rope, positions, reference_mask, **kwargs): + """Compare outputs, input gradients and mapped parameter gradients in FP32.""" + reference_input = hidden.clone().requires_grad_(True) + expected, _ = attention(reference_input, position_embeddings=rope, attention_mask=reference_mask) + expected.square().sum().backward() + candidate_input = hidden.clone().requires_grad_(True) + actual, _ = dsa(candidate_input, position_embeddings=rope, position_ids=positions, **kwargs) + actual.square().sum().backward() + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-6) + torch.testing.assert_close(candidate_input.grad, reference_input.grad, rtol=1e-4, atol=1e-6) + fused_grad = torch.cat([attention.q_a_proj.weight.grad, attention.kv_a_proj_with_mqa.weight.grad]) + torch.testing.assert_close(dsa.linear_qkv.weight.grad, fused_grad, rtol=1e-4, atol=1e-6) + for name in ("q_b_proj", "kv_b_proj", "o_proj", "q_a_layernorm", "kv_a_layernorm"): + torch.testing.assert_close( + getattr(dsa, name).weight.grad, getattr(attention, name).weight.grad, rtol=1e-4, atol=1e-6 + ) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_sparse_and_dense_selection_match_transformers(self): + """Feature: DSA replacement parity. + + Description: Run sparse (top-k below length) and dense selection against the Transformers module. + Expectation: Outputs and every attention gradient match in FP32. + """ + for index_topk in (4, 64): + with self.subTest(index_topk=index_topk), reference_dsa_kernels(): + torch.manual_seed(0) + model = DeepseekV32ForCausalLM(_tiny_config(index_topk=index_topk)) + attention = model.model.layers[0].self_attn + dsa = _dsa_from(attention) + hidden, rope, positions = _attention_inputs(model) + causal = torch.ones(12, 12, dtype=torch.bool).tril().expand(2, 1, 12, 12) + self._assert_matches_reference(attention, dsa, hidden, rope, positions, causal) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_packed_documents_match_block_diagonal_attention(self): + """Feature: DSA packed-document boundaries. + + Description: Pass global cu_seq_lens through the runtime adapter for documents crossing rows. + Expectation: DSA equals Transformers attention under the matching block-diagonal mask. + """ + boundaries = torch.tensor([0, 5, 12, 15, 24], dtype=torch.int32) + runtime = DeepseekV32PackedSequence().build_runtime_inputs( + batch={"cu_seq_lens": boundaries}, context=None + ) + mask = torch.zeros(2, 1, 12, 12, dtype=torch.bool) + for start, end in zip(boundaries[:-1].tolist(), boundaries[1:].tolist()): + row, first = divmod(start, 12) + last = end - row * 12 + mask[row, 0, first:last, first:last] = torch.ones(last - first, last - first, dtype=torch.bool).tril() + with reference_dsa_kernels(): + torch.manual_seed(1) + model = DeepseekV32ForCausalLM(_tiny_config(index_topk=3)) + attention = model.model.layers[0].self_attn + dsa = _dsa_from(attention) + hidden, rope, positions = _attention_inputs(model) + self._assert_matches_reference(attention, dsa, hidden, rope, positions, mask, **runtime) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_indexer_loss_rejects_tensor_parallelism(self): + """Feature: DSA indexer KL loss ownership. + + Description: Request the trainable-indexer loss with and without TP. + Expectation: TP raises before construction; TP1 builds the replacement. + """ + with reference_dsa_kernels(): + attention = DeepseekV32ForCausalLM(_tiny_config()).model.layers[0].self_attn + attention.config.dsa_loss_coeff = 0.01 + with self.assertRaisesRegex(ValueError, "tp_size=1"): + replace_deepseek_v32_dsa_attention(module=attention, module_fqn="layer", context={"tp": True}) + replacement = replace_deepseek_v32_dsa_attention(module=attention, module_fqn="layer", context={}) + self.assertEqual(replacement.dsa_loss_coeff, 0.01) + + +if __name__ == "__main__": + unittest.main() From 512000abcae393950dfde7952be86d73641c5779 Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 01:28:12 -0600 Subject: [PATCH 02/20] test(deepseek_v32): give DSA reference stand-ins module specs 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. --- tests/common/dsa_reference_kernels.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/tests/common/dsa_reference_kernels.py b/tests/common/dsa_reference_kernels.py index a8db998279..53d779cc30 100644 --- a/tests/common/dsa_reference_kernels.py +++ b/tests/common/dsa_reference_kernels.py @@ -29,6 +29,7 @@ from __future__ import annotations import contextlib +import importlib.machinery import sys import types from collections.abc import Iterator @@ -214,21 +215,28 @@ def rotary_mul( return tensor * cos + rotated * sin +def _stub_module(name: str, *, is_package: bool = False) -> types.ModuleType: + """Return an empty stand-in whose spec satisfies ``importlib.util.find_spec`` probes.""" + module = types.ModuleType(name) + module.__spec__ = importlib.machinery.ModuleSpec(name, None, is_package=is_package) + return module + + def _stub_modules() -> dict[str, types.ModuleType]: """Build import stand-ins exposing only what the DSA path calls.""" - torch_npu = types.ModuleType("torch_npu") + torch_npu = _stub_module("torch_npu") torch_npu.npu_rotary_mul = rotary_mul torch_npu.npu_sparse_flash_attention = sparse_flash_attention torch_npu.npu_sparse_lightning_indexer_grad_kl_loss = _unsupported_indexer_loss - ops = types.ModuleType("cann_ops_transformer.ops") + ops = _stub_module("cann_ops_transformer.ops") ops.lightning_indexer = lightning_indexer ops.lightning_indexer_metadata = lightning_indexer_metadata ops.sparse_flash_attention_grad = sparse_flash_attention_grad - cann_ops_transformer = types.ModuleType("cann_ops_transformer") + cann_ops_transformer = _stub_module("cann_ops_transformer", is_package=True) cann_ops_transformer.ops = ops return { "torch_npu": torch_npu, - "omni_training_custom_ops": types.ModuleType("omni_training_custom_ops"), + "omni_training_custom_ops": _stub_module("omni_training_custom_ops"), "cann_ops_transformer": cann_ops_transformer, "cann_ops_transformer.ops": ops, } @@ -291,9 +299,10 @@ def reference_dsa_kernels() -> Iterator[None]: ``torch_npu``, custom-operator and ``cann_ops_transformer`` modules, so a stand-in left behind by another test cannot leak into them. The CANN wrappers import their operators when called, so the stand-ins stay in - ``sys.modules`` until the context exits. On exit every module that - captured a stand-in is evicted and the previous modules and lazily cached - package symbols are restored. + ``sys.modules`` until the context exits; their module specs keep + dependency probes such as ``importlib.util.find_spec`` working meanwhile. + On exit every module that captured a stand-in is evicted and the previous + modules and lazily cached package symbols are restored. """ previous_modules = dict(sys.modules) previous_packages = { From 9d258643623ba078327c3eebca2fdfa5da71d6a2 Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 01:28:13 -0600 Subject: [PATCH 03/20] feat(deepseek_v32): add single-card cropped training example 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). --- examples/training_demo/README.md | 39 +++++ .../deepseek_v32/cropped_deepseek_v32.py | 132 ++++++++++++++ .../deepseek_v32/prepare_single_card_data.py | 90 ++++++++++ .../deepseek_v32/run_single_card.sh | 75 ++++++++ .../deepseek_v32/train_single_card.yaml | 165 ++++++++++++++++++ .../models/deepseek_v32/recipes/train.yaml | 3 + .../deepseek_v32/test_cropped_deepseek_v32.py | 83 +++++++++ 7 files changed, 587 insertions(+) create mode 100644 examples/training_demo/deepseek_v32/cropped_deepseek_v32.py create mode 100644 examples/training_demo/deepseek_v32/prepare_single_card_data.py create mode 100755 examples/training_demo/deepseek_v32/run_single_card.sh create mode 100644 examples/training_demo/deepseek_v32/train_single_card.yaml create mode 100644 tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py diff --git a/examples/training_demo/README.md b/examples/training_demo/README.md index 0d68019a96..998921f655 100644 --- a/examples/training_demo/README.md +++ b/examples/training_demo/README.md @@ -5,6 +5,7 @@ recipes, data preparation, launchers, and validation manifests are grouped by family: - `qwen3_moe/`: cropped and full-model Qwen3-MoE text demos; +- `deepseek_v32/`: single-card cropped DeepSeek-V3.2 text demo; - `deepseek_v41/`: DeepSeek-V4.1 text/VLM crops and validation tooling. ## Qwen3-MoE cropped Hugging Face demos @@ -113,6 +114,44 @@ validates both Indexed Dataset files. Missing local assets therefore fail explicitly rather than triggering a network download. Additional typed Trainer overrides may be appended to either command. +## DeepSeek-V3.2 single-card crop + +The [single-card configuration](deepseek_v32/train_single_card.yaml) builds +DeepSeek-V3.2 with `HyperAutoModelForCausalLM.from_config` and random weights. +It keeps the released hidden, MLA, indexer, and vocabulary dimensions and crops +the model to two decoder layers (one dense, one MoE) and 16 routed experts, the +fewest that keep the released group routing (`n_group=8`, `topk_group=4`, +top-8). The model has 3.40B parameters; FP32 parameters, FP32 gradients and the +two FP32 AdamW moments take about 51 GiB before activations (estimated, not +measured), which targets one 64 GB device such as 910B3. + +Module replacements and the packed-data path match the full +[recipe](../../hyper_parallel/models/deepseek_v32/recipes/train.yaml): DSA reads +packed document boundaries from `DeepseekV32PackedSequence` rather than a dense +mask. DSA runs on the CANN backend, so load the CANN and ops-transformer +environment described in the +[functional README](../../hyper_parallel/components/functional/README.md#deepseek-v32-dsa) +before launching. Only `config.json` and the tokenizer files of the official +checkpoint directory are read: + +```bash +bash examples/training_demo/deepseek_v32/run_single_card.sh /path/to/DeepSeek-V3.2 + +# Supply an existing text JSONL instead of the generated data. +bash examples/training_demo/deepseek_v32/run_single_card.sh \ + /path/to/DeepSeek-V3.2 /path/to/text/train.jsonl +``` + +Without a dataset argument the launcher writes +`output/training_demo/deepseek_v32/single_card.jsonl`. Each generated record +tokenizes into two full 4096-token windows and a short tail: a full window is a +single document longer than `index_topk=2048`, so the indexer's top-k selection +is active, and tails from several records pack into one row to exercise the +document boundaries. The Online dataset holds `train_iters × global_batch_size` +records, so a JSONL whose records are much shorter than 4096 tokens packs +several records into each step and can run out before `train_iters`. The log is +written to `output/training_demo/deepseek_v32/run_single_card.log`. + ## DeepSeek-V4.1 text pretraining The [text configuration](deepseek_v41/train_deepseek_v41_online.yaml) retains all diff --git a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py new file mode 100644 index 0000000000..9f6828b685 --- /dev/null +++ b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py @@ -0,0 +1,132 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Build a depth- and expert-cropped DeepSeek-V3.2 model from configuration only.""" + +from __future__ import annotations + +from typing import Any + +from transformers import AutoConfig, PretrainedConfig, PreTrainedModel + +from hyper_parallel.models import HyperAutoModelForCausalLM + +# ``DeepseekV32Config.__post_init__`` derives these per-layer lists from the +# layer count and ``first_k_dense_replace``. Copying the released 61-entry +# lists into a cropped config would keep the released dense/MoE pattern, so +# they are re-derived instead. +_LAYER_DERIVED_FIELDS = ("mlp_layer_types", "layer_types") + + +def build_cropped_deepseek_v32_config( + config_path: str, + *, + num_hidden_layers: int, + first_k_dense_replace: int, + n_routed_experts: int, + local_files_only: bool = True, +) -> PretrainedConfig: + """Return the released DeepSeek-V3.2 configuration cropped in depth and experts. + + Hidden, MLA, indexer and vocabulary dimensions stay as released. The FP8 + ``quantization_config`` describes the released checkpoint storage rather + than this randomly initialized model, so it is dropped. + + Args: + config_path: Hugging Face DeepSeek-V3.2 directory or repository id. + num_hidden_layers: Decoder layers retained in the cropped model. + first_k_dense_replace: Leading layers that keep the dense MLP; the + remaining layers use the MoE block. + n_routed_experts: Routed experts per MoE layer. The released group + routing scores each of ``n_group`` groups by its top-2 experts and + keeps ``topk_group`` groups, so every group needs two experts and + the kept groups must hold ``num_experts_per_tok`` experts. + local_files_only: Disable implicit Hub downloads when true. + + Returns: + The cropped configuration with ``use_cache`` disabled. + """ + released = AutoConfig.from_pretrained( + config_path, + local_files_only=local_files_only, + trust_remote_code=False, + ) + if getattr(released, "model_type", None) != "deepseek_v32": + raise ValueError( + "config_path must contain a DeepSeek-V3.2 configuration; " + f"got model_type={getattr(released, 'model_type', None)!r}" + ) + if num_hidden_layers <= 0 or not 0 <= first_k_dense_replace <= num_hidden_layers: + raise ValueError( + "need num_hidden_layers > 0 and 0 <= first_k_dense_replace <= num_hidden_layers; " + f"got num_hidden_layers={num_hidden_layers}, first_k_dense_replace={first_k_dense_replace}" + ) + experts_per_group, remainder = divmod(n_routed_experts, released.n_group) + if remainder or experts_per_group < 2 or experts_per_group * released.topk_group < released.num_experts_per_tok: + raise ValueError( + f"n_routed_experts={n_routed_experts} cannot keep the released routing " + f"(n_group={released.n_group}, topk_group={released.topk_group}, " + f"num_experts_per_tok={released.num_experts_per_tok}): it must be a multiple of n_group " + "with at least two experts per group, and topk_group groups must hold num_experts_per_tok experts" + ) + + values = released.to_dict() + for name in (*_LAYER_DERIVED_FIELDS, "quantization_config"): + values.pop(name, None) + values.update( + num_hidden_layers=num_hidden_layers, + first_k_dense_replace=first_k_dense_replace, + n_routed_experts=n_routed_experts, + use_cache=False, + ) + return type(released).from_dict(values) + + +def build_cropped_deepseek_v32( + config_path: str, + *, + num_hidden_layers: int = 2, + first_k_dense_replace: int = 1, + n_routed_experts: int = 16, + local_files_only: bool = True, + **build_kwargs: Any, +) -> PreTrainedModel: + """Create a randomly initialized cropped DeepSeek-V3.2 model. + + The function calls ``from_config`` instead of ``from_pretrained``: it + reads only the Hugging Face configuration from ``config_path`` and loads + no checkpoint tensor. + + Args: + config_path: Local Hugging Face DeepSeek-V3.2 directory. + num_hidden_layers: Decoder layers retained in the cropped model. + first_k_dense_replace: Leading dense-MLP layers. + n_routed_experts: Routed experts per MoE layer. + local_files_only: Disable implicit Hub downloads when true. + **build_kwargs: ``HyperAutoModelForCausalLM.from_config`` options, both + those set in YAML (``torch_dtype``, ``attn_implementation``, + ``validate_placement``) and those the Trainer injects + (``distributed_setup``, ``activation_checkpoint``, ...). + + Returns: + A parallelized, randomly initialized cropped DeepSeek-V3.2 model. + """ + config = build_cropped_deepseek_v32_config( + config_path, + num_hidden_layers=num_hidden_layers, + first_k_dense_replace=first_k_dense_replace, + n_routed_experts=n_routed_experts, + local_files_only=local_files_only, + ) + return HyperAutoModelForCausalLM.from_config(config, **build_kwargs) diff --git a/examples/training_demo/deepseek_v32/prepare_single_card_data.py b/examples/training_demo/deepseek_v32/prepare_single_card_data.py new file mode 100644 index 0000000000..7dcc372d60 --- /dev/null +++ b/examples/training_demo/deepseek_v32/prepare_single_card_data.py @@ -0,0 +1,90 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Generate deterministic documents for the DeepSeek-V3.2 single-card demo.""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Sequence + +from transformers import AutoTokenizer + + +def prepare_single_card_data( + output_path: Path, + tokenizer_path: str, + *, + num_samples: int = 64, + sequence_length: int = 4096, +) -> None: + """Write JSONL records that reach both DSA attention patterns. + + Each record tokenizes to about ``2 * sequence_length + sequence_length // 4`` + tokens, which the Online transform cuts into two full windows and a short + tail. A full window is a single document longer than ``index_topk`` (2048 + in the released config), so the indexer's top-k selection is active; the + tails of several records pack into one row and exercise the per-document + boundaries. + + Args: + output_path: JSONL file to create. + tokenizer_path: Local DeepSeek-V3.2 tokenizer directory used to size records. + num_samples: Number of records. + sequence_length: Model sequence length (``data_transform.max_seq_len``). + """ + if num_samples <= 0 or sequence_length <= 0: + raise ValueError("num_samples and sequence_length must be positive") + tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, local_files_only=True, trust_remote_code=False) + target_tokens = 2 * sequence_length + sequence_length // 4 + output_path.parent.mkdir(parents=True, exist_ok=True) + with output_path.open("w", encoding="utf-8") as output_file: + for sample_index in range(num_samples): + sentence = ( + f"DeepSeek-V3.2 single-card document {sample_index}: the lightning indexer scores " + "earlier tokens and sparse attention keeps the strongest candidates. " + ) + first = len(tokenizer.encode(sentence, add_special_tokens=False)) + # Repeated sentences merge at their boundary; measure the steady-state length. + repeated = len(tokenizer.encode(sentence * 2, add_special_tokens=False)) - first + repeats = 1 + math.ceil((target_tokens - first) / repeated) + output_file.write(json.dumps({"text": sentence * repeats}) + "\n") + + +def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: + """Parse command-line arguments.""" + parser = argparse.ArgumentParser(description="Prepare DeepSeek-V3.2 single-card demo data") + parser.add_argument("--output", required=True) + parser.add_argument("--tokenizer-path", required=True) + parser.add_argument("--num-samples", type=int, default=64) + parser.add_argument("--sequence-length", type=int, default=4096) + return parser.parse_args(argv) + + +def main(argv: Sequence[str] | None = None) -> None: + """Generate the requested JSONL dataset.""" + args = _parse_args(argv) + prepare_single_card_data( + Path(args.output).expanduser().resolve(), + args.tokenizer_path, + num_samples=args.num_samples, + sequence_length=args.sequence_length, + ) + + +if __name__ == "__main__": + main() diff --git a/examples/training_demo/deepseek_v32/run_single_card.sh b/examples/training_demo/deepseek_v32/run_single_card.sh new file mode 100755 index 0000000000..455c8e8fef --- /dev/null +++ b/examples/training_demo/deepseek_v32/run_single_card.sh @@ -0,0 +1,75 @@ +#!/bin/bash +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ + +set -euo pipefail + +# Keep generated data and run outputs under the repository output directory. +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +PROJECT_ROOT=$(cd "${SCRIPT_DIR}/../../.." && pwd) +OUTPUT_DIR=${OUTPUT_DIR:-"${PROJECT_ROOT}/output/training_demo/deepseek_v32"} +DEFAULT_DATA_PATH="${OUTPUT_DIR}/single_card.jsonl" +PYTHON_BIN=${PYTHON_BIN:-python} + +if [[ $# -lt 1 ]]; then + echo "Usage: $0 /path/to/DeepSeek-V3.2 [path/to/train.jsonl] [trainer overrides...]" >&2 + exit 1 +fi + +# Resolve input paths before switching to the repository root. +MODEL_PATH=$1 +shift +DATA_PATH="${DEFAULT_DATA_PATH}" +if [[ $# -gt 0 && ${1} != --* ]]; then + DATA_PATH=$1 + if [[ ! -s "${DATA_PATH}" ]]; then + echo "Text JSONL data is missing or empty: ${DATA_PATH}" >&2 + exit 1 + fi + shift +fi +MODEL_PATH=$(cd "${MODEL_PATH}" 2>/dev/null && pwd) || { + echo "Model directory does not exist: ${MODEL_PATH}" >&2 + exit 1 +} +if [[ "${DATA_PATH}" != /* ]]; then + DATA_PATH="${PWD}/${DATA_PATH}" +fi +if [[ ! -s "${MODEL_PATH}/config.json" || ! -s "${MODEL_PATH}/tokenizer.json" ]]; then + echo "Local DeepSeek-V3.2 config/tokenizer assets are incomplete: ${MODEL_PATH}" >&2 + exit 1 +fi + +cd "${PROJECT_ROOT}" +mkdir -p "${OUTPUT_DIR}" +# Generate deterministic text samples when the default dataset is absent. +if [[ ! -s "${DATA_PATH}" ]]; then + "${PYTHON_BIN}" -m examples.training_demo.deepseek_v32.prepare_single_card_data \ + --output "${DATA_PATH}" \ + --tokenizer-path "${MODEL_PATH}" +fi + +# Launch with the YAML settings; trailing Trainer arguments override its defaults. +"${PYTHON_BIN}" -m torch.distributed.run \ + --standalone \ + --nproc_per_node=1 \ + --module examples.training_demo.train_text \ + "${SCRIPT_DIR}/train_single_card.yaml" \ + --model.config_path="${MODEL_PATH}" \ + --dataset.model_assets.tokenizer.pretrained_model_name_or_path="${MODEL_PATH}" \ + --dataset.data_path="${DATA_PATH}" \ + --checkpoint.checkpoint_dir="${OUTPUT_DIR}/checkpoints" \ + "$@" \ + 2>&1 | tee "${OUTPUT_DIR}/run_single_card.log" diff --git a/examples/training_demo/deepseek_v32/train_single_card.yaml b/examples/training_demo/deepseek_v32/train_single_card.yaml new file mode 100644 index 0000000000..e9a9dd7367 --- /dev/null +++ b/examples/training_demo/deepseek_v32/train_single_card.yaml @@ -0,0 +1,165 @@ +# DeepSeek-V3.2 单卡裁剪示例:from_config 随机初始化,不加载 checkpoint。 +# +# 保留官方 config 的 hidden、MLA、indexer 和词表维度,只裁成 2 层(第 0 层 dense、 +# 第 1 层 MoE)和 16 个路由专家;16 是保持官方分组路由(n_group=8、topk_group=4、 +# top-8)的最小专家数。共 3.40B 参数,FP32 参数 + FP32 梯度 + AdamW 两个 FP32 动量 +# ≈ 16 B/param,约 51 GiB,再加激活(未实测),面向 64 GB 单卡(如 910B3)。 +# +# 模块替换与 packed 数据路径和完整配方 hyper_parallel/models/deepseek_v32/recipes/train.yaml +# 一致;单卡没有 TP/CP/EP,所以不带 `when: cp` / `when: ep` 条目。 +# +# 启动(只需要官方目录里的 config.json 和 tokenizer 文件,不需要权重): +# bash examples/training_demo/deepseek_v32/run_single_card.sh /path/to/DeepSeek-V3.2 + +model: + _target_: examples.training_demo.deepseek_v32.cropped_deepseek_v32.build_cropped_deepseek_v32 + config_path: /path/to/DeepSeek-V3.2 + num_hidden_layers: 2 + first_k_dense_replace: 1 + n_routed_experts: 16 + local_files_only: true + torch_dtype: bfloat16 + # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 + attn_implementation: sdpa + validate_placement: false + +model_init_dtype: float32 + +training: + train_iters: 10 + train_samples: null + eval_iters: 0 + global_batch_size: 1 + micro_batch_size: 1 + backend: hccl + init_device: meta + loss_aggregation: token_weighted + max_grad_norm: 1.0 + seed: 42 + enable_full_determinism: true + +accelerator: + tp_size: 1 + cp_size: 1 + ep_size: 1 + pp_size: 1 + sequence_parallel: false + loss_parallel: false + +fsdp_config: + dp_shard_size: 1 + edp_shard_size: 1 + replicate_params: [] + mix_precision: + param_dtype: bfloat16 + reduce_dtype: float32 + cast_forward_inputs: false + reshard_after_forward: true + reshard_after_backward: true + requires_grad_sync: true + forward_prefetch_depth: 1 + backward_prefetch_depth: 1 + comm_fusion: false + +plan_overrides: + - match: + - "*.input_layernorm" + - "*.post_attention_layernorm" + - model.norm + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_rms_norm + - match: "*.self_attn" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + - match: "*.mlp.experts" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_grouped_experts + +mixed_precision: + enabled: false + +activation_checkpoint: + mode: full + +activation_swap: none + +dataset: + model_assets: + chat_template: null + tokenizer: + _target_: hyper_parallel.data.text.build_tokenizer.AutoTokenizer.from_pretrained + pretrained_model_name_or_path: /path/to/DeepSeek-V3.2 + local_files_only: true + use_fast: true + trust_remote_code: false + data_transform: + _target_: hyper_parallel.data.text.text_transform.build_text_transform + data_type: plaintext + text_keys: text + max_seq_len: 4096 + _target_: hyper_parallel.data.text.build_dataset.build_online_text_mapping_dataset + # run_single_card.sh 缺省时用 prepare_single_card_data.py 生成:每条记录切成两个完整 + # 4096 窗口(单文档,超过 index_topk=2048,走稀疏选择)和一个短尾巴(多条尾巴拼成一行)。 + data_path: ./output/training_demo/deepseek_v32/single_card.jsonl + data_config: + labels_are_shifted: true + create_attention_mask_in_dataloader: false + create_ltor_fields_in_dataloader: false + +dataloader: + _target_: hyper_parallel.data.batching.TokenBatchLoader + min_buffered_samples: 8 + collate_fn: + _target_: hyper_parallel.data.batching.build_online_text_collate_fn + get_batch: + _target_: hyper_parallel.data.batching.TextParallelBatch + source_type: online + # DSA 从累计序列长度推导因果与文档边界,不需要 [S, S] 稠密 mask。 + attention_mode: compressed + runtime_input_adapter: + _target_: hyper_parallel.models.deepseek_v32.adapter.data.runtime.DeepseekV32PackedSequence + sampler_type: single + data_rearrange_map: null + data_sharding: false + drop_last: true + use_background_prefetcher: false + num_workers: 0 + pin_memory: false + prefetch_factor: null + +optimizer: + _target_: hyper_parallel.components.optim.AdamW + fp32_main_params: true + no_decay_params: [bias, norm, ln_] + adamw_config: + lr: 1.0e-5 + adamw_lr: 1.0e-5 + adamw_weight_decay: 0.01 + adamw_betas: [0.9, 0.999] + adamw_eps: 1.0e-8 + +lr_scheduler: + _target_: hyper_parallel.components.optim.MultiLRScheduler + lr_decay_style: cosine + lr_config: + lr: 1.0e-5 + lr_warmup_steps: 1 + min_lr: 0.0 + +checkpoint: + save_ckpt: false + checkpoint_dir: ./output/training_demo/deepseek_v32/checkpoints + restore_from: null + +debug: + check_nan_inf: false + check_dataset: null diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index c3ca9bb7bc..ee32abd0ff 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -24,6 +24,9 @@ # scripts/train_lm.py \ # --model.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 \ # --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 +# +# 单卡裁剪示例(2 层、16 个路由专家、随机初始化)见 +# examples/training_demo/deepseek_v32/train_single_card.yaml。 model: _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained diff --git a/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py b/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py new file mode 100644 index 0000000000..e41ec6c2bf --- /dev/null +++ b/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py @@ -0,0 +1,83 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Single-card DeepSeek-V3.2 crop: per-layer MLP pattern and routing constraints.""" + +import tempfile +import unittest + +import torch +from transformers import DeepseekV32Config, DeepseekV32ForCausalLM +from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32MLP, DeepseekV32MoE + +from examples.training_demo.deepseek_v32.cropped_deepseek_v32 import build_cropped_deepseek_v32_config +from tests.common.mark_utils import arg_mark + + +def _save_released_shape(directory: str) -> None: + """Save a narrow configuration with the released depth pattern, routing and FP8 storage.""" + DeepseekV32Config.from_dict({ + "vocab_size": 96, "hidden_size": 48, "intermediate_size": 64, "moe_intermediate_size": 16, + "num_hidden_layers": 5, "first_k_dense_replace": 3, "num_attention_heads": 4, "num_key_value_heads": 4, + "n_shared_experts": 1, "n_routed_experts": 32, "n_group": 8, "topk_group": 4, "num_experts_per_tok": 8, + "kv_lora_rank": 16, "q_lora_rank": 24, "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, + "index_topk": 4, "index_head_dim": 16, "index_n_heads": 4, + "quantization_config": {"quant_method": "fp8", "fmt": "e4m3", "weight_block_size": [128, 128]}, + }).save_pretrained(directory) + + +class TestCroppedDeepseekV32Config(unittest.TestCase): + """The crop must re-derive the dense/MoE layout instead of keeping the released one.""" + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_crop_builds_one_dense_and_one_moe_layer(self): + """ + Feature: Single-card DeepSeek-V3.2 crop. + Description: Crop a released-shaped configuration to two layers, the first dense, with 16 experts. + Expectation: Layer 1 is a 16-expert MoE block, widths are unchanged and the FP8 storage is dropped. + """ + with tempfile.TemporaryDirectory() as directory: + _save_released_shape(directory) + config = build_cropped_deepseek_v32_config( + directory, num_hidden_layers=2, first_k_dense_replace=1, n_routed_experts=16, + ) + with torch.device("meta"): + model = DeepseekV32ForCausalLM(config) + self.assertIsInstance(model.model.layers[0].mlp, DeepseekV32MLP) + self.assertIsInstance(model.model.layers[1].mlp, DeepseekV32MoE) + self.assertEqual(model.model.layers[1].mlp.experts.gate_up_proj.shape[0], 16) + self.assertEqual(config.hidden_size, 48) + self.assertIsNone(getattr(config, "quantization_config", None)) + self.assertFalse(config.use_cache) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_rejects_expert_counts_that_break_group_routing(self): + """ + Feature: Single-card DeepSeek-V3.2 crop. + Description: Request expert counts below two per group or not divisible by n_group. + Expectation: The crop fails before any model is built. + """ + with tempfile.TemporaryDirectory() as directory: + _save_released_shape(directory) + for experts in (8, 12): + with self.subTest(n_routed_experts=experts), self.assertRaisesRegex(ValueError, "n_group=8"): + build_cropped_deepseek_v32_config( + directory, num_hidden_layers=2, first_k_dense_replace=1, n_routed_experts=experts, + ) + + +if __name__ == "__main__": + unittest.main() From 02cfbab407b4f174f9eb4b4e31557e71adb7767c Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 02:38:18 -0600 Subject: [PATCH 04/20] fix(dsa): import same-named DSA functions from their submodules 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. --- .../components/modules/dsa_attention.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/hyper_parallel/components/modules/dsa_attention.py b/hyper_parallel/components/modules/dsa_attention.py index 5b158ad016..e6f0568264 100644 --- a/hyper_parallel/components/modules/dsa_attention.py +++ b/hyper_parallel/components/modules/dsa_attention.py @@ -28,14 +28,16 @@ from hyper_parallel.components.checkpoint import ConcatenateWithSections from hyper_parallel.models.replacement import module_replacement -from hyper_parallel.components.functional import aggregate_hidden, aux_loss_auto_scale +from hyper_parallel.components.functional import aux_loss_auto_scale from hyper_parallel.components.functional import apply_rotary_pos_emb, apply_rotary_pos_emb_interleave -from hyper_parallel.components.functional import ( - dsa_indexer, - dsa_kl_loss, - dsa_sparse_attention, - dsa_sparse_attention_rescale, -) +# Exports that share their submodule's name come from the submodule: once that +# submodule is imported elsewhere first (the DeepSeek-V3.2 CP wrapper does), the +# package attribute of that name is the module object, not the function. +from hyper_parallel.components.functional.aggregate_hidden import aggregate_hidden +from hyper_parallel.components.functional.dsa_indexer import dsa_indexer +from hyper_parallel.components.functional.dsa_kl_loss import dsa_kl_loss +from hyper_parallel.components.functional.dsa_sparse_attention import dsa_sparse_attention +from hyper_parallel.components.functional.dsa_sparse_attention_rescale import dsa_sparse_attention_rescale from hyper_parallel.components.functional.npu_fusion_attention import resolve_packed_sequence_lengths From c97bdb0ac81f84c3bb35e91a5862738da78c785b Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 02:38:18 -0600 Subject: [PATCH 05/20] test(deepseek_v32): load the single-card example by file path 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. --- .../models/deepseek_v32/test_cropped_deepseek_v32.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py b/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py index e41ec6c2bf..3ea5df81b6 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py @@ -14,16 +14,26 @@ # ============================================================================ """Single-card DeepSeek-V3.2 crop: per-layer MLP pattern and routing constraints.""" +import importlib.util import tempfile import unittest +from pathlib import Path import torch from transformers import DeepseekV32Config, DeepseekV32ForCausalLM from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32MLP, DeepseekV32MoE -from examples.training_demo.deepseek_v32.cropped_deepseek_v32 import build_cropped_deepseek_v32_config from tests.common.mark_utils import arg_mark +# Load the example by path: `examples` is also the RL package name that +# tests/ut/rl/conftest.py puts on sys.path, so importing it by name would +# bind whichever package a pytest session imports first. +_BUILDER = Path(__file__).resolve().parents[5] / "examples/training_demo/deepseek_v32/cropped_deepseek_v32.py" +_SPEC = importlib.util.spec_from_file_location("_cropped_deepseek_v32_example", _BUILDER) +_EXAMPLE = importlib.util.module_from_spec(_SPEC) +_SPEC.loader.exec_module(_EXAMPLE) +build_cropped_deepseek_v32_config = _EXAMPLE.build_cropped_deepseek_v32_config + def _save_released_shape(directory: str) -> None: """Save a narrow configuration with the released depth pattern, routing and FP8 storage.""" From b6e26fb7e20b414c1cccd16dadba0f07b7202533 Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 02:38:18 -0600 Subject: [PATCH 06/20] fix(deepseek_v32): run every recipe step and correct the expert sharding 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. --- docs/feature_status.md | 2 +- examples/training_demo/README.md | 9 +++-- .../deepseek_v32/train_single_card.yaml | 8 ++-- .../models/deepseek_v32/recipes/train.yaml | 39 ++++++++++--------- 4 files changed, 30 insertions(+), 28 deletions(-) diff --git a/docs/feature_status.md b/docs/feature_status.md index ea1c28398b..8c11c1ee82 100644 --- a/docs/feature_status.md +++ b/docs/feature_status.md @@ -5,7 +5,7 @@ ## 支持模型 - [x] Qwen3-30B-A3B -- [x] DeepSeek-V3.2(DSA + MoE,TP/CP/EP/FSDP) +- [x] DeepSeek-V3.2(DSA + MoE;TP/CP/EP/FSDP 在 CPU/Gloo 上与单卡结果对齐,NPU 端到端未验证) ## HyperShard diff --git a/examples/training_demo/README.md b/examples/training_demo/README.md index 998921f655..ed934f6690 100644 --- a/examples/training_demo/README.md +++ b/examples/training_demo/README.md @@ -125,10 +125,11 @@ top-8). The model has 3.40B parameters; FP32 parameters, FP32 gradients and the two FP32 AdamW moments take about 51 GiB before activations (estimated, not measured), which targets one 64 GB device such as 910B3. -Module replacements and the packed-data path match the full -[recipe](../../hyper_parallel/models/deepseek_v32/recipes/train.yaml): DSA reads -packed document boundaries from `DeepseekV32PackedSequence` rather than a dense -mask. DSA runs on the CANN backend, so load the CANN and ops-transformer +Module replacements match the full +[recipe](../../hyper_parallel/models/deepseek_v32/recipes/train.yaml). Unlike its +one-line-per-row default data, this example packs documents into 4096-token rows, +and DSA reads their boundaries from `DeepseekV32PackedSequence` rather than a +dense mask. DSA runs on the CANN backend, so load the CANN and ops-transformer environment described in the [functional README](../../hyper_parallel/components/functional/README.md#deepseek-v32-dsa) before launching. Only `config.json` and the tokenizer files of the official diff --git a/examples/training_demo/deepseek_v32/train_single_card.yaml b/examples/training_demo/deepseek_v32/train_single_card.yaml index e9a9dd7367..10bba7cb83 100644 --- a/examples/training_demo/deepseek_v32/train_single_card.yaml +++ b/examples/training_demo/deepseek_v32/train_single_card.yaml @@ -5,8 +5,9 @@ # top-8)的最小专家数。共 3.40B 参数,FP32 参数 + FP32 梯度 + AdamW 两个 FP32 动量 # ≈ 16 B/param,约 51 GiB,再加激活(未实测),面向 64 GB 单卡(如 910B3)。 # -# 模块替换与 packed 数据路径和完整配方 hyper_parallel/models/deepseek_v32/recipes/train.yaml -# 一致;单卡没有 TP/CP/EP,所以不带 `when: cp` / `when: ep` 条目。 +# 模块替换与完整配方 hyper_parallel/models/deepseek_v32/recipes/train.yaml 一致;数据用 +# TokenBatchLoader 把多个文档拼成 4096 token 的行,文档边界由 DeepseekV32PackedSequence +# 传给 DSA。单卡没有 TP/CP/EP,所以不带 `when: cp` / `when: ep` 条目。 # # 启动(只需要官方目录里的 config.json 和 tokenizer 文件,不需要权重): # bash examples/training_demo/deepseek_v32/run_single_card.sh /path/to/DeepSeek-V3.2 @@ -112,7 +113,6 @@ dataset: data_path: ./output/training_demo/deepseek_v32/single_card.jsonl data_config: labels_are_shifted: true - create_attention_mask_in_dataloader: false create_ltor_fields_in_dataloader: false dataloader: @@ -123,7 +123,7 @@ dataloader: get_batch: _target_: hyper_parallel.data.batching.TextParallelBatch source_type: online - # DSA 从累计序列长度推导因果与文档边界,不需要 [S, S] 稠密 mask。 + # DSA 只检查 attention_mask 的形状、不读内容;文档边界由下面的 runtime adapter 以 cu_seq_lens 传入。 attention_mode: compressed runtime_input_adapter: _target_: hyper_parallel.models.deepseek_v32.adapter.data.runtime.DeepseekV32PackedSequence diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index ee32abd0ff..b71692d1e3 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -2,25 +2,27 @@ # # 主线拓扑:64 节点 / 512 卡 Ascend NPU(hccl backend)。 # dense 区域:tp 1 × cp 1 × dp 512,FSDP 在 512 卡上切分; -# 专家区域:ep 64 × edp 8(edp = dp*cp*tp/ep),edp 维度再做 FSDP 切分。 -# 显存估算(未在本配方上实测,按需在目标集群确认):FP32 参数 + FP32 main grad -# + AdamW 两个 FP32 动量 ≈ 16 B/param;256 个路由专家(约 654B 参数)由 -# ep 64 × edp_shard 8 摊到每卡约 1.28B 参数(≈ 20 GB),dense 部分约 18B 参数在 -# 512 卡上可忽略,再加 4K 序列全重计算激活,单卡约 30 GB。 +# 专家区域:ep 64 × edp 8(edp = dp*cp*tp/ep)。每个 EP rank 持有 256/64 = 4 个专家, +# edp 内按 edp_shard 4 × 副本 2 做 HSDP,每卡每个 MoE 层恰好 1 个专家。 +# 显存估算(未在本配方上实测,按需在目标集群确认):FP32 参数 + FP32 梯度 +# + AdamW 两个 FP32 动量 ≈ 16 B/param。58 个 MoE 层 × 每卡 1 个专家 ≈ 2.55B 参数 +# (≈ 41 GB);dense 部分约 18B 参数切到 512 卡上约 35M(≈ 0.6 GB);激活另计。 # # 其它并行维度都通过 CLI dotted override 打开,无需维护第二份配置: -# TP/loss parallel:--accelerator.tp_size=2 --accelerator.loss_parallel=true;DSA 暂不支持 +# TP/loss parallel:--accelerator.tp_size=2 --accelerator.loss_parallel=true +# --fsdp_config.dp_shard_size=256(dp 随 TP 减半);DSA 暂不支持 # sequence parallel。 # MoE 层在 TP 下走 TP-extend-EP(专家只按 ep 切),因此 tp_size>1 时 ep_size # 必须 >1;fused gate_up 专家不能直接做 TP 切分(planner 会给出明确报错)。 # CP:--accelerator.cp_size=2,下方 `when: cp` 的 DSA CP wrapper 自动生效; # EP:--accelerator.ep_size 与 --fsdp_config.edp_shard_size 一起调整。 # 修改拓扑时保持 world_size = tp*cp*dp、dp*cp 可被 dp_shard_size 整除、 -# dp*cp*tp/ep 可被 edp_shard_size 整除、256 个专家可被 ep_size 整除,且 -# global_batch_size 可被 micro_batch_size*dp 整除。 +# dp*cp*tp/ep 可被 edp_shard_size 整除、256 个专家可被 ep_size 整除、 +# 256/ep_size 可被 edp_shard_size 整除(否则 FSDP 按第 0 维切专家时会补齐空数据), +# 且 global_batch_size 可被 micro_batch_size*dp 整除。 # -# 默认加载公开 Hugging Face 资源(模型、tokenizer、dataset)。本地或离线资源 -# 用命令行覆盖,例如: +# 默认加载公开 Hugging Face 资源(模型、tokenizer、dataset)。默认数据是 wikitext-2 +# 的逐行文本,每行一个样本,只用于跑通流程。本地或离线资源用命令行覆盖,例如: # scripts/train_lm.py \ # --model.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 \ # --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 @@ -60,7 +62,7 @@ accelerator: fsdp_config: dp_shard_size: 512 - edp_shard_size: 8 + edp_shard_size: 4 replicate_params: [] mix_precision: param_dtype: bfloat16 @@ -109,15 +111,16 @@ plan_overrides: _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper # null follows dsa_dense_warm_up; true/false forces one path for the full run. dense_warmup: null - # EP:只匹配 MoE 层。DeepSeek-V3.2 的 first_k_dense_replace=3,层 0-2 为稠密 MLP, - # 层 3-60 为 MoE;fnmatch 不支持数值区间,因此分两条 glob 覆盖 3-9 与 10-99。 + # EP:DeepSeek-V3.2 的 router 与 DeepSeek-V3 相同,直接用框架内置的 V3 EP 工厂。 + # 只匹配 MoE 层:first_k_dense_replace=3,层 0-2 为稠密 MLP,层 3-60 为 MoE; + # fnmatch 不支持数值区间,因此分两条 glob 覆盖 3-9 与 10-99。 # 裁剪模型改变稠密层数时需要同步调整这两条 glob。 - match: "model.layers.[3-9].mlp.forward" when: ep replace: kind: method implementation: - _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - match: "model.layers.[1-9][0-9].mlp.forward" @@ -125,7 +128,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true @@ -163,20 +166,18 @@ dataset: config_name: wikitext-2-raw-v1 cache_dir: null labels_are_shifted: true - create_attention_mask_in_dataloader: false create_ltor_fields_in_dataloader: false _target_: hyper_parallel.data.text.build_dataset.build_online_text_mapping_dataset data_path: Salesforce/wikitext dataloader: - _target_: hyper_parallel.data.batching.TokenBatchLoader - min_buffered_samples: 200 + _target_: hyper_parallel.data.batching.FixedBatchDataLoader collate_fn: _target_: hyper_parallel.data.batching.build_online_text_collate_fn get_batch: _target_: hyper_parallel.data.batching.TextParallelBatch source_type: online - # DSA 从累计序列长度推导因果与文档边界,不需要 [S, S] 稠密 mask。 + # DSA 只检查 attention_mask 的形状、不读内容;文档边界由下面的 runtime adapter 以 cu_seq_lens 传入。 attention_mode: compressed runtime_input_adapter: _target_: hyper_parallel.models.deepseek_v32.adapter.data.runtime.DeepseekV32PackedSequence From 775c3002707117abae84bc60ecdd8f78f75af4c0 Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 02:38:18 -0600 Subject: [PATCH 07/20] refactor(deepseek_v32): drop adapter code the framework covers; check 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. --- .../references/known-models.md | 2 +- .../adapter/conversion/module_replacement.py | 18 +- .../adapter/distributed/expert_parallel.py | 104 ---------- .../deepseek_v32/adapter/policies/sharding.py | 11 +- .../deepseek_v32/adapter/registration.py | 10 - tests/common/dsa_reference_kernels.py | 25 ++- .../_test_deepseek_v32_parallel.py | 196 +++++++++--------- .../test_deepseek_v32_parallel.py | 7 +- .../test_deepseek_v32_adapter_contracts.py | 43 +--- 9 files changed, 128 insertions(+), 288 deletions(-) delete mode 100644 hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py diff --git a/.agent/skills/parallel-strategy-analyzer/references/known-models.md b/.agent/skills/parallel-strategy-analyzer/references/known-models.md index 725ca12b48..bd01404a94 100644 --- a/.agent/skills/parallel-strategy-analyzer/references/known-models.md +++ b/.agent/skills/parallel-strategy-analyzer/references/known-models.md @@ -63,7 +63,7 @@ V3.2 keeps MLA and adds a Lightning Indexer that selects `index_topk` keys per q | index_head_dim | 128 | | index_topk | 2048 | -**Impact on parallel strategy**: attention score memory and compute scale with `s × index_topk` instead of `s²` once `s > index_topk`; the indexer itself still scores `s²` pairs with `index_n_heads × index_head_dim`. Under CP the indexer keys (`index_head_dim` per token) are all-gathered alongside the MLA latent KV. The indexer heads stay replicated under TP, and the trainable indexer KL loss needs every attention head on one rank, so it is incompatible with `tp_size > 1`. +**Impact on parallel strategy**: attention score memory and compute scale with `s × index_topk` instead of `s²` once `s > index_topk`; the indexer itself still scores `s²` pairs with `index_n_heads × index_head_dim`. Under CP the indexer keys (`index_head_dim` per token) are all-gathered alongside the MLA latent KV. The indexer heads stay replicated under TP. HyperParallel's fused indexer KL operator has no TP reduction, so training the indexer with the KL loss requires `tp_size=1`. ### GQA (Grouped Query Attention) — LLaMA-2/3, Qwen3/3.5 diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py index b2a016581d..c24a926ef4 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py @@ -42,23 +42,7 @@ def replace_deepseek_v32_dsa_attention( module_fqn: str, context: Mapping[str, Any], ) -> nn.Module: - """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module. - - The indexer KL loss distils the attention distribution summed over every - head. Tensor parallelism leaves each rank a subset of the heads and the - fused KL operator has no cross-rank reduction, so the trainable-indexer - loss is rejected together with ``tp_size > 1``. - """ - config = module.config - indexer_loss = getattr(config, "dsa_loss_coeff", 0.0) and not getattr( - config, "freeze_DSA", getattr(config, "freeze_dsa", False) - ) - if indexer_loss and context.get("tp", False): - raise ValueError( - f"{module_fqn}: the DeepSeek-V3.2 indexer KL loss (dsa_loss_coeff=" - f"{config.dsa_loss_coeff}) needs every attention head on one rank; " - "train it with tp_size=1 or set dsa_loss_coeff=0 / freeze_dsa=true" - ) + """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module.""" from hyper_parallel.components.modules import DeepseekV32DSAAttention # pylint: disable=C0415 return DeepseekV32DSAAttention(module=module, module_fqn=module_fqn, context=context) diff --git a/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py b/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py deleted file mode 100644 index 919de52f61..0000000000 --- a/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""DeepSeek-V3.2 expert-parallel compute factory. - -``DeepseekV32TopkRouter`` already returns the complete DeepSeek routing -decision ``(router_logits, topk_weights, topk_indices)``: sigmoid scores, the -``e_score_correction_bias`` used only for selection, group-limited top-k, -normalisation and ``routed_scaling_factor``. The factory consumes that decision -through the generic ``topk_router_module`` adapter instead of re-deriving it, so -the EP block evaluates the router once and selects exactly the experts and -weights of the non-EP block. Token dispatch, the local expert GEMMs and the -combine come from the generic EP skeleton; the shared experts are added to the -routed output as ``DeepseekV32MoE.forward`` does. -""" - -from typing import Any, Callable, Optional - -import torch # pylint: disable=forbidden-backend-import - -from hyper_parallel.distributed.expert_parallel.recipes import build_ep_compute -from hyper_parallel.distributed.recipe_spec import local_compute - - -@local_compute -def deepseek_v32_ep_compute_fn( - *, - module: Any, - mesh: Any, - tp_mesh: Any, - cp_mesh: Any, - ep_mesh: Any, - use_grouped_gemm: bool = False, - overlap_shared_expert: bool = False, - fix_router: bool = False, - capacity_factor: Optional[float] = None, -) -> Callable: - """Build the EP forward of one ``DeepseekV32MoE`` block. - - Expected module interface: ``gate`` returning ``(logits, weights, - indices)``, batched ``experts`` and ``shared_experts``. - - Args: - module: DeepSeek-V3.2 MoE block. - mesh: Unused; part of the local-compute factory signature. - tp_mesh: Unused. - cp_mesh: Unused. - ep_mesh: Expert mesh whose ``ep`` axis owns the routed experts. - use_grouped_gemm: Run local experts through the grouped-GEMM path. - Required when ``experts`` is the ``GroupedExperts`` replacement, - whose weights use the transposed grouped-GEMM layout. - overlap_shared_expert: Evaluate ``shared_experts`` while the dispatch - exchange is in flight. The shared branch reads only - ``hidden_states``, so the result is unchanged. - fix_router: Benchmark-only balanced routing. Loss, gradient norm and - expert-load statistics are meaningless in that mode. - capacity_factor: Per-expert slot bound of the overlapped dispatch path; - ``None`` keeps dropless routing. - - Returns: - ``compute_fn(module, hidden_states)`` with the block forward signature. - """ - del mesh, tp_mesh, cp_mesh - - def combine( - module: Any, - hidden_states: torch.Tensor, - routed: torch.Tensor, - overlapped: Optional[torch.Tensor] = None, - ) -> torch.Tensor: - """Add the shared-experts branch to the routed output.""" - shared = module.shared_experts(hidden_states) if overlapped is None else overlapped - return routed + shared - - def overlap_shared(module: Any, hidden_states: torch.Tensor) -> torch.Tensor: - """Run the shared-experts branch behind the dispatch exchange.""" - return module.shared_experts(hidden_states) - - return build_ep_compute( - module, - ep_mesh, - router_fn="topk_router_module", - fix_router=fix_router, - archetype_key="deepseek_v32_topk_router_shared", - expected_attrs=["gate", "experts", "shared_experts"], - combine=combine, - use_grouped_gemm=use_grouped_gemm, - capacity_factor=capacity_factor, - overlap_fn=overlap_shared if overlap_shared_expert else None, - ) - - -__all__ = ["deepseek_v32_ep_compute_fn"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py b/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py index 6b846c615d..8628d6ef4a 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py +++ b/hyper_parallel/models/deepseek_v32/adapter/policies/sharding.py @@ -18,20 +18,13 @@ def build_parameter_sharding_rules() -> list[tuple[list[str], Any]]: - """Return DSA and MLA tensor-parallel naming-rule overrides. - - The latent projections (``q_a_proj``/``kv_a_proj_with_mqa``, or their - fused ``linear_qkv`` form after the DSA replacement) feed every attention - head, so each TP rank keeps them whole; the head-major up-projections are - column-parallel. The indexer scores all of its heads on every TP rank so - each rank selects the same top-k tokens. - """ + """Return DSA and MLA tensor-parallel naming-rule overrides.""" from hyper_parallel.distributed.tensor_parallel.param_role import ( # pylint: disable=C0415 ParamRole, ) return [ - (["q_a_proj", "kv_a_proj_with_mqa", "linear_qkv"], ParamRole.REPLICATED), + (["linear_qkv"], ParamRole.REPLICATED), (["q_b_proj", "kv_b_proj"], ParamRole.COLWISE), ( [ diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index 13d03b04cd..a7a8a67454 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -39,21 +39,11 @@ def _load_context_parallel(): return context_parallel -def _load_expert_parallel(): - """Return the DeepSeek-V3.2 EP compute factory provider lazily.""" - from hyper_parallel.models.deepseek_v32.adapter.distributed import ( # pylint: disable=C0415 - expert_parallel, - ) - - return expert_parallel - - DEEPSEEK_V32_ADAPTER_SPEC = ModelAdapterSpec( architecture="DeepseekV32ForCausalLM", model_type="deepseek_v32", replacements=_load_replacements, context_parallel=_load_context_parallel, - expert_parallel=_load_expert_parallel, sharding_rules=build_parameter_sharding_rules, ) register_model_adapter(DEEPSEEK_V32_ADAPTER_SPEC) diff --git a/tests/common/dsa_reference_kernels.py b/tests/common/dsa_reference_kernels.py index 53d779cc30..d42cbc6c4c 100644 --- a/tests/common/dsa_reference_kernels.py +++ b/tests/common/dsa_reference_kernels.py @@ -272,9 +272,15 @@ def _restore_modules( previous_packages: dict[str, dict], stubs: dict[str, types.ModuleType], ) -> None: - """Evict modules bound to the stand-ins and restore the previous import state.""" + """Return the stand-in namespaces to their state before the context. + + Every refreshed module and lazy package first imported inside the context + is evicted, together with any other module that captured a stand-in, so a + lazily cached package symbol cannot keep a stand-in alive after exit. + """ for name, module in list(sys.modules.items()): - if name not in previous_modules and (name in _DSA_MODULES or _binds_stub(module, stubs)): + if name not in previous_modules and ( + _is_refreshed(name) or name in _LAZY_PACKAGES or _binds_stub(module, stubs)): del sys.modules[name] parent, _, child = name.rpartition(".") if getattr(sys.modules.get(parent), child, None) is module: @@ -295,14 +301,13 @@ def _restore_modules( def reference_dsa_kernels() -> Iterator[None]: """Run the DSA replacement and its CP wrapper on CPU reference kernels. - The NPU-dependent modules are imported afresh against stand-in - ``torch_npu``, custom-operator and ``cann_ops_transformer`` modules, so a - stand-in left behind by another test cannot leak into them. The CANN - wrappers import their operators when called, so the stand-ins stay in - ``sys.modules`` until the context exits; their module specs keep + Cached NPU-dependent modules are dropped on entry, so they import afresh + against stand-in ``torch_npu``, custom-operator and ``cann_ops_transformer`` + modules when the test first reaches them, in the same order as a real run. + The CANN wrappers import their operators when called, so the stand-ins stay + in ``sys.modules`` until the context exits; their module specs keep dependency probes such as ``importlib.util.find_spec`` working meanwhile. - On exit every module that captured a stand-in is evicted and the previous - modules and lazily cached package symbols are restored. + On exit the stand-in namespaces are restored to their state before entry. """ previous_modules = dict(sys.modules) previous_packages = { @@ -312,8 +317,6 @@ def reference_dsa_kernels() -> Iterator[None]: _forget_cached_dsa_modules(previous_packages) sys.modules.update(stubs) try: - for module_name in _DSA_MODULES: - __import__(module_name) yield finally: for name in _STUB_MODULES: diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index 7bb3b6dc88..c22fedd80f 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -12,18 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ -"""CPU/Gloo DeepSeek-V3.2 TP/SP/CP/EP parity against a single-process reference. +"""CPU/Gloo DeepSeek-V3.2 TP/CP/EP/FSDP parity against a single-process reference. Each case builds one small DeepSeek-V3.2 with fixed weights, converts a copy through the Trainer chain (recipe ``plan_overrides`` -> module replacement -> -``ShardingPlanner`` -> ``apply_sharding_plan``) and runs one forward/backward -on the same tokens. The DSA cases run the NPU sparse-attention replacement on -the CPU reference kernels of ``tests.common.dsa_reference_kernels``. - -FSDP is NPU/GPU-only, so the gradient reductions it owns are emulated: the -dense DP+CP domain averages, and only parameters whose final value needs no -TP-replicate reduction are compared (TP-sharded weights under sequence -parallelism and EP-sharded experts when no other rank feeds them tokens). +``ShardingPlanner`` -> ``apply_sharding_plan`` -> FSDP2) and runs one +forward/backward on the same tokens. DSA runs the NPU sparse-attention +replacement on the CPU reference kernels of ``tests.common.dsa_reference_kernels``; +the NPU-only RMSNorm and grouped-expert kernels stay native. + +FSDP2 owns the Trainer's gradient reduction (SUM over the DP x CP domain and +over TP replicas, scaled by 1 / (dp * cp * (1 if loss_parallel else tp))), so +the raw loss is backpropagated and every gradient must equal the +single-process gradient. """ # Distributed worker: torch and hyper_parallel imports are required here. # pylint: disable=forbidden-backend-import @@ -33,6 +34,7 @@ import tempfile from pathlib import Path from typing import Any +from unittest.mock import patch import torch import torch.distributed as dist @@ -45,6 +47,9 @@ _ADAPTER = "hyper_parallel.models.deepseek_v32.adapter" _SEQ_LEN = 16 _BATCH = 2 +# Packed documents over the flattened [batch, sequence] stream; two of them +# straddle the CP2 split of their row (positions 8 and 24). +_PACKED_BOUNDARIES = (0, 5, 16, 19, 27, 32) class _GlooAllGather(torch.autograd.Function): @@ -98,39 +103,32 @@ def _reference_model() -> DeepseekV32ForCausalLM: return model -def _plan_overrides(dsa: bool) -> list: - """Return the recipe parallel entries; NPU-only norm and expert kernels stay native.""" - entries = [] - if dsa: - entries.append({ +def _plan_overrides() -> list: + """Return the recipe's DSA, CP and EP entries; NPU-only norm and expert kernels stay native.""" + return [ + { "match": "*.self_attn", - "replace": { - "kind": "module", - "implementation": { - "_target_": f"{_ADAPTER}.conversion.module_replacement.replace_deepseek_v32_dsa_attention", - }, - }, - }) - entries.append({ + "replace": {"kind": "module", "implementation": { + "_target_": f"{_ADAPTER}.conversion.module_replacement.replace_deepseek_v32_dsa_attention", + }}, + }, + { "match": "*.self_attn.forward", "when": "cp", - "replace": { - "kind": "method", - "implementation": { - "_target_": f"{_ADAPTER}.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper", - }, - }, - }) - entries.append({ - "match": "model.layers.[1-9].mlp.forward", "when": "ep", - "replace": { - "kind": "method", - "implementation": {"_target_": f"{_ADAPTER}.distributed.expert_parallel.deepseek_v32_ep_compute_fn"}, + "replace": {"kind": "method", "implementation": { + "_target_": f"{_ADAPTER}.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper", + }}, }, - }) - return entries + { + "match": "model.layers.[1-9].mlp.forward", "when": "ep", + "replace": {"kind": "method", "implementation": { + "_target_": "hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn", + "overlap_shared_expert": True, + }}, + }, + ] -def _parse_trainer_config(tp, cp, ep, sequence_parallel, loss_parallel, dsa): +def _parse_trainer_config(tp, cp, ep, loss_parallel): """Resolve a minimal Trainer YAML so plan_overrides follow the recipe path.""" from hyper_parallel.trainer.config.parser import parse_training_args # pylint: disable=import-outside-toplevel @@ -139,9 +137,12 @@ def _parse_trainer_config(tp, cp, ep, sequence_parallel, loss_parallel, dsa): "optimizer": {"_target_": "hyper_parallel.components.optim.AdamW", "adamw_config": {"lr": 1.0e-4}}, "training": {"backend": "gloo", "global_batch_size": 1, "micro_batch_size": 1}, "accelerator": {"tp_size": tp, "cp_size": cp, "ep_size": ep, "pp_size": 1, - "sequence_parallel": sequence_parallel, "loss_parallel": loss_parallel}, - "fsdp_config": {"dp_shard_size": 1, "edp_shard_size": 1}, - "plan_overrides": _plan_overrides(dsa), + "sequence_parallel": False, "loss_parallel": loss_parallel}, + "fsdp_config": { + "dp_shard_size": 1, "edp_shard_size": 1, + "mix_precision": {"param_dtype": "float32", "reduce_dtype": "float32"}, + }, + "plan_overrides": _plan_overrides(), } with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "recipe.yaml" @@ -149,12 +150,13 @@ def _parse_trainer_config(tp, cp, ep, sequence_parallel, loss_parallel, dsa): return parse_training_args([str(path)]) -def _build_parallel_model(reference, config, dsa): - """Run replacement, planning and sharding on a copy of the reference weights.""" +def _build_parallel_model(reference, config): + """Run replacement, planning, sharding and FSDP2 on a copy of the reference weights.""" # pylint: disable=import-outside-toplevel from hyper_parallel.components.checkpoint.weight_conversion import get_model_conversion_mapping from hyper_parallel.distributed.apply import apply_sharding_plan from hyper_parallel.models._transformers.model_builder import ( + _apply_fsdp2_with_external, _maybe_apply_module_replacements, instantiate_infrastructure, ) @@ -168,18 +170,18 @@ def _build_parallel_model(reference, config, dsa): model, _ = _maybe_apply_module_replacements( model, None, setup, None, False, get_model_conversion_mapping(model) ) - if dsa: - for replaced, source in zip(model.model.layers, reference.model.layers): - with torch.no_grad(): - replaced.self_attn.linear_qkv.weight.copy_(torch.cat([ - source.self_attn.q_a_proj.weight, source.self_attn.kv_a_proj_with_mqa.weight, - ])) - planner, _ = instantiate_infrastructure(distributed_setup=setup, device=torch.device("cpu")) + for replaced, source in zip(model.model.layers, reference.model.layers): + with torch.no_grad(): + replaced.self_attn.linear_qkv.weight.copy_(torch.cat([ + source.self_attn.q_a_proj.weight, source.self_attn.kv_a_proj_with_mqa.weight, + ])) + planner, fsdp_manager = instantiate_infrastructure(distributed_setup=setup, device=torch.device("cpu")) plan = planner.plan( model, mesh.device_mesh, tp_size=mesh.tp_size, cp_size=mesh.cp_size, ep_size=mesh.ep_size, - sequence_parallel=mesh.sequence_parallel, loss_parallel=mesh.loss_parallel, + sequence_parallel=False, loss_parallel=mesh.loss_parallel, ) model, source_shard_info = apply_sharding_plan(model, plan, mesh) + model = _apply_fsdp2_with_external(model, fsdp_manager, source_shard_info, None) return model, mesh, source_shard_info or {} @@ -192,48 +194,50 @@ def _reference_gradient(reference, name): return named[name].grad -def _compared_gradients(model, reference, mesh, source_shard_info, *, check_experts): - """Yield (name, local gradient, expected local gradient) for locally exact parameters. - - TP-replicated weights are compared only without TP, where the emulated - DP+CP average is their complete reduction. - """ +def _compared_gradients(model, reference, source_shard_info): + """Yield (name, local gradient, expected local gradient) for every parameter with a gradient.""" from hyper_parallel import distribute_tensor # pylint: disable=import-outside-toplevel - dense_group = mesh.dp_cp_mesh.get_group() if mesh.dp_cp_mesh is not None and mesh.dp_cp_mesh.size() > 1 else None for name, parameter in model.named_parameters(): - if parameter.grad is None: + expected = _reference_gradient(reference, name) + assert (parameter.grad is None) == (expected is None), f"{name}: gradient presence differs" + if expected is None: continue + grad = parameter.grad + grad = grad.to_local() if hasattr(grad, "to_local") else grad placements, source_mesh = source_shard_info.get(name, ((), None)) - sharded = any(not placement.is_replicate() for placement in placements) - is_expert = source_mesh is not None and "ep" in (source_mesh.mesh_dim_names or ()) - if (not sharded and mesh.tp_size > 1) or (is_expert and not check_experts): - continue - grad = parameter.grad.clone() - if not is_expert and dense_group is not None: - dist.all_reduce(grad, op=dist.ReduceOp.AVG, group=dense_group) - expected = _reference_gradient(reference, name) - if sharded: + if any(not placement.is_replicate() for placement in placements): expected = distribute_tensor(expected, source_mesh, placements, src_data_rank=None).to_local() yield name, grad, expected -def _run_case(*, tp=1, cp=1, ep=1, sequence_parallel=False, loss_parallel=False, dsa=False, - check_gradients=True, check_experts=True): +def _block_diagonal_mask(boundaries): + """Return the causal per-document mask of packed boundaries over [batch, sequence].""" + mask = torch.zeros(_BATCH, 1, _SEQ_LEN, _SEQ_LEN, dtype=torch.bool) + for start, end in zip(boundaries[:-1], boundaries[1:]): + row, first = divmod(start, _SEQ_LEN) + last = end - row * _SEQ_LEN + mask[row, 0, first:last, first:last] = torch.ones(last - first, last - first, dtype=torch.bool).tril() + return mask + + +def _run_case(*, tp=1, cp=1, ep=1, loss_parallel=False, packed=False): """Compare one parallel topology against the single-process model.""" # pylint: disable=import-outside-toplevel dist.init_process_group("gloo") original_all_gather = dist_nn.all_gather dist_nn.all_gather = lambda tensor, group=dist.group.WORLD: _GlooAllGather.apply(group, tensor) - kernels = reference_dsa_kernels() if dsa else contextlib.nullcontext() try: - with kernels: + # FSDP2 resolves its device from the mesh; the Gloo mesh lives on CPU. + with reference_dsa_kernels(), patch( + "hyper_parallel.core.fully_shard.api._get_device_from_mesh", return_value=torch.device("cpu")): from hyper_parallel.core.tensor_parallel import loss_parallel as loss_parallel_context from hyper_parallel.models._transformers.loss_parallel import causal_lm_loss_parallel + from hyper_parallel.models.deepseek_v32.adapter.data.runtime import DeepseekV32PackedSequence reference = _reference_model() - config = _parse_trainer_config(tp, cp, ep, sequence_parallel, loss_parallel, dsa) - model, mesh, source_shard_info = _build_parallel_model(reference, config, dsa) + config = _parse_trainer_config(tp, cp, ep, loss_parallel) + model, mesh, source_shard_info = _build_parallel_model(reference, config) if loss_parallel: model.loss_function = causal_lm_loss_parallel @@ -241,12 +245,17 @@ def _run_case(*, tp=1, cp=1, ep=1, sequence_parallel=False, loss_parallel=False, tokens = torch.randint(1, 128, (_BATCH, _SEQ_LEN + 1)) inputs, labels = tokens[:, :-1].contiguous(), tokens[:, 1:].contiguous() positions = torch.arange(_SEQ_LEN).unsqueeze(0).expand(_BATCH, -1) + reference_mask = {"attention_mask": _block_diagonal_mask(_PACKED_BOUNDARIES)} if packed else {} expected = reference(input_ids=inputs, labels=labels, shift_labels=labels, - position_ids=positions, use_cache=False) + position_ids=positions, use_cache=False, **reference_mask) expected.loss.backward() local = slice(mesh.cp_rank * _SEQ_LEN // cp, (mesh.cp_rank + 1) * _SEQ_LEN // cp) - extra = {} if dsa else {"attention_mask": torch.ones(1, 1, _SEQ_LEN, _SEQ_LEN, dtype=torch.bool).tril()} + boundaries = {} + if packed: + boundaries = DeepseekV32PackedSequence().build_runtime_inputs( + batch={"cu_seq_lens": torch.tensor(_PACKED_BOUNDARIES, dtype=torch.int32)}, context=None, + ) forward_context = ( loss_parallel_context(mesh=mesh.device_mesh["tp"]) if loss_parallel else contextlib.nullcontext() ) @@ -254,42 +263,39 @@ def _run_case(*, tp=1, cp=1, ep=1, sequence_parallel=False, loss_parallel=False, output = model( input_ids=inputs[:, local].contiguous(), labels=labels[:, local].contiguous(), shift_labels=labels[:, local].contiguous(), position_ids=positions[:, local], - use_cache=False, **extra, + use_cache=False, **boundaries, ) - # Trainer loss rule: equal token counts cancel the DP*CP factor; SP divides by TP. - (output.loss / (tp if sequence_parallel else 1)).backward() + output.loss.backward() loss = output.loss.detach().reshape(()).clone() if cp > 1: dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=mesh.device_mesh["cp"].get_group()) torch.testing.assert_close(loss, expected.loss.detach(), rtol=1e-5, atol=1e-6) - if check_gradients: - compared = 0 - for name, grad, reference_grad in _compared_gradients( - model, reference, mesh, source_shard_info, check_experts=check_experts): - torch.testing.assert_close(grad, reference_grad, rtol=1e-4, atol=1e-6, msg=name) - compared += 1 - assert compared, "no parallel gradient was compared" + compared = 0 + for name, grad, reference_grad in _compared_gradients(model, reference, source_shard_info): + torch.testing.assert_close(grad, reference_grad, rtol=1e-4, atol=1e-6, msg=name) + compared += 1 + assert compared, "no parallel gradient was compared" finally: dist_nn.all_gather = original_all_gather dist.destroy_process_group() -def test_tp2_sp_ep2_transformers_attention(): - """TP2 + sequence parallel + EP2 on the Transformers attention and experts.""" - _run_case(tp=2, ep=2, sequence_parallel=True) +def test_cp2_dsa(): + """CP2 through the DSA all-gather wrapper.""" + _run_case(cp=2) -def test_cp2_dsa(): - """CP2 through the DSA all-gather wrapper; every gradient is compared.""" - _run_case(cp=2, dsa=True) +def test_cp2_dsa_packed(): + """CP2 with packed documents straddling the CP split, boundaries from the runtime adapter.""" + _run_case(cp=2, packed=True) def test_tp2_ep2_dsa_loss_parallel(): - """TP2 + loss parallel + EP2 on the DSA replacement (forward parity).""" - _run_case(tp=2, ep=2, loss_parallel=True, dsa=True, check_gradients=False) + """TP2 + loss parallel + EP2 at cp_size=1, so the plain DSA forward runs.""" + _run_case(tp=2, ep=2, loss_parallel=True) def test_tp2_cp2_ep4_dsa(): - """TP2 x CP2 with EP4 over the DSA replacement on four ranks (forward parity).""" - _run_case(tp=2, cp=2, ep=4, dsa=True, check_gradients=False) + """TP2 x CP2 with EP4 over the DSA replacement on four ranks.""" + _run_case(tp=2, cp=2, ep=4) diff --git a/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py index 115a317d86..daffca3b4a 100644 --- a/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py @@ -28,8 +28,8 @@ @pytest.mark.parametrize( ("case_name", "num_proc"), [ - ("test_tp2_sp_ep2_transformers_attention", 2), ("test_cp2_dsa", 2), + ("test_cp2_dsa_packed", 2), ("test_tp2_ep2_dsa_loss_parallel", 2), ("test_tp2_cp2_ep4_dsa", 4), ], @@ -39,8 +39,9 @@ def test_deepseek_v32_parallel_parity_gloo(case_name: str, num_proc: int) -> None: """ Feature: DeepSeek-V3.2 parallel integration. - Description: Run TP/SP/loss-parallel, DSA CP and EP topologies on CPU ranks through the Trainer chain. - Expectation: The loss and every locally exact gradient match the single-process model. + Description: Run DSA under CP (with packed documents), TP + loss parallel, TP x CP and EP on CPU ranks + through the Trainer chain including FSDP2. + Expectation: The loss and every gradient match the single-process model. """ # CPU workers need no accelerator backend, including torch's entry-point loading. with patch.dict("os.environ", {"TORCH_DEVICE_BACKEND_AUTOLOAD": "0"}): diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py index 4525477282..47b883d6a1 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py @@ -79,36 +79,17 @@ class TestDeepseekV32TensorParallelRoles(unittest.TestCase): @staticmethod def _attention_placements(model): """Plan TP2 and return the TP placement of every layer-0 attention parameter.""" - plan = ShardingPlanner().plan(model, FakeDeviceMesh((2,), ("tp",)), tp_size=2, sequence_parallel=True) + plan = ShardingPlanner().plan(model, FakeDeviceMesh((2,), ("tp",)), tp_size=2) spec = plan.modules["model.layers.0.self_attn"] return {name: placement[TP] for name, placement in spec.params.items()} - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_reference_attention_roles_cover_mla_and_indexer(self): - """Feature: DeepSeek-V3.2 TP roles on the Transformers attention. - - Description: Plan TP2 for a dense-only model without any replacement. - Expectation: Latent and indexer projections replicate and head projections shard. - """ - with torch.device("meta"): - model = DeepseekV32ForCausalLM(_tiny_config(num_hidden_layers=2, first_k_dense_replace=2)) - placements = self._attention_placements(model) - expected = { - "q_a_proj.weight": Replicate(), "kv_a_proj_with_mqa.weight": Replicate(), - "q_b_proj.weight": Shard(0), "kv_b_proj.weight": Shard(0), "o_proj.weight": Shard(1), - "indexer.wq_b.weight": Replicate(), "indexer.wk.weight": Replicate(), - "indexer.weights_proj.weight": Replicate(), - } - self.assertEqual(placements, expected) - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", card_mark="allcards", essential_mark="essential") def test_dsa_replacement_keeps_fused_latent_projection_replicated(self): """Feature: DeepSeek-V3.2 TP roles on the DSA replacement. Description: Plan TP2 after fusing q_a_proj and kv_a_proj_with_mqa into linear_qkv. - Expectation: linear_qkv replicates while head-major projections shard. + Expectation: linear_qkv and the indexer projections replicate while head-major projections shard. """ with reference_dsa_kernels(): with torch.device("meta"): @@ -122,6 +103,8 @@ def test_dsa_replacement_keeps_fused_latent_projection_replicated(self): self.assertEqual(placements["q_b_proj.weight"], Shard(0)) self.assertEqual(placements["kv_b_proj.weight"], Shard(0)) self.assertEqual(placements["o_proj.weight"], Shard(1)) + for name in ("indexer.wq_b.weight", "indexer.wk.weight", "indexer.weights_proj.weight"): + self.assertEqual(placements[name], Replicate(), name) self.assertNotIn("q_a_proj.weight", placements) @@ -198,7 +181,7 @@ def test_sparse_and_dense_selection_match_transformers(self): def test_packed_documents_match_block_diagonal_attention(self): """Feature: DSA packed-document boundaries. - Description: Pass global cu_seq_lens through the runtime adapter for documents crossing rows. + Description: Pass global cu_seq_lens through the runtime adapter for two rows of packed documents. Expectation: DSA equals Transformers attention under the matching block-diagonal mask. """ boundaries = torch.tensor([0, 5, 12, 15, 24], dtype=torch.int32) @@ -218,22 +201,6 @@ def test_packed_documents_match_block_diagonal_attention(self): hidden, rope, positions = _attention_inputs(model) self._assert_matches_reference(attention, dsa, hidden, rope, positions, mask, **runtime) - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_indexer_loss_rejects_tensor_parallelism(self): - """Feature: DSA indexer KL loss ownership. - - Description: Request the trainable-indexer loss with and without TP. - Expectation: TP raises before construction; TP1 builds the replacement. - """ - with reference_dsa_kernels(): - attention = DeepseekV32ForCausalLM(_tiny_config()).model.layers[0].self_attn - attention.config.dsa_loss_coeff = 0.01 - with self.assertRaisesRegex(ValueError, "tp_size=1"): - replace_deepseek_v32_dsa_attention(module=attention, module_fqn="layer", context={"tp": True}) - replacement = replace_deepseek_v32_dsa_attention(module=attention, module_fqn="layer", context={}) - self.assertEqual(replacement.dsa_loss_coeff, 0.01) - if __name__ == "__main__": unittest.main() From b32679d1e924809627a9f3aad73e136a351cd0dc Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 02:50:33 -0600 Subject: [PATCH 08/20] chore(deepseek_v32): trim process remarks from recipe and import comments 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. --- hyper_parallel/components/modules/dsa_attention.py | 5 ++--- .../models/deepseek_v32/recipes/train.yaml | 12 ++++++------ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/hyper_parallel/components/modules/dsa_attention.py b/hyper_parallel/components/modules/dsa_attention.py index e6f0568264..daf3d9836a 100644 --- a/hyper_parallel/components/modules/dsa_attention.py +++ b/hyper_parallel/components/modules/dsa_attention.py @@ -30,9 +30,8 @@ from hyper_parallel.models.replacement import module_replacement from hyper_parallel.components.functional import aux_loss_auto_scale from hyper_parallel.components.functional import apply_rotary_pos_emb, apply_rotary_pos_emb_interleave -# Exports that share their submodule's name come from the submodule: once that -# submodule is imported elsewhere first (the DeepSeek-V3.2 CP wrapper does), the -# package attribute of that name is the module object, not the function. +# Exports named like their submodule come from the submodule: once that submodule +# is imported, the package attribute of that name is the module, not the function. from hyper_parallel.components.functional.aggregate_hidden import aggregate_hidden from hyper_parallel.components.functional.dsa_indexer import dsa_indexer from hyper_parallel.components.functional.dsa_kl_loss import dsa_kl_loss diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index b71692d1e3..ac2f6f0306 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -1,19 +1,19 @@ -# DeepSeek-V3.2 完整训练配方(唯一对外交付的 DeepSeek-V3.2 recipe)。 +# DeepSeek-V3.2 训练配方。 # # 主线拓扑:64 节点 / 512 卡 Ascend NPU(hccl backend)。 # dense 区域:tp 1 × cp 1 × dp 512,FSDP 在 512 卡上切分; # 专家区域:ep 64 × edp 8(edp = dp*cp*tp/ep)。每个 EP rank 持有 256/64 = 4 个专家, # edp 内按 edp_shard 4 × 副本 2 做 HSDP,每卡每个 MoE 层恰好 1 个专家。 -# 显存估算(未在本配方上实测,按需在目标集群确认):FP32 参数 + FP32 梯度 +# 显存估算:FP32 参数 + FP32 梯度 # + AdamW 两个 FP32 动量 ≈ 16 B/param。58 个 MoE 层 × 每卡 1 个专家 ≈ 2.55B 参数 # (≈ 41 GB);dense 部分约 18B 参数切到 512 卡上约 35M(≈ 0.6 GB);激活另计。 # -# 其它并行维度都通过 CLI dotted override 打开,无需维护第二份配置: +# 其它并行维度用命令行覆盖打开: # TP/loss parallel:--accelerator.tp_size=2 --accelerator.loss_parallel=true # --fsdp_config.dp_shard_size=256(dp 随 TP 减半);DSA 暂不支持 # sequence parallel。 # MoE 层在 TP 下走 TP-extend-EP(专家只按 ep 切),因此 tp_size>1 时 ep_size -# 必须 >1;fused gate_up 专家不能直接做 TP 切分(planner 会给出明确报错)。 +# 必须 >1;fused gate_up 专家不能直接做 TP 切分。 # CP:--accelerator.cp_size=2,下方 `when: cp` 的 DSA CP wrapper 自动生效; # EP:--accelerator.ep_size 与 --fsdp_config.edp_shard_size 一起调整。 # 修改拓扑时保持 world_size = tp*cp*dp、dp*cp 可被 dp_shard_size 整除、 @@ -21,8 +21,8 @@ # 256/ep_size 可被 edp_shard_size 整除(否则 FSDP 按第 0 维切专家时会补齐空数据), # 且 global_batch_size 可被 micro_batch_size*dp 整除。 # -# 默认加载公开 Hugging Face 资源(模型、tokenizer、dataset)。默认数据是 wikitext-2 -# 的逐行文本,每行一个样本,只用于跑通流程。本地或离线资源用命令行覆盖,例如: +# 默认加载公开 Hugging Face 资源(模型、tokenizer、dataset),默认数据为 wikitext-2, +# 每行一个样本。本地或离线资源用命令行覆盖,例如: # scripts/train_lm.py \ # --model.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 \ # --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 From 69bb3d74c8367bc857fb2a2e3d6120e60e2a1ede Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 04:35:29 -0600 Subject: [PATCH 09/20] feat(dsa): Hadamard indexer rotation and KL teacher over tensor-parallel 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. --- .../components/modules/dsa_attention.py | 70 ++++++++++++++++++- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/hyper_parallel/components/modules/dsa_attention.py b/hyper_parallel/components/modules/dsa_attention.py index daf3d9836a..a06b32c905 100644 --- a/hyper_parallel/components/modules/dsa_attention.py +++ b/hyper_parallel/components/modules/dsa_attention.py @@ -17,6 +17,7 @@ from __future__ import annotations from collections.abc import Mapping, Sequence +from functools import lru_cache from typing import Any # This package provides PyTorch-specific high-performance modules. @@ -97,6 +98,7 @@ def _deepseek_v32_dense_attention( key, value = projected_kv.split((module.qk_nope_head_dim, module.v_head_dim), dim=-1) key_rope = key_rope.expand(-1, -1, module.num_heads, -1) need_stats = bool(module.training and not module.freeze_dsa and module.dsa_loss_coeff) + module.last_indexer_loss = None output, maximum, total = _dense_flash_attention( module, torch.cat((query, query_rope), dim=-1), torch.cat((key, key_rope), dim=-1), value, sequence_lengths, need_stats=need_stats, @@ -115,13 +117,20 @@ def _deepseek_v32_dense_attention( indexer_stats = dsa_dense_indexer_lse( index_query, index_key, weights, query_lengths=query_lengths, key_lengths=key_lengths, ) + teacher = (query, key, query_rope, key_rope) + group = module._kl_head_group() # pylint: disable=protected-access + if group is not None: + teacher = tuple(_gather_heads(tensor.detach(), 2, group) for tensor in teacher) + maximum, total = (_gather_heads(tensor.detach(), 0, group) for tensor in (maximum, total)) + query, key, query_rope, key_rope = teacher loss = dsa_dense_indexer_kl_loss( index_query, index_key, weights, query.flatten(0, 1), key.flatten(0, 1), maximum, total, indexer_stats, scale=module.scaling, query_rope=query_rope.flatten(0, 1), key_rope=key_rope.flatten(0, 1), query_lengths=query_lengths, key_lengths=key_lengths, loss_coefficient=module.dsa_loss_coeff, ) - output = aux_loss_auto_scale(output, loss) + module.last_indexer_loss = loss.detach() + output = aux_loss_auto_scale(output, loss / module.kl_loss_tp_replicas) return output @@ -195,6 +204,31 @@ def _apply_index_rope( return torch.cat((query_rot, query_pass), dim=-1), torch.cat((key_rot, key_pass), dim=-1) +@lru_cache(maxsize=8) +def _hadamard_matrix(size: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + """Return the Sylvester-ordered ``size`` x ``size`` Hadamard matrix.""" + matrix = torch.ones(1, 1, dtype=torch.float32) + while matrix.shape[0] < size: + matrix = torch.cat((torch.cat((matrix, matrix), dim=1), torch.cat((matrix, -matrix), dim=1)), dim=0) + return matrix.to(dtype=dtype, device=device) + + +def _rotate_activation(states: torch.Tensor) -> torch.Tensor: + """Apply the orthonormal Hadamard rotation over the last dimension.""" + size = states.shape[-1] + if size & (size - 1): + raise ValueError(f"Hadamard rotation requires a power-of-two width, got {size}") + matrix = _hadamard_matrix(size, states.dtype, states.device) + return F.linear(states, matrix) * size**-0.5 # pylint: disable=not-callable + + +def _gather_heads(tensor: torch.Tensor, dim: int, group: Any) -> torch.Tensor: + """Concatenate tensor-parallel head shards along ``dim`` in rank order.""" + shards = [torch.empty_like(tensor) for _ in range(torch.distributed.get_world_size(group))] + torch.distributed.all_gather(shards, tensor.contiguous(), group=group) + return torch.cat(shards, dim=dim) + + def _absorb_query_projection( query: torch.Tensor, key_up_weight: torch.Tensor, @@ -304,6 +338,12 @@ def _initialize_options(self, module: nn.Module) -> None: self.dsa_dense_warm_up = bool( getattr(module, "dsa_dense_warm_up", getattr(config, "dsa_dense_warm_up", False)) ) + self.index_rotate_activation = bool(getattr(config, "index_rotate_activation", False)) + # Group of the tensor-parallel attention-head shards, set by the model builder, + # and the TP ranks whose identical KL gradients the Trainer sums. + self.kl_head_group = None + self.kl_loss_tp_replicas = 1 + self.last_indexer_loss = None if getattr(module, "param_sink_number", 0) > 0: raise ValueError("DeepseekV32DSAAttention does not support the parameter-sink path") if getattr(module, "use_mome", False): @@ -509,8 +549,22 @@ def _project_index_states( index_head_dim=self.index_head_dim, interleaved=self.index_rotary_interleaved, ) + if self.index_rotate_activation: + index_query, index_key = _rotate_activation(index_query), _rotate_activation(index_key) return index_query, index_key, merge_weight + def _kl_head_group(self) -> Any: + """Return the group holding the other heads of the KL teacher when TP shards them.""" + full_heads = getattr(self, "_hp_full_head_counts", {}).get("num_heads") + if full_heads is None or full_heads == self.num_heads: + return None + if self.kl_head_group is None: + raise RuntimeError( + "Tensor parallelism shards the attention heads; the DSA indexer loss " + "needs kl_head_group set to the tensor-parallel group" + ) + return self.kl_head_group + def _apply_auxiliary_loss( self, attn_output: torch.Tensor, @@ -521,20 +575,30 @@ def _apply_auxiliary_loss( actual_q_len: torch.Tensor, actual_kv_len: torch.Tensor, ) -> torch.Tensor: - """Attach the DSA KL auxiliary loss when training enables it.""" + """Attach the DSA KL auxiliary loss when training enables it. + + The teacher sums the attention distribution over all heads, so heads + sharded by tensor parallelism are gathered first. + """ if not (self.training and not self.freeze_dsa and self.dsa_loss_coeff): + self.last_indexer_loss = None return attn_output query_tnd, key_tnd, q_rot_tnd, k_rot_tnd = ( tensor.reshape(-1, tensor.shape[2], tensor.shape[3]) for tensor in attention_states ) + group = self._kl_head_group() + if group is not None: + query_tnd, q_rot_tnd = (_gather_heads(tensor.detach(), 1, group) for tensor in (query_tnd, q_rot_tnd)) + softmax_stats = tuple(_gather_heads(tensor.detach(), -1, group) for tensor in softmax_stats) aux_loss = dsa_kl_loss( *index_states, query_tnd, key_tnd, topk_indices, *softmax_stats, q_rot_tnd, k_rot_tnd, actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff, backend="cann", ) - return aux_loss_auto_scale(attn_output, aux_loss) + self.last_indexer_loss = aux_loss.detach() + return aux_loss_auto_scale(attn_output, aux_loss / self.kl_loss_tp_replicas) def _prepare_attention_states(self, hidden_states, position_embeddings): """Project attention states and apply their rotary embeddings.""" From 6a1efbc3a383841cf3de8fff5080399adb4ed91c Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 04:35:43 -0600 Subject: [PATCH 10/20] feat(deepseek_v32): train MTP, sequence balance loss and expert bias 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. --- .../deepseek_v32/cropped_deepseek_v32.py | 16 +- .../deepseek_v32/train_single_card.yaml | 12 +- .../distributed/expert_parallel/recipes.py | 7 +- .../adapter/conversion/checkpoint_mapping.py | 79 ++++ .../deepseek_v32/adapter/materialization.py | 46 ++ .../deepseek_v32/adapter/registration.py | 40 +- .../deepseek_v32/modeling_deepseek_v32.py | 443 ++++++++++++++++++ .../models/deepseek_v32/recipes/train.yaml | 44 +- .../_test_deepseek_v32_parallel.py | 82 +++- .../test_deepseek_v32_adapter_contracts.py | 7 +- .../test_deepseek_v32_training_model.py | 259 ++++++++++ 11 files changed, 995 insertions(+), 40 deletions(-) create mode 100644 hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py create mode 100644 hyper_parallel/models/deepseek_v32/adapter/materialization.py create mode 100644 hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py create mode 100644 tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py diff --git a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py index 9f6828b685..89349ad230 100644 --- a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py +++ b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py @@ -20,7 +20,7 @@ from transformers import AutoConfig, PretrainedConfig, PreTrainedModel -from hyper_parallel.models import HyperAutoModelForCausalLM +from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import build_model # ``DeepseekV32Config.__post_init__`` derives these per-layer lists from the # layer count and ``first_k_dense_replace``. Copying the released 61-entry @@ -35,6 +35,7 @@ def build_cropped_deepseek_v32_config( num_hidden_layers: int, first_k_dense_replace: int, n_routed_experts: int, + num_nextn_predict_layers: int = 0, local_files_only: bool = True, ) -> PretrainedConfig: """Return the released DeepSeek-V3.2 configuration cropped in depth and experts. @@ -52,6 +53,7 @@ def build_cropped_deepseek_v32_config( routing scores each of ``n_group`` groups by its top-2 experts and keeps ``topk_group`` groups, so every group needs two experts and the kept groups must hold ``num_experts_per_tok`` experts. + num_nextn_predict_layers: MTP depth; 0 disables MTP. local_files_only: Disable implicit Hub downloads when true. Returns: @@ -88,6 +90,7 @@ def build_cropped_deepseek_v32_config( num_hidden_layers=num_hidden_layers, first_k_dense_replace=first_k_dense_replace, n_routed_experts=n_routed_experts, + num_nextn_predict_layers=num_nextn_predict_layers, use_cache=False, ) return type(released).from_dict(values) @@ -99,6 +102,7 @@ def build_cropped_deepseek_v32( num_hidden_layers: int = 2, first_k_dense_replace: int = 1, n_routed_experts: int = 16, + num_nextn_predict_layers: int = 0, local_files_only: bool = True, **build_kwargs: Any, ) -> PreTrainedModel: @@ -113,10 +117,11 @@ def build_cropped_deepseek_v32( num_hidden_layers: Decoder layers retained in the cropped model. first_k_dense_replace: Leading dense-MLP layers. n_routed_experts: Routed experts per MoE layer. + num_nextn_predict_layers: MTP depth; 0 disables MTP. local_files_only: Disable implicit Hub downloads when true. - **build_kwargs: ``HyperAutoModelForCausalLM.from_config`` options, both - those set in YAML (``torch_dtype``, ``attn_implementation``, - ``validate_placement``) and those the Trainer injects + **build_kwargs: Model build options, both those set in YAML + (``torch_dtype``, ``attn_implementation``, ``validate_placement``, + training objectives) and those the Trainer injects (``distributed_setup``, ``activation_checkpoint``, ...). Returns: @@ -127,6 +132,7 @@ def build_cropped_deepseek_v32( num_hidden_layers=num_hidden_layers, first_k_dense_replace=first_k_dense_replace, n_routed_experts=n_routed_experts, + num_nextn_predict_layers=num_nextn_predict_layers, local_files_only=local_files_only, ) - return HyperAutoModelForCausalLM.from_config(config, **build_kwargs) + return build_model(config=config, **build_kwargs) diff --git a/examples/training_demo/deepseek_v32/train_single_card.yaml b/examples/training_demo/deepseek_v32/train_single_card.yaml index 10bba7cb83..66694c13f1 100644 --- a/examples/training_demo/deepseek_v32/train_single_card.yaml +++ b/examples/training_demo/deepseek_v32/train_single_card.yaml @@ -18,11 +18,19 @@ model: num_hidden_layers: 2 first_k_dense_replace: 1 n_routed_experts: 16 + # MTP 层(DSA + 16 专家 MoE + 融合投影)再加约 1B 参数,单卡显存放不下,这里关闭。 + num_nextn_predict_layers: 0 local_files_only: true torch_dtype: bfloat16 # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 attn_implementation: sdpa validate_placement: false + # 训练目标与完整配方相同:序列级负载均衡 loss、专家 bias 更新、indexer KL loss。 + moe_aux_loss_coeff: 1.0e-4 + moe_router_enable_expert_bias: true + moe_router_bias_update_rate: 1.0e-3 + dsa_loss_coeff: 1.0 + index_rotate_activation: true model_init_dtype: float32 @@ -152,8 +160,8 @@ lr_scheduler: lr_decay_style: cosine lr_config: lr: 1.0e-5 - lr_warmup_steps: 1 - min_lr: 0.0 + lr_warmup_steps: 0 + min_lr: 1.0e-7 checkpoint: save_ckpt: false diff --git a/hyper_parallel/distributed/expert_parallel/recipes.py b/hyper_parallel/distributed/expert_parallel/recipes.py index 58fb7f6089..72d593e89b 100644 --- a/hyper_parallel/distributed/expert_parallel/recipes.py +++ b/hyper_parallel/distributed/expert_parallel/recipes.py @@ -343,6 +343,7 @@ def deepseekv3_ep_compute_fn( overlap_shared_expert: bool = False, fix_router: bool = False, capacity_factor: Optional[float] = None, + router_fn: str = "deepseekv3", ) -> Callable: """Archetype ``deepseekv3_sigmoid_group_shared``: sigmoid group-limited routing (with e_score_correction_bias / routed_scaling_factor, already @@ -370,6 +371,10 @@ def deepseekv3_ep_compute_fn( happened to route. Loss / grad_norm / expert-load metrics are meaningless in that mode and it must not be used to report an efficiency number — see ``routing.make_balanced_router``. Correctness runs keep it off. + + ``router_fn="topk_router_module"`` takes the expert indices and gate values + returned by ``module.gate`` instead of recomputing them from its logits, so + a training router can attach auxiliary losses to the gate values. """ del mesh, tp_mesh, cp_mesh @@ -390,7 +395,7 @@ def overlap_shared(module: Any, hidden_states: torch.Tensor) -> torch.Tensor: return build_ep_compute( module, ep_mesh, - router_fn="deepseekv3", + router_fn=router_fn, fix_router=fix_router, archetype_key="deepseekv3_sigmoid_group_shared", expected_attrs=["gate", "experts", "shared_experts"], diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py new file mode 100644 index 0000000000..337d86ad73 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py @@ -0,0 +1,79 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Checkpoint key mapping for the DeepSeek-V3.2 training model.""" + +from __future__ import annotations + +from typing import Any + + +def build_training_checkpoint_mapping(mtp_first_layer: int, mtp_depth: int) -> list[Any]: + """Return the Transformers DeepSeek-V3.2 mapping plus the MTP layer renames. + + The released checkpoint stores MTP depth ``d`` as layer ``mtp_first_layer + d``: + the fusion norms and projection, the shared-head norm and an ordinary decoder + layer. Its embedding and head copies stay unmapped because the training model + shares the trunk's. + + Args: + mtp_first_layer: Checkpoint layer index of the first MTP depth. + mtp_depth: Number of MTP depths; 0 adds no renames. + + Returns: + Weight renames followed by the expert merge operations. + """ + try: + # Family registration stays importable without Transformers installed. + # pylint: disable=import-outside-toplevel + from transformers.conversion_mapping import get_checkpoint_conversion_mapping + from transformers.core_model_loading import WeightRenaming + except ImportError: + return [] + + mapping = [] + for depth in range(mtp_depth): + source = rf"^model\.layers\.{mtp_first_layer + depth}\." + target = f"mtp.layers.{depth}." + mapping.extend([ + WeightRenaming(source + r"(enorm|hnorm|eh_proj)\.", target + r"\1."), + WeightRenaming(source + r"shared_head\.norm\.", target + "post_norm."), + WeightRenaming(source + r"(self_attn|mlp|input_layernorm|post_attention_layernorm)\.", + target + r"mtp_block.\1."), + ]) + mapping.extend(get_checkpoint_conversion_mapping("deepseek_v32") or []) + return mapping + + +def register_training_checkpoint_mapping(class_name: str, mtp_first_layer: int, mtp_depth: int) -> None: + """Register the training model's mapping; its nested trunk then adds none. + + Args: + class_name: Training model class name, which takes lookup priority. + mtp_first_layer: Checkpoint layer index of the first MTP depth. + mtp_depth: Number of MTP depths. + """ + from transformers.conversion_mapping import ( # pylint: disable=import-outside-toplevel + register_checkpoint_conversion_mapping, + ) + + register_checkpoint_conversion_mapping( + class_name, build_training_checkpoint_mapping(mtp_first_layer, mtp_depth), overwrite=True, + ) + # The root mapping already covers the nested trunk; a second, scoped copy + # would merge its experts twice. + register_checkpoint_conversion_mapping("DeepseekV32Model", [], overwrite=True) + + +__all__ = ["build_training_checkpoint_mapping", "register_training_checkpoint_mapping"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/materialization.py b/hyper_parallel/models/deepseek_v32/adapter/materialization.py new file mode 100644 index 0000000000..b26ddd58ba --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/materialization.py @@ -0,0 +1,46 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Rebuild DeepSeek-V3.2 rotary buffers after empty materialization.""" + +import torch # pylint: disable=forbidden-backend-import +from torch import nn # pylint: disable=forbidden-backend-import + +from hyper_parallel.models.materialization import register_rebuildable_buffer + + +def register_rotary_materialization(model: nn.Module) -> None: + """Keep CPU copies of the YaRN frequencies, which checkpoints do not store. + + A model built on the meta device and materialized with ``to_empty`` would + otherwise keep uninitialized ``inv_freq`` and ``original_inv_freq``. + + Args: + model: Constructed DeepSeek-V3.2 model, before sharding. + """ + # pylint: disable=import-outside-toplevel + from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32RotaryEmbedding + + for module in model.modules(): + if not isinstance(module, DeepseekV32RotaryEmbedding): + continue + with torch.device("cpu"): + reference = DeepseekV32RotaryEmbedding(module.config) + for name, value in reference.named_buffers(recurse=False): + register_rebuildable_buffer( + module, name, value=value.to(dtype=getattr(module, name).dtype), persistent=False, + ) + + +__all__ = ["register_rotary_materialization"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index a7a8a67454..a1bb6e5059 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -12,13 +12,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ -"""Architecture and lazy provider registration for DeepSeek-V3.2.""" +"""Architecture and lazy provider registration for DeepSeek-V3.2. -from hyper_parallel.models.adapter_spec import ModelAdapterSpec +``DeepseekV32ForCausalLM`` checkpoints build +:class:`~hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.DeepseekV32TrainingForCausalLM` +unless a recipe forces the Transformers class. +""" + +from typing import Any + +from hyper_parallel.models.adapter_spec import ModelAdapterSpec, RecomputePolicy +from hyper_parallel.models.deepseek_v32.adapter.materialization import register_rotary_materialization from hyper_parallel.models.deepseek_v32.adapter.policies.sharding import ( build_parameter_sharding_rules, ) -from hyper_parallel.models.registry import register_model_adapter +from hyper_parallel.models.registry import register_custom_model, register_model_adapter def _load_replacements(): @@ -39,11 +47,37 @@ def _load_context_parallel(): return context_parallel +def build_recompute_policy() -> RecomputePolicy: + """Expose trunk decoder layers and MTP depths as recompute regions.""" + return RecomputePolicy(region_patterns=("model.layers.*", "mtp.layers.*")) + + +def get_fsdp_wrap_modules(model: Any) -> tuple[str, ...]: + """Make each MTP depth its own FSDP unit.""" + mtp = getattr(model, "mtp", None) + return () if mtp is None else tuple(f"mtp.layers.{name}" for name, _ in mtp.layers.named_children()) + + +def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: + """Keep decoder discovery out of the MTP branch, which declares its own units.""" + return () if getattr(model, "mtp", None) is None else ("mtp",) + + +register_custom_model( + "DeepseekV32ForCausalLM", + "hyper_parallel.models.deepseek_v32.modeling_deepseek_v32", + "DeepseekV32TrainingForCausalLM", +) + DEEPSEEK_V32_ADAPTER_SPEC = ModelAdapterSpec( architecture="DeepseekV32ForCausalLM", model_type="deepseek_v32", replacements=_load_replacements, + materialization=register_rotary_materialization, context_parallel=_load_context_parallel, sharding_rules=build_parameter_sharding_rules, + fsdp_wrap_modules=get_fsdp_wrap_modules, + fsdp_excluded_subtrees=get_fsdp_excluded_subtrees, + recompute=build_recompute_policy, ) register_model_adapter(DEEPSEEK_V32_ADAPTER_SPEC) diff --git a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py new file mode 100644 index 0000000000..88a09f6225 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py @@ -0,0 +1,443 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 training model. + +``DeepseekV32ForCausalLM`` in Transformers implements inference. The training +model keeps its modules and checkpoint names and adds the DeepSeek-V3 training +objectives with Megatron-Core definitions: + +* every MoE router adds the sequence-wise balance loss and counts routed tokens + for the loss-free expert-bias update; +* multi-token prediction (MTP) runs the extra decoder depth that the released + checkpoint stores after the last trunk layer. +""" + +from __future__ import annotations + +import copy +from dataclasses import dataclass +from functools import partial +from typing import Any, Optional + +import torch # pylint: disable=forbidden-backend-import +import torch.distributed as dist # pylint: disable=forbidden-backend-import +from torch import nn # pylint: disable=forbidden-backend-import +from torch.nn import functional as F # pylint: disable=forbidden-backend-import +from transformers.masking_utils import create_causal_mask +from transformers.modeling_outputs import MoeCausalLMOutputWithPast +from transformers.models.deepseek_v32.modeling_deepseek_v32 import ( + DeepseekV32DecoderLayer, + DeepseekV32ForCausalLM, + DeepseekV32MoE, + DeepseekV32RMSNorm, + DeepseekV32TopkRouter, +) + +from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale +from hyper_parallel.components.modules.mtp import MTPLayer, build_mtp +from hyper_parallel.core.activation_memory.recompute_state import is_recomputing +from hyper_parallel.core.utils.communication import differentiable_all_reduce, gather_counts_via_all_gather +from hyper_parallel.data.constants import IGNORE_INDEX +from hyper_parallel.models.deepseek_v32.adapter.conversion.checkpoint_mapping import ( + register_training_checkpoint_mapping, +) + +__all__ = [ + "DeepseekV32Router", + "DeepseekV32TrainingForCausalLM", + "DeepseekV32TrainingOutput", + "bind_parallel_groups", + "build_model", +] + + +class DeepseekV32Router(DeepseekV32TopkRouter): + """Top-k router with the sequence-wise balance loss and expert-load counts. + + Expert selection and gate values match ``DeepseekV32TopkRouter``. In + training, the balance loss is attached to the returned gate values and the + tokens routed to each expert are counted. The Trainer's MoE monitor sums the + counts over data-parallel ranks after each optimizer step and calls + :meth:`update_expert_bias`. + + Args: + config: DeepSeek-V3.2 configuration. + aux_loss_coeff: Weight of the sequence-wise balance loss; 0 disables it. + enable_expert_bias: Whether ``e_score_correction_bias`` follows the routed load. + expert_bias_update_rate: Bias step per optimizer step. + """ + + def __init__(self, config: Any, *, aux_loss_coeff: float = 0.0, enable_expert_bias: bool = False, + expert_bias_update_rate: float = 1e-3) -> None: + """Create the router state; the caller transfers the source weights.""" + super().__init__(config) + if aux_loss_coeff < 0 or expert_bias_update_rate < 0: + raise ValueError("aux_loss_coeff and expert_bias_update_rate must be nonnegative") + self.aux_loss_coeff = float(aux_loss_coeff) + self.enable_expert_bias = bool(enable_expert_bias) + self.expert_bias_update_rate = float(expert_bias_update_rate) + # Context-parallel group over which one sequence is split; bound by build_model. + self.sequence_partition_group = None + # TP ranks that compute this same loss and whose gradients the Trainer sums. + self.aux_loss_tp_replicas = 1 + self.last_aux_loss: Optional[torch.Tensor] = None + self._token_counts: Optional[torch.Tensor] = None + + @classmethod + def from_router(cls, router: DeepseekV32TopkRouter, config: Any, **options: Any) -> "DeepseekV32Router": + """Wrap an existing router, sharing its weight and bias tensors.""" + trained = cls(config, **options) + trained.weight = router.weight + trained.e_score_correction_bias = router.e_score_correction_bias + return trained + + def _select_experts(self, scores: torch.Tensor) -> torch.Tensor: + """Return the biased, group-limited top-k expert indices.""" + scores_for_choice = scores + self.e_score_correction_bias + group_scores = ( + scores_for_choice.view(-1, self.num_group, self.num_experts // self.num_group) + .topk(2, dim=-1)[0] + .sum(dim=-1) + ) + group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] + group_mask = torch.zeros_like(group_scores).scatter_(1, group_idx, 1) + score_mask = ( + group_mask.unsqueeze(-1) + .expand(-1, self.num_group, self.num_experts // self.num_group) + .reshape(-1, self.num_experts) + ) + scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) + return torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1] + + def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return router logits, gate values and expert indices for ``[B, S, H]`` tokens.""" + batch_size = hidden_states.shape[0] if hidden_states.ndim == 3 else 1 + hidden_states = hidden_states.view(-1, self.hidden_dim) + router_logits = F.linear( # pylint: disable=not-callable + hidden_states.type(torch.float32), self.weight.type(torch.float32)) + scores = router_logits.sigmoid() + topk_indices = self._select_experts(scores) + topk_weights = scores.gather(1, topk_indices) + if self.norm_topk_prob: + topk_weights = topk_weights / (topk_weights.sum(dim=-1, keepdim=True) + 1e-20) + topk_weights = topk_weights * self.routed_scaling_factor + if self.training: + if self.aux_loss_coeff: + topk_weights = self._attach_balance_loss(topk_weights, scores, topk_indices, batch_size) + if self.enable_expert_bias and not is_recomputing(): + counts = self.tokens_per_expert + counts.scatter_add_(0, topk_indices.reshape(-1), + torch.ones_like(topk_indices.reshape(-1), dtype=counts.dtype)) + return router_logits, topk_weights, topk_indices + + def _attach_balance_loss(self, weights: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor, + batch_size: int) -> torch.Tensor: + """Attach ``coeff * mean_b sum_i f_i P_i`` over each sample of the micro-batch. + + ``f_i`` is the fraction of the sample's routed slots on expert ``i`` + times the expert count, from the selection actually used (biased and + group-limited). ``P_i`` is the sample mean of the scores normalized over + all experts, without the bias. A context-parallel split sums both + statistics over the full sequence. + """ + num_tokens = scores.shape[0] + sequence_length = num_tokens // batch_size + probabilities = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) + probability_sum = probabilities.view(batch_size, sequence_length, -1).sum(dim=1) + routed = torch.zeros_like(scores).scatter_(1, indices, 1.0) + counts = routed.view(batch_size, sequence_length, -1).sum(dim=1) + group = self.sequence_partition_group + if group is not None: + dist.all_reduce(counts, group=group) + probability_sum = differentiable_all_reduce(probability_sum, "sum", group) + sequence_length *= dist.get_world_size(group) + load = counts / (sequence_length * self.top_k / self.num_experts) + loss = (load * (probability_sum / sequence_length)).sum(dim=-1).mean() + self.last_aux_loss = loss.detach() + return aux_loss_auto_scale(weights, loss * (self.aux_loss_coeff / self.aux_loss_tp_replicas)) + + @property + def tokens_per_expert(self) -> torch.Tensor: + """Expert loads routed since the last bias update.""" + counts = self._token_counts + if counts is None or counts.device != self.e_score_correction_bias.device: + counts = torch.zeros(self.num_experts, dtype=torch.int64, device=self.e_score_correction_bias.device) + self._token_counts = counts + return counts + + @torch.no_grad() + def update_expert_bias(self, lr: float, num_recomputations: int = 1) -> None: + """Move each bias by ``lr`` toward the mean load and reset the counts. + + Recomputed forwards are not counted, so ``num_recomputations`` is unused. + """ + del num_recomputations + counts = self.tokens_per_expert + offset = (counts.sum() - counts * self.num_experts).sign().to(self.e_score_correction_bias.dtype) + self.e_score_correction_bias.add_(offset, alpha=lr) + counts.zero_() + + +@dataclass +class DeepseekV32TrainingOutput(MoeCausalLMOutputWithPast): + """Causal-LM output with log-only training metrics read by the Trainer.""" + + extra_metrics: Optional[dict[str, torch.Tensor]] = None + + +def _mtp_layer_config(config: Any, layer_idx: int) -> Any: + """Return a configuration whose per-layer lists also describe ``layer_idx``.""" + layer_config = copy.copy(config) + for name in ("mlp_layer_types", "layer_types"): + values = getattr(config, name, None) + if isinstance(values, (list, tuple)) and len(values) <= layer_idx: + setattr(layer_config, name, [*values, *([values[-1]] * (layer_idx + 1 - len(values)))]) + return layer_config + + +class DeepseekV32TrainingForCausalLM(DeepseekV32ForCausalLM): + """DeepSeek-V3.2 causal LM with MoE balancing, MTP and DSA indexer training. + + Args: + config: DeepSeek-V3.2 configuration. ``num_nextn_predict_layers`` sets + the MTP depth; 0 disables MTP. + mtp_loss_scaling_factor: Weight of the MTP loss, divided by the depth. + mtp_checkpoint_first_layer: Checkpoint layer index of the first MTP + depth. Defaults to ``num_hidden_layers``; set it to the source + checkpoint's trunk depth when loading a truncated trunk. + moe_aux_loss_coeff: Weight of the sequence-wise balance loss. + moe_router_enable_expert_bias: Whether routers update their load bias. + moe_router_bias_update_rate: Load-bias step per optimizer step. + dsa_loss_coeff: Weight of the DSA indexer KL loss; 0 keeps the indexer fixed. + index_rotate_activation: Apply the Hadamard rotation to indexer queries + and keys before scoring. + dsa_dense_warm_up: Train the indexer against dense attention. + """ + + _no_split_modules = ["DeepseekV32DecoderLayer", "MTPLayer"] + # MTP embedding and head are copies of the trunk's; the trunk weights are used. + _keys_to_ignore_on_load_unexpected = [ + r"model\.layers\.\d+\.embed_tokens\.weight", + r"model\.layers\.\d+\.shared_head\.head\.weight", + ] + + def __init__(self, config: Any, *, mtp_loss_scaling_factor: float = 0.3, + mtp_checkpoint_first_layer: Optional[int] = None, moe_aux_loss_coeff: float = 0.0, + moe_router_enable_expert_bias: bool = False, moe_router_bias_update_rate: float = 1e-3, + dsa_loss_coeff: float = 0.0, index_rotate_activation: bool = False, + dsa_dense_warm_up: bool = False) -> None: + """Build the trunk, the MTP depths and the training routers.""" + # The DSA replacement reads its options from the configuration. + config.dsa_loss_coeff = float(dsa_loss_coeff) + config.index_rotate_activation = bool(index_rotate_activation) + config.dsa_dense_warm_up = bool(dsa_dense_warm_up) + super().__init__(config) + if mtp_loss_scaling_factor < 0: + raise ValueError("mtp_loss_scaling_factor must be nonnegative") + self.mtp_loss_scaling_factor = float(mtp_loss_scaling_factor) + first_layer = config.num_hidden_layers + self.mtp = build_mtp(getattr(config, "num_nextn_predict_layers", 0) or None, + layer_factory=lambda depth: MTPLayer( + config.hidden_size, + DeepseekV32DecoderLayer(_mtp_layer_config(config, first_layer + depth), + first_layer + depth), + norm_factory=partial(DeepseekV32RMSNorm, eps=config.rms_norm_eps), + )) + self.mtp_checkpoint_first_layer = (first_layer if mtp_checkpoint_first_layer is None + else int(mtp_checkpoint_first_layer)) + router_options = { + "aux_loss_coeff": moe_aux_loss_coeff, + "enable_expert_bias": moe_router_enable_expert_bias, + "expert_bias_update_rate": moe_router_bias_update_rate, + } + for module in list(self.modules()): + if isinstance(module, DeepseekV32MoE): + module.gate = DeepseekV32Router.from_router(module.gate, config, **router_options) + # Context-parallel group of the trunk sequence; bound by build_model. + self.sequence_group = None + self._pre_norm_capture: Optional[tuple[nn.Module, Any]] = None + self._pre_norm_hidden: Optional[torch.Tensor] = None + self._capturing_pre_norm = False + register_training_checkpoint_mapping(type(self).__name__, self.mtp_checkpoint_first_layer, + 0 if self.mtp is None else len(self.mtp.layers)) + self.post_init() + + @classmethod + def from_config(cls, config: Any, **kwargs: Any) -> "DeepseekV32TrainingForCausalLM": + """Construct from a configuration through the shared custom-model builder.""" + return cls._from_config(config, **kwargs) + + def _capture_pre_norm_hidden(self) -> None: + """Keep the next trunk output entering the final norm, which MTP consumes.""" + self._pre_norm_hidden = None + self._capturing_pre_norm = True + norm = self.model.norm + if self._pre_norm_capture is not None and self._pre_norm_capture[0] is norm: + return + if self._pre_norm_capture is not None: + self._pre_norm_capture[1].remove() + + def keep_input(_module: nn.Module, args: tuple[Any, ...]) -> None: + """Store the final norm's input for the MTP depths during a capture.""" + if self._capturing_pre_norm: + self._pre_norm_hidden = args[0] + self._capturing_pre_norm = False + + self._pre_norm_capture = (norm, norm.register_forward_pre_hook(keep_input)) + + def _shift_left(self, tokens: torch.Tensor, pad_value: int) -> torch.Tensor: + """Shift ``[B, S]`` rows one position left; only the sequence tail is padded. + + Under context parallelism each rank holds a contiguous slice, so the new + last column comes from the first column of the next rank. + """ + group = self.sequence_group + if group is None: + return F.pad(tokens[:, 1:], (0, 1), value=pad_value) + rank, size = dist.get_rank(group), dist.get_world_size(group) + first = gather_counts_via_all_gather(tokens[:, 0].contiguous(), group, size) + tail = first[rank + 1] if rank + 1 < size else torch.full_like(first[0], pad_value) + return torch.cat((tokens[:, 1:], tail.unsqueeze(1)), dim=1) + + def _sequence_mean(self, loss_sum: torch.Tensor, count: torch.Tensor) -> torch.Tensor: + """Average a token loss sum over the full sequence across context-parallel ranks.""" + group = self.sequence_group + if group is None: + return loss_sum / count.clamp_min(1) + global_count = count.clone() + dist.all_reduce(global_count, group=group) + return differentiable_all_reduce(loss_sum, "sum", group) / global_count.clamp_min(1) + + def _mtp_loss(self, hidden: torch.Tensor, input_ids: torch.Tensor, targets: torch.Tensor, + attention_mask: Any, position_ids: torch.Tensor, kwargs: dict[str, Any], + ) -> tuple[torch.Tensor, list[torch.Tensor]]: + """Return the weighted MTP loss and each depth's unweighted loss. + + Depth ``k`` fuses the previous depth's state at position ``i`` with the + embedding of token ``i + k`` and predicts token ``i + k + 1``. Inputs and + targets keep the trunk length; the positions shifted past the end use + token 0 and are excluded from the loss. + """ + position_embeddings = self.model.rotary_emb(hidden, position_ids=position_ids) + total = torch.zeros((), device=hidden.device, dtype=torch.float32) + depth_losses = [] + for layer in self.mtp.layers: + input_ids = self._shift_left(input_ids, 0) + targets = self._shift_left(targets, IGNORE_INDEX) + hidden = layer(hidden, self.model.embed_tokens(input_ids), attention_mask=attention_mask, + position_ids=position_ids, position_embeddings=position_embeddings, **kwargs) + loss_sum = self.loss_function(logits=self.lm_head(hidden), labels=None, vocab_size=self.config.vocab_size, + num_items_in_batch=1, ignore_index=IGNORE_INDEX, shift_labels=targets) + depth_loss = self._sequence_mean(loss_sum, targets.ne(IGNORE_INDEX).sum()) + depth_losses.append(depth_loss.detach()) + total = total + depth_loss + return total * (self.mtp_loss_scaling_factor / len(self.mtp.layers)), depth_losses + + def _training_metrics(self) -> dict[str, torch.Tensor]: + """Return the trunk's mean DSA indexer loss when the indexer is trained.""" + losses = [loss for layer in self.model.layers + if (loss := getattr(layer.self_attn, "last_indexer_loss", None)) is not None] + return {"dsa_indexer_loss": torch.stack(losses).mean()} if losses else {} + + def forward(self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, past_key_values: Any = None, + inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, logits_to_keep: int | torch.Tensor = 0, + **kwargs: Any) -> MoeCausalLMOutputWithPast: + """Return the LM loss, plus the weighted MTP loss under ``foundation_loss/mtp``. + + Without labels, or outside training, this is the Transformers forward. + """ + if labels is None or not self.training: + return super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, + past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, + use_cache=use_cache, logits_to_keep=logits_to_keep, **kwargs) + if self.mtp is not None: + if input_ids is None: + raise ValueError("DeepSeek-V3.2 MTP training requires input_ids") + self._capture_pre_norm_hidden() + outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, + inputs_embeds=inputs_embeds, use_cache=False, **kwargs) + logits = self.lm_head(outputs.last_hidden_state) + loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) + metrics = self._training_metrics() + if self.mtp is not None: + hidden, self._pre_norm_hidden = self._pre_norm_hidden, None + targets = kwargs.get("shift_labels") + if targets is None: + targets = self._shift_left(labels, IGNORE_INDEX) + if position_ids is None: + position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0) + mask = create_causal_mask(config=self.config, inputs_embeds=hidden, attention_mask=attention_mask, + past_key_values=None, position_ids=position_ids, + allow_is_causal_skip=False) + mtp_loss, depth_losses = self._mtp_loss(hidden, input_ids, targets, mask, position_ids, + {k: v for k, v in kwargs.items() if k != "shift_labels"}) + # A context-parallel slice may hold no trunk target; its LM mean is then undefined. + loss = torch.where(targets.ne(IGNORE_INDEX).any(), loss, torch.zeros_like(loss)) + loss = {"foundation_loss": loss, "foundation_loss/mtp": mtp_loss} + metrics.update({f"mtp_{depth}_loss": value for depth, value in enumerate(depth_losses, start=1)}) + return DeepseekV32TrainingOutput(loss=loss, logits=logits, router_logits=None, + extra_metrics=metrics or None) + + +def bind_parallel_groups(model: nn.Module, mesh: Any) -> None: + """Bind the process groups the training objectives reduce over. + + Under loss parallelism the Trainer sums replicated gradients over TP ranks, + while each TP rank computes the full balance and indexer losses; those + losses are therefore divided by the TP size. + + Args: + model: Constructed and parallelized DeepSeek-V3.2 training model. + mesh: Trainer ``MeshContext``; ``None`` leaves single-process groups. + """ + if mesh is None: + return + cp_group = mesh.cp_mesh.get_group() if mesh.cp_size > 1 else None + tp_group = mesh.device_mesh["tp"].get_group() if mesh.tp_size > 1 else None + tp_replicas = mesh.tp_size if mesh.loss_parallel else 1 + for module in model.modules(): + if isinstance(module, DeepseekV32TrainingForCausalLM): + module.sequence_group = cp_group + elif isinstance(module, DeepseekV32Router): + module.sequence_partition_group = cp_group + module.aux_loss_tp_replicas = tp_replicas + elif hasattr(module, "kl_head_group"): + module.kl_head_group = tp_group + module.kl_loss_tp_replicas = tp_replicas + + +def build_model(**options: Any) -> nn.Module: + """Build the DeepSeek-V3.2 training model and bind its parallel groups. + + Args: + **options: ``pretrained_model_name_or_path`` loads a checkpoint; otherwise + ``config`` builds from a configuration. The remaining options go to + ``HyperAutoModelForCausalLM`` and, for the training options of + :class:`DeepseekV32TrainingForCausalLM`, to the model constructor. + + Returns: + The constructed and parallelized model. + """ + from hyper_parallel.models import HyperAutoModelForCausalLM # pylint: disable=C0415 + + pretrained = options.pop("pretrained_model_name_or_path", None) + if pretrained is not None: + model = HyperAutoModelForCausalLM.from_pretrained(pretrained, **options) + else: + model = HyperAutoModelForCausalLM.from_config(options.pop("config"), **options) + bind_parallel_groups(model, getattr(options.get("distributed_setup"), "mesh_context", None)) + return model diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index ac2f6f0306..6e47904fd4 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -5,8 +5,8 @@ # 专家区域:ep 64 × edp 8(edp = dp*cp*tp/ep)。每个 EP rank 持有 256/64 = 4 个专家, # edp 内按 edp_shard 4 × 副本 2 做 HSDP,每卡每个 MoE 层恰好 1 个专家。 # 显存估算:FP32 参数 + FP32 梯度 -# + AdamW 两个 FP32 动量 ≈ 16 B/param。58 个 MoE 层 × 每卡 1 个专家 ≈ 2.55B 参数 -# (≈ 41 GB);dense 部分约 18B 参数切到 512 卡上约 35M(≈ 0.6 GB);激活另计。 +# + AdamW 两个 FP32 动量 ≈ 16 B/param。主干 58 个 MoE 层加 MTP 层,每卡每层 1 个专家 +# ≈ 2.6B 参数(≈ 42 GB);dense 部分约 18B 参数切到 512 卡上约 35M(≈ 0.6 GB);激活另计。 # # 其它并行维度用命令行覆盖打开: # TP/loss parallel:--accelerator.tp_size=2 --accelerator.loss_parallel=true @@ -31,12 +31,21 @@ # examples/training_demo/deepseek_v32/train_single_card.yaml。 model: - _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained + # 训练模型:在 Transformers 的 DeepSeek-V3.2 上加 MTP、MoE 负载均衡和 DSA indexer 训练,并绑定并行通信组。 + _target_: hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.build_model pretrained_model_name_or_path: deepseek-ai/DeepSeek-V3.2 torch_dtype: bfloat16 # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 attn_implementation: sdpa - force_hf: true + # MTP 深度取 config 的 num_nextn_predict_layers(1);MTP loss 按 0.3 / 深度加权。 + mtp_loss_scaling_factor: 0.3 + # 序列级负载均衡 loss 与无辅助损失的专家 bias 更新(每个优化步按负载 ±1e-3)。 + moe_aux_loss_coeff: 1.0e-4 + moe_router_enable_expert_bias: true + moe_router_bias_update_rate: 1.0e-3 + # 稀疏阶段的 indexer KL loss;indexer q/k 在打分前做 Hadamard 旋转。 + dsa_loss_coeff: 1.0 + index_rotate_activation: true model_init_dtype: float32 @@ -76,10 +85,17 @@ fsdp_config: comm_fusion: false plan_overrides: + # MTP 融合投影([embedding; hidden] -> hidden)在 TP 下保持完整副本。 + - match: mtp.layers.*.eh_proj + params: + weight: {tp: replicate} - match: - "*.input_layernorm" - "*.post_attention_layernorm" - model.norm + - "mtp.layers.*.enorm" + - "mtp.layers.*.hnorm" + - "mtp.layers.*.post_norm" replace: kind: module implementation: @@ -111,8 +127,9 @@ plan_overrides: _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper # null follows dsa_dense_warm_up; true/false forces one path for the full run. dense_warmup: null - # EP:DeepSeek-V3.2 的 router 与 DeepSeek-V3 相同,直接用框架内置的 V3 EP 工厂。 - # 只匹配 MoE 层:first_k_dense_replace=3,层 0-2 为稠密 MLP,层 3-60 为 MoE; + # EP:DeepSeek-V3.2 的 router 与 DeepSeek-V3 相同,用框架内置的 V3 EP 工厂; + # router_fn 取训练 router 返回的专家与门控值,负载均衡 loss 挂在门控值上。 + # 只匹配 MoE 层:first_k_dense_replace=3,层 0-2 为稠密 MLP,层 3-60 与 MTP 层为 MoE; # fnmatch 不支持数值区间,因此分两条 glob 覆盖 3-9 与 10-99。 # 裁剪模型改变稠密层数时需要同步调整这两条 glob。 - match: "model.layers.[3-9].mlp.forward" @@ -121,6 +138,7 @@ plan_overrides: kind: method implementation: _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + router_fn: topk_router_module use_grouped_gemm: true overlap_shared_expert: true - match: "model.layers.[1-9][0-9].mlp.forward" @@ -129,6 +147,16 @@ plan_overrides: kind: method implementation: _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + router_fn: topk_router_module + use_grouped_gemm: true + overlap_shared_expert: true + - match: "mtp.layers.*.mtp_block.mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + router_fn: topk_router_module use_grouped_gemm: true overlap_shared_expert: true @@ -206,8 +234,8 @@ lr_scheduler: lr_decay_style: cosine lr_config: lr: 1.0e-5 - lr_warmup_steps: 1 - min_lr: 0.0 + lr_warmup_steps: 0 + min_lr: 1.0e-7 checkpoint: save_ckpt: false diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index c22fedd80f..b30511966c 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -14,8 +14,9 @@ # ============================================================================ """CPU/Gloo DeepSeek-V3.2 TP/CP/EP/FSDP parity against a single-process reference. -Each case builds one small DeepSeek-V3.2 with fixed weights, converts a copy -through the Trainer chain (recipe ``plan_overrides`` -> module replacement -> +Each case builds one small DeepSeek-V3.2 training model with fixed weights, +one MTP depth and the sequence-wise balance loss, converts a copy through the +Trainer chain (recipe ``plan_overrides`` -> module replacement -> ``ShardingPlanner`` -> ``apply_sharding_plan`` -> FSDP2) and runs one forward/backward on the same tokens. DSA runs the NPU sparse-attention replacement on the CPU reference kernels of ``tests.common.dsa_reference_kernels``; @@ -23,8 +24,9 @@ FSDP2 owns the Trainer's gradient reduction (SUM over the DP x CP domain and over TP replicas, scaled by 1 / (dp * cp * (1 if loss_parallel else tp))), so -the raw loss is backpropagated and every gradient must equal the -single-process gradient. +the raw losses are backpropagated and every gradient must equal the +single-process gradient. Expert loads summed over the DP x CP domain must equal +the single-process loads. """ # Distributed worker: torch and hyper_parallel imports are required here. # pylint: disable=forbidden-backend-import @@ -40,7 +42,7 @@ import torch.distributed as dist import torch.distributed.nn.functional as dist_nn import yaml -from transformers import DeepseekV32Config, DeepseekV32ForCausalLM +from transformers import DeepseekV32Config from tests.common.dsa_reference_kernels import reference_dsa_kernels @@ -78,7 +80,7 @@ def backward(ctx: Any, *grads: torch.Tensor) -> tuple: # pylint: disable=argume def _config() -> DeepseekV32Config: - """Return one dense layer followed by two MoE layers.""" + """Return one dense layer followed by two MoE layers and one MoE MTP depth.""" config = DeepseekV32Config.from_dict({ "vocab_size": 128, "hidden_size": 64, "intermediate_size": 96, "moe_intermediate_size": 32, "num_hidden_layers": 3, "first_k_dense_replace": 1, "num_attention_heads": 4, @@ -87,15 +89,22 @@ def _config() -> DeepseekV32Config: "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 6, "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, "attn_implementation": "sdpa", + "num_nextn_predict_layers": 1, }) config.architectures = ["DeepseekV32ForCausalLM"] return config -def _reference_model() -> DeepseekV32ForCausalLM: - """Build the unsharded model with nonzero expert-selection biases.""" +def _reference_model(): + """Build the unsharded training model with nonzero expert-selection biases.""" + from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=import-outside-toplevel + DeepseekV32TrainingForCausalLM, + ) + torch.manual_seed(7) - model = DeepseekV32ForCausalLM(_config()).float().train() + model = DeepseekV32TrainingForCausalLM( + _config(), moe_aux_loss_coeff=0.1, moe_router_enable_expert_bias=True, + ).float().train() with torch.no_grad(): for name, buffer in model.named_buffers(): if name.endswith("e_score_correction_bias"): @@ -104,8 +113,9 @@ def _reference_model() -> DeepseekV32ForCausalLM: def _plan_overrides() -> list: - """Return the recipe's DSA, CP and EP entries; NPU-only norm and expert kernels stay native.""" + """Return the recipe's DSA, MTP, CP and EP entries; NPU-only norm and expert kernels stay native.""" return [ + {"match": "mtp.layers.*.eh_proj", "params": {"weight": {"tp": "replicate"}}}, { "match": "*.self_attn", "replace": {"kind": "module", "implementation": { @@ -122,7 +132,14 @@ def _plan_overrides() -> list: "match": "model.layers.[1-9].mlp.forward", "when": "ep", "replace": {"kind": "method", "implementation": { "_target_": "hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn", - "overlap_shared_expert": True, + "router_fn": "topk_router_module", "overlap_shared_expert": True, + }}, + }, + { + "match": "mtp.layers.*.mtp_block.mlp.forward", "when": "ep", + "replace": {"kind": "method", "implementation": { + "_target_": "hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn", + "router_fn": "topk_router_module", "overlap_shared_expert": True, }}, }, ] @@ -160,6 +177,7 @@ def _build_parallel_model(reference, config): _maybe_apply_module_replacements, instantiate_infrastructure, ) + from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import bind_parallel_groups from hyper_parallel.trainer.config import normalize_distributed_setup_overrides from hyper_parallel.trainer.runtime.distributed import create_distributed_setup_from_config @@ -170,7 +188,9 @@ def _build_parallel_model(reference, config): model, _ = _maybe_apply_module_replacements( model, None, setup, None, False, get_model_conversion_mapping(model) ) - for replaced, source in zip(model.model.layers, reference.model.layers): + replaced_layers = [*model.model.layers, *(layer.mtp_block for layer in model.mtp.layers)] + source_layers = [*reference.model.layers, *(layer.mtp_block for layer in reference.mtp.layers)] + for replaced, source in zip(replaced_layers, source_layers): with torch.no_grad(): replaced.self_attn.linear_qkv.weight.copy_(torch.cat([ source.self_attn.q_a_proj.weight, source.self_attn.kv_a_proj_with_mqa.weight, @@ -182,6 +202,7 @@ def _build_parallel_model(reference, config): ) model, source_shard_info = apply_sharding_plan(model, plan, mesh) model = _apply_fsdp2_with_external(model, fsdp_manager, source_shard_info, None) + bind_parallel_groups(model, mesh) return model, mesh, source_shard_info or {} @@ -221,6 +242,16 @@ def _block_diagonal_mask(boundaries): return mask +def _expert_loads(model): + """Return each training router's routed-token counts by module name.""" + from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=import-outside-toplevel + DeepseekV32Router, + ) + + return {name: module.tokens_per_expert for name, module in model.named_modules() + if isinstance(module, DeepseekV32Router)} + + def _run_case(*, tp=1, cp=1, ep=1, loss_parallel=False, packed=False): """Compare one parallel topology against the single-process model.""" # pylint: disable=import-outside-toplevel @@ -248,7 +279,7 @@ def _run_case(*, tp=1, cp=1, ep=1, loss_parallel=False, packed=False): reference_mask = {"attention_mask": _block_diagonal_mask(_PACKED_BOUNDARIES)} if packed else {} expected = reference(input_ids=inputs, labels=labels, shift_labels=labels, position_ids=positions, use_cache=False, **reference_mask) - expected.loss.backward() + sum(expected.loss.values()).backward() local = slice(mesh.cp_rank * _SEQ_LEN // cp, (mesh.cp_rank + 1) * _SEQ_LEN // cp) boundaries = {} @@ -265,17 +296,30 @@ def _run_case(*, tp=1, cp=1, ep=1, loss_parallel=False, packed=False): shift_labels=labels[:, local].contiguous(), position_ids=positions[:, local], use_cache=False, **boundaries, ) - output.loss.backward() - - loss = output.loss.detach().reshape(()).clone() - if cp > 1: - dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=mesh.device_mesh["cp"].get_group()) - torch.testing.assert_close(loss, expected.loss.detach(), rtol=1e-5, atol=1e-6) + sum(output.loss.values()).backward() + + same_keys = set(output.loss) == set(expected.loss) == {"foundation_loss", "foundation_loss/mtp"} + assert same_keys, f"loss keys differ: {set(output.loss)} vs {set(expected.loss)}" + for key, value in output.loss.items(): + loss = value.detach().reshape(()).clone() + if cp > 1: + dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=mesh.device_mesh["cp"].get_group()) + torch.testing.assert_close(loss, expected.loss[key].detach(), rtol=1e-5, atol=1e-6, msg=key) compared = 0 for name, grad, reference_grad in _compared_gradients(model, reference, source_shard_info): torch.testing.assert_close(grad, reference_grad, rtol=1e-4, atol=1e-6, msg=name) compared += 1 assert compared, "no parallel gradient was compared" + # The Trainer's MoE monitor sums expert loads over DP x CP before the bias update. + dp_cp_mesh = mesh.dp_cp_mesh + expected_loads = _expert_loads(reference) + loads = _expert_loads(model) + assert loads.keys() == expected_loads.keys() and loads, "router sets differ" + for name, counts in loads.items(): + counts = counts.clone() + if dp_cp_mesh is not None and dp_cp_mesh.size() > 1: + dist.all_reduce(counts, group=dp_cp_mesh.get_group()) + torch.testing.assert_close(counts, expected_loads[name], msg=name) finally: dist_nn.all_gather = original_all_gather dist.destroy_process_group() diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py index 47b883d6a1..6546d32a09 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py @@ -117,11 +117,14 @@ def test_ep_entries_target_exactly_the_moe_layers(self): """Feature: DeepSeek-V3.2 EP plan overrides. Description: Activate the recipe at EP>1 and match its MLP globs against the released depth. - Expectation: Only MoE layers receive the EP compute; CP and EP stay off at size one. + Expectation: Only MoE layers, including the MTP depth, receive the EP compute; CP and EP stay + off at size one. """ released = DeepseekV32Config() mlps = [f"model.layers.{index}.mlp" for index in range(released.num_hidden_layers)] sparse = [name for name, kind in zip(mlps, released.mlp_layer_types) if kind == "sparse"] + mlps.append("mtp.layers.0.mtp_block.mlp") + sparse.append("mtp.layers.0.mtp_block.mlp") with reference_dsa_kernels(): from hyper_parallel.trainer.config import ( # pylint: disable=import-outside-toplevel entries_to_plan_overrides, @@ -130,7 +133,7 @@ def test_ep_entries_target_exactly_the_moe_layers(self): parse_training_args, ) entries = parse_training_args([str(_RECIPE)]).plan_overrides - self.assertEqual(entries_to_plan_overrides(entries), {}) + self.assertEqual(set(entries_to_plan_overrides(entries)), {"mtp.layers.*.eh_proj"}) active = entries_to_plan_overrides(entries, cp_size=2, ep_size=2) ep_globs = [key for key, spec in active.items() if spec.local_compute_fn is not None] matched = [name for name in mlps if any(fnmatch.fnmatchcase(name, glob) for glob in ep_globs)] diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py new file mode 100644 index 0000000000..1abed17d26 --- /dev/null +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py @@ -0,0 +1,259 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 training objectives: balance loss, expert bias, MTP and checkpoint names.""" + +import tempfile +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +import torch +from safetensors.torch import save_file +from transformers import DeepseekV32Config +from transformers.masking_utils import create_causal_mask +from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter + +from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( + DeepseekV32Router, + DeepseekV32TrainingForCausalLM, +) +from tests.common.dsa_reference_kernels import reference_dsa_kernels +from tests.common.mark_utils import arg_mark + + +def _tiny_config(**overrides) -> DeepseekV32Config: + """Return one dense layer, one MoE layer and one MoE MTP depth.""" + values = { + "vocab_size": 96, "hidden_size": 48, "intermediate_size": 64, "moe_intermediate_size": 16, + "num_hidden_layers": 2, "first_k_dense_replace": 1, "num_attention_heads": 4, + "num_key_value_heads": 4, "n_shared_experts": 1, "n_routed_experts": 8, "n_group": 2, + "topk_group": 1, "num_experts_per_tok": 2, "kv_lora_rank": 16, "q_lora_rank": 24, + "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 4, + "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, "attn_implementation": "sdpa", + "num_nextn_predict_layers": 1, + } + values.update(overrides) + config = DeepseekV32Config.from_dict(values) + config.architectures = ["DeepseekV32ForCausalLM"] + return config + + +def _router(config, **options): + """Return a training router over a randomly initialized Transformers router.""" + torch.manual_seed(1) + source = DeepseekV32TopkRouter(config) + with torch.no_grad(): + source.weight.normal_(std=0.2) + source.e_score_correction_bias.normal_(std=0.05) + return source, DeepseekV32Router.from_router(source, config, **options) + + +def _reference_balance_loss(scores, indices, batch_size, top_k): + """Sequence-wise balance loss, one sample at a time.""" + num_experts = scores.shape[-1] + sequence_length = scores.shape[0] // batch_size + losses = [] + for sample in range(batch_size): + rows = slice(sample * sequence_length, (sample + 1) * sequence_length) + load = torch.zeros(num_experts) + for expert in indices[rows].reshape(-1).tolist(): + load[expert] += 1 + load = load * num_experts / (sequence_length * top_k) + probability = scores[rows] / scores[rows].sum(dim=-1, keepdim=True) + losses.append((load * probability.mean(dim=0)).sum()) + return torch.stack(losses).mean() + + +class TestDeepseekV32Router(unittest.TestCase): + """The training router keeps Transformers routing and adds the training objectives.""" + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_selection_and_balance_loss(self): + """Feature: DeepSeek-V3.2 training router. + + Description: Route two samples through the Transformers and the training router. + Expectation: Indices and gate values match; the balance loss and its router gradient + match the per-sample definition on the biased, group-limited selection. + """ + config = _tiny_config() + source, router = _router(config, aux_loss_coeff=0.5) + hidden = torch.randn(2, 6, config.hidden_size) + _, expected_weights, expected_indices = source(hidden) + router.train() + _, weights, indices = router(hidden) + torch.testing.assert_close(indices, expected_indices, rtol=0, atol=0) + torch.testing.assert_close(weights, expected_weights) + + router.weight.grad = None + (weights * 0).sum().backward() + reference_weight = router.weight.detach().clone().requires_grad_() + flat = hidden.reshape(-1, config.hidden_size) + scores = torch.nn.functional.linear(flat, reference_weight).sigmoid() # pylint: disable=not-callable + reference = _reference_balance_loss(scores, indices, batch_size=2, top_k=config.num_experts_per_tok) + torch.testing.assert_close(router.last_aux_loss, reference.detach()) + (0.5 * reference).backward() + torch.testing.assert_close(router.weight.grad, reference_weight.grad) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_expert_bias_update(self): + """Feature: Loss-free expert-bias update. + + Description: Count routed tokens in training, skip a recomputed forward, then update. + Expectation: Each bias moves by the rate toward the mean load and the counts reset. + """ + config = _tiny_config() + _, router = _router(config, enable_expert_bias=True) + router.train() + hidden = torch.randn(1, 5, config.hidden_size) + _, _, indices = router(hidden) + with patch("hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.is_recomputing", return_value=True): + router(hidden) + counts = torch.bincount(indices.reshape(-1), minlength=config.n_routed_experts) + torch.testing.assert_close(router.tokens_per_expert, counts) + before = router.e_score_correction_bias.clone() + router.update_expert_bias(lr=1e-3) + expected = before + 1e-3 * torch.sign(counts.float().mean() - counts.float()) + torch.testing.assert_close(router.e_score_correction_bias, expected) + self.assertEqual(int(router.tokens_per_expert.sum()), 0) + + +class TestDeepseekV32MultiTokenPrediction(unittest.TestCase): + """MTP depth 1 predicts token i + 2 from the trunk state at i and token i + 1.""" + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_mtp_loss_matches_truncated_depth(self): + """Feature: DeepSeek-V3.2 MTP loss. + + Description: Compare the full-length MTP loss with the depth evaluated on the first + S - 1 positions, whose last target is the final label. + Expectation: Equal losses, scaled by 0.3, with the LM loss under ``foundation_loss``. + """ + torch.manual_seed(2) + model = DeepseekV32TrainingForCausalLM(_tiny_config()).float().train() + tokens = torch.randint(1, 96, (2, 13)) + inputs, labels = tokens[:, :-1].contiguous(), tokens[:, 1:].contiguous() + captured = {} + hook = model.model.norm.register_forward_pre_hook(lambda _, args: captured.setdefault("hidden", args[0])) + with torch.no_grad(): + output = model(input_ids=inputs, labels=labels, shift_labels=labels, use_cache=False) + hook.remove() + length = inputs.shape[1] - 1 + positions = torch.arange(length).unsqueeze(0) + embeds = model.model.embed_tokens(inputs[:, 1:]) + mask = create_causal_mask(config=model.config, inputs_embeds=embeds, attention_mask=None, + past_key_values=None, position_ids=positions, allow_is_causal_skip=False) + hidden = model.mtp.layers[0]( + captured["hidden"][:, :-1], embeds, attention_mask=mask, position_ids=positions, + position_embeddings=model.model.rotary_emb(embeds, positions), + ) + logits = model.lm_head(hidden) + expected = torch.nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]), + labels[:, 1:].reshape(-1)) + torch.testing.assert_close(output.loss["foundation_loss/mtp"], 0.3 * expected) + torch.testing.assert_close(output.extra_metrics["mtp_1_loss"], expected) + self.assertIn("foundation_loss", output.loss) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_released_mtp_layer_loads_into_mtp(self): + """Feature: DeepSeek-V3.2 MTP checkpoint names. + + Description: Save the MTP depth under the released layer names, with per-expert + weights and its own embedding and head copies, then load the training model. + Expectation: Every MTP parameter is loaded and the copies are not. + """ + config = _tiny_config() + torch.manual_seed(3) + source = DeepseekV32TrainingForCausalLM(config).float() + layer = config.num_hidden_layers + state = {} + for name, tensor in source.state_dict().items(): + name = name.replace("mtp.layers.0.mtp_block.", f"model.layers.{layer}.") + name = name.replace("mtp.layers.0.post_norm.", f"model.layers.{layer}.shared_head.norm.") + name = name.replace("mtp.layers.0.", f"model.layers.{layer}.") + if name.endswith("mlp.experts.gate_up_proj"): + gate, up = tensor.chunk(2, dim=1) + for expert in range(tensor.shape[0]): + state[name.replace("gate_up_proj", f"{expert}.gate_proj.weight")] = gate[expert].clone() + state[name.replace("gate_up_proj", f"{expert}.up_proj.weight")] = up[expert].clone() + elif name.endswith("mlp.experts.down_proj"): + for expert in range(tensor.shape[0]): + state[name.replace("down_proj", f"{expert}.down_proj.weight")] = tensor[expert].clone() + else: + state[name] = tensor.clone().contiguous() + state[f"model.layers.{layer}.embed_tokens.weight"] = torch.zeros(config.vocab_size, config.hidden_size) + state[f"model.layers.{layer}.shared_head.head.weight"] = torch.zeros(config.vocab_size, config.hidden_size) + with tempfile.TemporaryDirectory() as directory: + config.save_pretrained(directory) + save_file(state, f"{directory}/model.safetensors") + loaded, info = DeepseekV32TrainingForCausalLM.from_pretrained( + directory, torch_dtype=torch.float32, output_loading_info=True, + ) + self.assertEqual(info["missing_keys"], set()) + expected = source.state_dict() + for name, tensor in loaded.state_dict().items(): + if name.startswith("mtp.") or name.startswith("model.embed_tokens"): + torch.testing.assert_close(tensor, expected[name], msg=name) + + +class TestDeepseekV32IndexerOptions(unittest.TestCase): + """Indexer rotation and the tensor-parallel KL teacher.""" + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_hadamard_rotation_preserves_scores(self): + """Feature: Indexer Hadamard rotation. + + Description: Rotate indexer queries and keys. + Expectation: The Sylvester matrix is orthogonal up to its size and query-key dot + products are unchanged. + """ + with reference_dsa_kernels(): + # pylint: disable=import-outside-toplevel,protected-access + from hyper_parallel.components.modules.dsa_attention import _hadamard_matrix, _rotate_activation + + matrix = _hadamard_matrix(16, torch.float64, torch.device("cpu")) + torch.testing.assert_close(matrix @ matrix.T, 16 * torch.eye(16, dtype=torch.float64)) + query, key = torch.randn(5, 3, 16, dtype=torch.float64), torch.randn(7, 16, dtype=torch.float64) + torch.testing.assert_close(_rotate_activation(query) @ _rotate_activation(key).T, query @ key.T) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_kl_teacher_requires_head_group_under_tensor_parallelism(self): + """Feature: DSA indexer KL under tensor parallelism. + + Description: Resolve the KL head group for whole and TP-sharded attention heads. + Expectation: Whole heads need no group; sharded heads use the bound group and + fail without one. + """ + with reference_dsa_kernels(): + # pylint: disable=import-outside-toplevel,protected-access + from hyper_parallel.components.modules.dsa_attention import DeepseekV32DSAAttention + + resolve = DeepseekV32DSAAttention._kl_head_group + self.assertIsNone(resolve(SimpleNamespace(num_heads=4, kl_head_group=None))) + sharded = SimpleNamespace(num_heads=2, kl_head_group=None, _hp_full_head_counts={"num_heads": 4}) + with self.assertRaises(RuntimeError): + resolve(sharded) + sharded.kl_head_group = "tp" + self.assertEqual(resolve(sharded), "tp") + + +if __name__ == "__main__": + unittest.main() From f1f64f82d8ad58d666ee2cdfeaa0296ae8e7de5c Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 04:35:49 -0600 Subject: [PATCH 11/20] docs(deepseek_v32): loss comparison against MindSpeed-LLM pretraining 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. --- docs/feature_status.md | 2 +- examples/training_demo/README.md | 62 ++++- .../deepseek_v32/align_mindspeed.yaml | 242 ++++++++++++++++++ .../models/deepseek_v32/recipes/train.yaml | 3 +- 4 files changed, 299 insertions(+), 10 deletions(-) create mode 100644 examples/training_demo/deepseek_v32/align_mindspeed.yaml diff --git a/docs/feature_status.md b/docs/feature_status.md index 8c11c1ee82..e64af27303 100644 --- a/docs/feature_status.md +++ b/docs/feature_status.md @@ -5,7 +5,7 @@ ## 支持模型 - [x] Qwen3-30B-A3B -- [x] DeepSeek-V3.2(DSA + MoE;TP/CP/EP/FSDP 在 CPU/Gloo 上与单卡结果对齐,NPU 端到端未验证) +- [x] DeepSeek-V3.2(DSA + MoE + MTP,含 indexer KL、序列级负载均衡 loss 与专家 bias 更新;TP/CP/EP/FSDP 在 CPU/Gloo 上与单卡结果对齐,NPU 端到端未验证) ## HyperShard diff --git a/examples/training_demo/README.md b/examples/training_demo/README.md index ed934f6690..c57036a4fa 100644 --- a/examples/training_demo/README.md +++ b/examples/training_demo/README.md @@ -116,14 +116,16 @@ overrides may be appended to either command. ## DeepSeek-V3.2 single-card crop -The [single-card configuration](deepseek_v32/train_single_card.yaml) builds -DeepSeek-V3.2 with `HyperAutoModelForCausalLM.from_config` and random weights. -It keeps the released hidden, MLA, indexer, and vocabulary dimensions and crops -the model to two decoder layers (one dense, one MoE) and 16 routed experts, the -fewest that keep the released group routing (`n_group=8`, `topk_group=4`, -top-8). The model has 3.40B parameters; FP32 parameters, FP32 gradients and the -two FP32 AdamW moments take about 51 GiB before activations (estimated, not -measured), which targets one 64 GB device such as 910B3. +The [single-card configuration](deepseek_v32/train_single_card.yaml) builds the +DeepSeek-V3.2 training model with random weights. It keeps the released hidden, +MLA, indexer, and vocabulary dimensions and crops the model to two decoder +layers (one dense, one MoE) and 16 routed experts, the fewest that keep the +released group routing (`n_group=8`, `topk_group=4`, top-8). The model has 3.40B +parameters; FP32 parameters, FP32 gradients and the two FP32 AdamW moments take +about 51 GiB before activations (estimated, not measured), which targets one +64 GB device such as 910B3. The MTP depth would add about 1B parameters, so the +example disables it with `num_nextn_predict_layers: 0`; the balance loss, the +expert-bias update and the indexer KL loss stay on as in the full recipe. Module replacements match the full [recipe](../../hyper_parallel/models/deepseek_v32/recipes/train.yaml). Unlike its @@ -153,6 +155,50 @@ records, so a JSONL whose records are much shorter than 4096 tokens packs several records into each step and can run out before `train_iters`. The log is written to `output/training_demo/deepseek_v32/run_single_card.log`. +## DeepSeek-V3.2 loss comparison with MindSpeed-LLM + +[`align_mindspeed.yaml`](deepseek_v32/align_mindspeed.yaml) trains the same +objectives as MindSpeed-LLM `examples/mcore/deepseek32/pretrain_deepseek32_671b_4k_A3_ptd.sh`: +indexer top-k 1024 with KL weight 1.0 and the Hadamard rotation, the +sequence-wise balance loss (1e-4), the expert-bias update (1e-3 per step), one +MTP depth weighted 0.3, AdamW at 1e-5 with cosine decay to 1e-7 and no warmup, +and FP32 RMSNorm weights. Both sides must start from the same weights and read +the same samples: + +1. Dequantize the released FP8 checkpoint to BF16 once (for example with + DeepSeek's `inference/fp8_cast_bf16.py`). HyperParallel loads this directory; + MindSpeed converts it with `ckpt_convert_deepseek32_hf2mcore.sh`, whose + converter does not dequantize FP8. +2. Build the Megatron `.bin/.idx` dataset with MindSpeed's + `data_convert_deepseek32_pretrain.sh` and point both sides at its prefix. + HyperParallel's indexed dataset reproduces Megatron's `GPTDataset` sample + order when the seed (MindSpeed default 1234), `--split 100,0,0`, + `--seq-length 4096`, `--train-iters` and `--global-batch-size` are equal. + Neither side isolates documents inside a 4096-token window. +3. Keep MindSpeed's model and optimizer flags from its script and enable its + deterministic mode (`--npu-deterministic` and `HCCL_DETERMINISTIC=true`); + `enable_full_determinism` does the same on the HyperParallel side. + +Launch it like the full recipe, on every node with its torchrun arguments: + +```bash +scripts/train_lm.py examples/training_demo/deepseek_v32/align_mindspeed.yaml \ + --model.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2-bf16 \ + --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2-bf16 \ + --dataset.data_path=/path/to/dataset/deepseek32_text_document +``` + +| MindSpeed-LLM log | HyperParallel log | Definition differences | +| --- | --- | --- | +| `lm loss` | `foundation_loss` | None. | +| `mtp_1 loss` | `mtp_1_loss` | HyperParallel sums the step's micro-batches; divide by the gradient-accumulation count. | +| `dsa_indexer_loss` | `dsa_indexer_loss` | MindSpeed divides the layer sum by `--num-layers`, which includes no-op layers (64 for 61 layers in its script); HyperParallel averages the 61 trunk layers and sums micro-batches. | +| `load_balancing_loss` | `router_aux_loss` | HyperParallel also averages the MTP router. | + +The DSA-internal norms (`q_a_layernorm`, `kv_a_layernorm` and the indexer +`k_norm`) run with BF16 weights on the HyperParallel side, so the two runs +differ by BF16 rounding there. + ## DeepSeek-V4.1 text pretraining The [text configuration](deepseek_v41/train_deepseek_v41_online.yaml) retains all diff --git a/examples/training_demo/deepseek_v32/align_mindspeed.yaml b/examples/training_demo/deepseek_v32/align_mindspeed.yaml new file mode 100644 index 0000000000..6946963b67 --- /dev/null +++ b/examples/training_demo/deepseek_v32/align_mindspeed.yaml @@ -0,0 +1,242 @@ +# DeepSeek-V3.2 与 MindSpeed-LLM 预训练做 loss 对比的配置。 +# +# 训练语义对应 MindSpeed-LLM examples/mcore/deepseek32/pretrain_deepseek32_671b_4k_A3_ptd.sh: +# DSA:index_topk 1024,indexer KL 系数 1.0,indexer q/k 打分前做 Hadamard 旋转; +# MoE:sigmoid 分组路由,序列级负载均衡 loss 1e-4,专家 bias 每步按负载 ±1e-3; +# MTP:1 层,loss 系数 0.3; +# 优化器:AdamW lr 1e-5,cosine 衰减到 1e-7,无 warmup,weight decay 0.01, +# betas (0.9, 0.999),梯度裁剪 1.0;RMSNorm 权重保持 FP32(对应 --init-norm-weight-in-fp32); +# 数据:两边读同一份 Megatron .bin/.idx,seed 1234、split 100,0,0、seq_length 4096, +# 每个 4096 窗口是一条完整的因果序列(不按文档隔离,对应未开 --reset-attention-mask)。 +# 两边需要一致的设置、MindSpeed 侧命令和日志指标的对应关系见同目录 README 的对齐小节。 +# +# 拓扑与完整配方相同(512 卡,ep 64 × edp 8);并行方式不改变计算语义,可以按机器调整。 + +model: + _target_: hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.build_model + # 官方 FP8 权重反量化后的 BF16 Hugging Face 目录,MindSpeed 侧转换同一份。 + pretrained_model_name_or_path: /path/to/DeepSeek-V3.2-bf16 + torch_dtype: bfloat16 + attn_implementation: sdpa + config_overrides: + index_topk: 1024 + mtp_loss_scaling_factor: 0.3 + moe_aux_loss_coeff: 1.0e-4 + moe_router_enable_expert_bias: true + moe_router_bias_update_rate: 1.0e-3 + dsa_loss_coeff: 1.0 + index_rotate_activation: true + +model_init_dtype: float32 + +training: + # 与 MindSpeed 的 --train-iters / --global-batch-size 保持一致:样本顺序由总样本数决定。 + train_iters: 2000 + train_samples: null + eval_iters: 0 + global_batch_size: 7680 + micro_batch_size: 1 + backend: hccl + init_device: meta + loss_aggregation: token_weighted + max_grad_norm: 1.0 + seed: 1234 + enable_full_determinism: true + +accelerator: + tp_size: 1 + cp_size: 1 + ep_size: 64 + pp_size: 1 + sequence_parallel: false + loss_parallel: false + +fsdp_config: + dp_shard_size: 512 + edp_shard_size: 4 + replicate_params: [] + mix_precision: + param_dtype: bfloat16 + reduce_dtype: float32 + cast_forward_inputs: false + custom_params: + "*.input_layernorm.weight": {param_dtype: float32} + "*.post_attention_layernorm.weight": {param_dtype: float32} + model.norm.weight: {param_dtype: float32} + mtp.layers.*.enorm.weight: {param_dtype: float32} + mtp.layers.*.hnorm.weight: {param_dtype: float32} + mtp.layers.*.post_norm.weight: {param_dtype: float32} + reshard_after_forward: true + reshard_after_backward: true + requires_grad_sync: true + forward_prefetch_depth: 1 + backward_prefetch_depth: 1 + comm_fusion: false + +plan_overrides: + - match: mtp.layers.*.eh_proj + params: + weight: {tp: replicate} + - match: + - "*.input_layernorm" + - "*.post_attention_layernorm" + - model.norm + - "mtp.layers.*.enorm" + - "mtp.layers.*.hnorm" + - "mtp.layers.*.post_norm" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_rms_norm + - match: "*.self_attn" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + - match: "*.mlp.experts" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_grouped_experts + - match: "*.self_attn.forward" + when: cp + replace: + kind: method + implementation: + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper + dense_warmup: false + - match: "model.layers.[3-9].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + router_fn: topk_router_module + use_grouped_gemm: true + overlap_shared_expert: true + - match: "model.layers.[1-9][0-9].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + router_fn: topk_router_module + use_grouped_gemm: true + overlap_shared_expert: true + - match: "mtp.layers.*.mtp_block.mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + router_fn: topk_router_module + use_grouped_gemm: true + overlap_shared_expert: true + +mixed_precision: + enabled: false + +activation_checkpoint: + mode: full + +activation_swap: none + +compile: + enabled: false + mode: default + fullgraph: false + dynamic: false + backend: null + options: {} + dynamo_cache_size_limit: 256 + +dataset: + model_assets: + chat_template: null + tokenizer: + _target_: hyper_parallel.data.text.build_tokenizer.AutoTokenizer.from_pretrained + pretrained_model_name_or_path: /path/to/DeepSeek-V3.2-bf16 + tokenizer_type: pretokenized + vocab_size: 129280 + eod_token_id: 1 + _target_: hyper_parallel.data.text.build_dataset.build_indexed_text_dataset + # MindSpeed data_convert_deepseek32_pretrain.sh 输出的前缀(不带 .bin/.idx 后缀)。 + data_path: /path/to/dataset/deepseek32_text_document + data_config: + seq_length: 4096 + split: "100,0,0" + mock_data: false + distributed_walk: true + is_dataset_from_mr: false + simple_blend: "no" + data_lazy_load: true + skip_data_check: true + labels_are_shifted: true + create_attention_mask_in_dataloader: false + create_ltor_fields_in_dataloader: false + +dataloader: + _target_: hyper_parallel.data.batching.FixedBatchDataLoader + collate_fn: + _target_: hyper_parallel.data.batching.build_default_collate_fn + get_batch: + _target_: hyper_parallel.data.batching.TextParallelBatch + source_type: indexed + # 不配 runtime_input_adapter:每行是一条因果序列,与 MindSpeed 未开 --reset-attention-mask 一致。 + attention_mode: compressed + sampler_type: single + data_rearrange_map: null + data_sharding: false + drop_last: true + use_background_prefetcher: false + num_workers: 0 + pin_memory: false + prefetch_factor: null + +optimizer: + _target_: hyper_parallel.components.optim.AdamW + fp32_main_params: true + no_decay_params: [bias, norm, ln_] + adamw_config: + lr: 1.0e-5 + adamw_lr: 1.0e-5 + adamw_weight_decay: 0.01 + adamw_betas: [0.9, 0.999] + adamw_eps: 1.0e-8 + +lr_scheduler: + _target_: hyper_parallel.components.optim.MultiLRScheduler + lr_decay_style: cosine + lr_config: + lr: 1.0e-5 + lr_warmup_steps: 0 + min_lr: 1.0e-7 + +checkpoint: + save_ckpt: false + checkpoint_dir: ./outputs/deepseek_v32_align/checkpoints + save_steps: 2000 + save_epochs: 1 + is_async: false + save_optimizer: true + save_train_state: true + save_extra_state_per_rank: false + restore_from: null + restore_optimizer: true + restore_train_state: true + +debug: + check_nan_inf: false + check_dataset: null + +profiler: + enable: false + start_step: 3 + stop_step: 3 + output_path: ./outputs/deepseek_v32_align/profiling + memory: false + with_stack: false + rank_ids: [0] diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index 6e47904fd4..a9e6acc27e 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -28,7 +28,8 @@ # --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2 # # 单卡裁剪示例(2 层、16 个路由专家、随机初始化)见 -# examples/training_demo/deepseek_v32/train_single_card.yaml。 +# examples/training_demo/deepseek_v32/train_single_card.yaml;与 MindSpeed-LLM 做精度对比的配置见 +# examples/training_demo/deepseek_v32/align_mindspeed.yaml。 model: # 训练模型:在 Transformers 的 DeepSeek-V3.2 上加 MTP、MoE 负载均衡和 DSA indexer 训练,并绑定并行通信组。 From 7411a15a9898fe5e81079155eb842c90c889bf16 Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 04:42:04 -0600 Subject: [PATCH 12/20] fix(deepseek_v32): save the training model under the released architecture 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. --- .../deepseek_v32/adapter/registration.py | 6 ++--- .../deepseek_v32/modeling_deepseek_v32.py | 15 ++++++----- .../_test_deepseek_v32_parallel.py | 4 +-- .../test_deepseek_v32_training_model.py | 25 +++++++++++++------ 4 files changed, 32 insertions(+), 18 deletions(-) diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index a1bb6e5059..9d39710187 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -14,8 +14,8 @@ # ============================================================================ """Architecture and lazy provider registration for DeepSeek-V3.2. -``DeepseekV32ForCausalLM`` checkpoints build -:class:`~hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.DeepseekV32TrainingForCausalLM` +``DeepseekV32ForCausalLM`` checkpoints build the training model +:class:`~hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.DeepseekV32ForCausalLM` unless a recipe forces the Transformers class. """ @@ -66,7 +66,7 @@ def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: register_custom_model( "DeepseekV32ForCausalLM", "hyper_parallel.models.deepseek_v32.modeling_deepseek_v32", - "DeepseekV32TrainingForCausalLM", + "DeepseekV32ForCausalLM", ) DEEPSEEK_V32_ADAPTER_SPEC = ModelAdapterSpec( diff --git a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py index 88a09f6225..3886fa512e 100644 --- a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py +++ b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py @@ -39,7 +39,7 @@ from transformers.modeling_outputs import MoeCausalLMOutputWithPast from transformers.models.deepseek_v32.modeling_deepseek_v32 import ( DeepseekV32DecoderLayer, - DeepseekV32ForCausalLM, + DeepseekV32ForCausalLM as TransformersDeepseekV32ForCausalLM, DeepseekV32MoE, DeepseekV32RMSNorm, DeepseekV32TopkRouter, @@ -56,7 +56,7 @@ __all__ = [ "DeepseekV32Router", - "DeepseekV32TrainingForCausalLM", + "DeepseekV32ForCausalLM", "DeepseekV32TrainingOutput", "bind_parallel_groups", "build_model", @@ -207,9 +207,12 @@ def _mtp_layer_config(config: Any, layer_idx: int) -> Any: return layer_config -class DeepseekV32TrainingForCausalLM(DeepseekV32ForCausalLM): +class DeepseekV32ForCausalLM(TransformersDeepseekV32ForCausalLM): """DeepSeek-V3.2 causal LM with MoE balancing, MTP and DSA indexer training. + It keeps the released architecture name, so checkpoints it saves load like + the released one. + Args: config: DeepSeek-V3.2 configuration. ``num_nextn_predict_layers`` sets the MTP depth; 0 disables MTP. @@ -275,7 +278,7 @@ def __init__(self, config: Any, *, mtp_loss_scaling_factor: float = 0.3, self.post_init() @classmethod - def from_config(cls, config: Any, **kwargs: Any) -> "DeepseekV32TrainingForCausalLM": + def from_config(cls, config: Any, **kwargs: Any) -> "DeepseekV32ForCausalLM": """Construct from a configuration through the shared custom-model builder.""" return cls._from_config(config, **kwargs) @@ -410,7 +413,7 @@ def bind_parallel_groups(model: nn.Module, mesh: Any) -> None: tp_group = mesh.device_mesh["tp"].get_group() if mesh.tp_size > 1 else None tp_replicas = mesh.tp_size if mesh.loss_parallel else 1 for module in model.modules(): - if isinstance(module, DeepseekV32TrainingForCausalLM): + if isinstance(module, DeepseekV32ForCausalLM): module.sequence_group = cp_group elif isinstance(module, DeepseekV32Router): module.sequence_partition_group = cp_group @@ -427,7 +430,7 @@ def build_model(**options: Any) -> nn.Module: **options: ``pretrained_model_name_or_path`` loads a checkpoint; otherwise ``config`` builds from a configuration. The remaining options go to ``HyperAutoModelForCausalLM`` and, for the training options of - :class:`DeepseekV32TrainingForCausalLM`, to the model constructor. + :class:`DeepseekV32ForCausalLM`, to the model constructor. Returns: The constructed and parallelized model. diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index b30511966c..3a8a7137ec 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -98,11 +98,11 @@ def _config() -> DeepseekV32Config: def _reference_model(): """Build the unsharded training model with nonzero expert-selection biases.""" from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=import-outside-toplevel - DeepseekV32TrainingForCausalLM, + DeepseekV32ForCausalLM, ) torch.manual_seed(7) - model = DeepseekV32TrainingForCausalLM( + model = DeepseekV32ForCausalLM( _config(), moe_aux_loss_coeff=0.1, moe_router_enable_expert_bias=True, ).float().train() with torch.no_grad(): diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py index 1abed17d26..3dd927b31d 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py @@ -14,20 +14,22 @@ # ============================================================================ """DeepSeek-V3.2 training objectives: balance loss, expert bias, MTP and checkpoint names.""" +import json import tempfile import unittest from types import SimpleNamespace from unittest.mock import patch import torch +from safetensors import safe_open from safetensors.torch import save_file from transformers import DeepseekV32Config from transformers.masking_utils import create_causal_mask from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( + DeepseekV32ForCausalLM, DeepseekV32Router, - DeepseekV32TrainingForCausalLM, ) from tests.common.dsa_reference_kernels import reference_dsa_kernels from tests.common.mark_utils import arg_mark @@ -145,7 +147,7 @@ def test_mtp_loss_matches_truncated_depth(self): Expectation: Equal losses, scaled by 0.3, with the LM loss under ``foundation_loss``. """ torch.manual_seed(2) - model = DeepseekV32TrainingForCausalLM(_tiny_config()).float().train() + model = DeepseekV32ForCausalLM(_tiny_config()).float().train() tokens = torch.randint(1, 96, (2, 13)) inputs, labels = tokens[:, :-1].contiguous(), tokens[:, 1:].contiguous() captured = {} @@ -171,16 +173,17 @@ def test_mtp_loss_matches_truncated_depth(self): @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", card_mark="allcards", essential_mark="essential") - def test_released_mtp_layer_loads_into_mtp(self): + def test_released_mtp_layer_round_trips(self): """Feature: DeepSeek-V3.2 MTP checkpoint names. Description: Save the MTP depth under the released layer names, with per-expert - weights and its own embedding and head copies, then load the training model. - Expectation: Every MTP parameter is loaded and the copies are not. + weights and its own embedding and head copies, load the training model and save it. + Expectation: Every MTP parameter is loaded and the copies are not; the saved + checkpoint has the released architecture and weight names. """ config = _tiny_config() torch.manual_seed(3) - source = DeepseekV32TrainingForCausalLM(config).float() + source = DeepseekV32ForCausalLM(config).float() layer = config.num_hidden_layers state = {} for name, tensor in source.state_dict().items(): @@ -202,14 +205,22 @@ def test_released_mtp_layer_loads_into_mtp(self): with tempfile.TemporaryDirectory() as directory: config.save_pretrained(directory) save_file(state, f"{directory}/model.safetensors") - loaded, info = DeepseekV32TrainingForCausalLM.from_pretrained( + loaded, info = DeepseekV32ForCausalLM.from_pretrained( directory, torch_dtype=torch.float32, output_loading_info=True, ) + loaded.save_pretrained(f"{directory}/export") + with open(f"{directory}/export/config.json", encoding="utf-8") as handle: + architectures = json.load(handle)["architectures"] + with safe_open(f"{directory}/export/model.safetensors", "pt") as handle: + exported = set(handle.keys()) self.assertEqual(info["missing_keys"], set()) expected = source.state_dict() for name, tensor in loaded.state_dict().items(): if name.startswith("mtp.") or name.startswith("model.embed_tokens"): torch.testing.assert_close(tensor, expected[name], msg=name) + self.assertEqual(architectures, ["DeepseekV32ForCausalLM"]) + copies = {f"model.layers.{layer}.embed_tokens.weight", f"model.layers.{layer}.shared_head.head.weight"} + self.assertEqual(exported, set(state) - copies) class TestDeepseekV32IndexerOptions(unittest.TestCase): From a17635f0fbf224719855243c131cec4b124b65bf Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 04:44:23 -0600 Subject: [PATCH 13/20] docs(deepseek_v32): MindSpeed conversion layout for the loss comparison 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. --- examples/training_demo/README.md | 15 ++++++++++----- .../deepseek_v32/align_mindspeed.yaml | 6 ++++-- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/examples/training_demo/README.md b/examples/training_demo/README.md index c57036a4fa..5d837c6c43 100644 --- a/examples/training_demo/README.md +++ b/examples/training_demo/README.md @@ -168,13 +168,18 @@ the same samples: 1. Dequantize the released FP8 checkpoint to BF16 once (for example with DeepSeek's `inference/fp8_cast_bf16.py`). HyperParallel loads this directory; MindSpeed converts it with `ckpt_convert_deepseek32_hf2mcore.sh`, whose - converter does not dequantize FP8. + converter does not dequantize FP8. Convert to the training script's layout + (`--target-tensor-parallel-size 4 --target-pipeline-parallel-size 8 + --target-expert-parallel-size 64 --num-layers-per-virtual-pipeline-stage 2 + --noop-layers 7,62,63 --mtp-num-layers 1`); the shipped conversion script + uses TP 1 and `--noop-layers 61,62,63`, which do not match it. 2. Build the Megatron `.bin/.idx` dataset with MindSpeed's `data_convert_deepseek32_pretrain.sh` and point both sides at its prefix. - HyperParallel's indexed dataset reproduces Megatron's `GPTDataset` sample - order when the seed (MindSpeed default 1234), `--split 100,0,0`, - `--seq-length 4096`, `--train-iters` and `--global-batch-size` are equal. - Neither side isolates documents inside a 4096-token window. + Both sides derive the document, sample and shuffle indices from the seed + (MindSpeed default 1234), the split (`--split 100,0,0`), `--seq-length 4096` + and the sample count (`--train-iters` × `--global-batch-size`), so keep them + equal; compare the first step's `lm loss` before a long run. Neither side + isolates documents inside a 4096-token window. 3. Keep MindSpeed's model and optimizer flags from its script and enable its deterministic mode (`--npu-deterministic` and `HCCL_DETERMINISTIC=true`); `enable_full_determinism` does the same on the HyperParallel side. diff --git a/examples/training_demo/deepseek_v32/align_mindspeed.yaml b/examples/training_demo/deepseek_v32/align_mindspeed.yaml index 6946963b67..d34895d6ee 100644 --- a/examples/training_demo/deepseek_v32/align_mindspeed.yaml +++ b/examples/training_demo/deepseek_v32/align_mindspeed.yaml @@ -5,10 +5,12 @@ # MoE:sigmoid 分组路由,序列级负载均衡 loss 1e-4,专家 bias 每步按负载 ±1e-3; # MTP:1 层,loss 系数 0.3; # 优化器:AdamW lr 1e-5,cosine 衰减到 1e-7,无 warmup,weight decay 0.01, -# betas (0.9, 0.999),梯度裁剪 1.0;RMSNorm 权重保持 FP32(对应 --init-norm-weight-in-fp32); +# betas (0.9, 0.999),梯度裁剪 1.0;层间 RMSNorm 权重保持 FP32(对应 --init-norm-weight-in-fp32, +# DSA 内部的 q_a/kv_a/k_norm 仍为 BF16); # 数据:两边读同一份 Megatron .bin/.idx,seed 1234、split 100,0,0、seq_length 4096, # 每个 4096 窗口是一条完整的因果序列(不按文档隔离,对应未开 --reset-attention-mask)。 -# 两边需要一致的设置、MindSpeed 侧命令和日志指标的对应关系见同目录 README 的对齐小节。 +# 两边需要一致的设置(权重与数据转换、确定性开关)和日志指标的对应关系见 +# examples/training_demo/README.md 的 MindSpeed-LLM 对比小节。 # # 拓扑与完整配方相同(512 卡,ep 64 × edp 8);并行方式不改变计算语义,可以按机器调整。 From aa05698ecd7b8d335149d30b165833bcbdeff40f Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 22:19:54 -0600 Subject: [PATCH 14/20] refactor(deepseek_v32): own the EP compute factory in the model adapter 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. --- .../deepseek_v32/align_mindspeed.yaml | 9 +- .../distributed/expert_parallel/recipes.py | 7 +- .../adapter/distributed/expert_parallel.py | 106 ++++++++++++++++++ .../models/deepseek_v32/recipes/train.yaml | 13 +-- .../_test_deepseek_v32_parallel.py | 8 +- 5 files changed, 119 insertions(+), 24 deletions(-) create mode 100644 hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py diff --git a/examples/training_demo/deepseek_v32/align_mindspeed.yaml b/examples/training_demo/deepseek_v32/align_mindspeed.yaml index d34895d6ee..7170f78f59 100644 --- a/examples/training_demo/deepseek_v32/align_mindspeed.yaml +++ b/examples/training_demo/deepseek_v32/align_mindspeed.yaml @@ -115,8 +115,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn - router_fn: topk_router_module + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - match: "model.layers.[1-9][0-9].mlp.forward" @@ -124,8 +123,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn - router_fn: topk_router_module + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - match: "mtp.layers.*.mtp_block.mlp.forward" @@ -133,8 +131,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn - router_fn: topk_router_module + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true diff --git a/hyper_parallel/distributed/expert_parallel/recipes.py b/hyper_parallel/distributed/expert_parallel/recipes.py index 72d593e89b..58fb7f6089 100644 --- a/hyper_parallel/distributed/expert_parallel/recipes.py +++ b/hyper_parallel/distributed/expert_parallel/recipes.py @@ -343,7 +343,6 @@ def deepseekv3_ep_compute_fn( overlap_shared_expert: bool = False, fix_router: bool = False, capacity_factor: Optional[float] = None, - router_fn: str = "deepseekv3", ) -> Callable: """Archetype ``deepseekv3_sigmoid_group_shared``: sigmoid group-limited routing (with e_score_correction_bias / routed_scaling_factor, already @@ -371,10 +370,6 @@ def deepseekv3_ep_compute_fn( happened to route. Loss / grad_norm / expert-load metrics are meaningless in that mode and it must not be used to report an efficiency number — see ``routing.make_balanced_router``. Correctness runs keep it off. - - ``router_fn="topk_router_module"`` takes the expert indices and gate values - returned by ``module.gate`` instead of recomputing them from its logits, so - a training router can attach auxiliary losses to the gate values. """ del mesh, tp_mesh, cp_mesh @@ -395,7 +390,7 @@ def overlap_shared(module: Any, hidden_states: torch.Tensor) -> torch.Tensor: return build_ep_compute( module, ep_mesh, - router_fn=router_fn, + router_fn="deepseekv3", fix_router=fix_router, archetype_key="deepseekv3_sigmoid_group_shared", expected_attrs=["gate", "experts", "shared_experts"], diff --git a/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py b/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py new file mode 100644 index 0000000000..6b6fbb6f8e --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/distributed/expert_parallel.py @@ -0,0 +1,106 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 expert-parallel compute factory. + +The DeepSeek-V3.2 router returns the complete routing decision +``(router_logits, topk_weights, topk_indices)``: sigmoid scores, the +``e_score_correction_bias`` used only for selection, group-limited top-k, +normalisation and ``routed_scaling_factor``. The training router also attaches +the sequence-wise balance loss to ``topk_weights`` and counts the expert loads. +The factory therefore consumes that decision through the generic +``topk_router_module`` adapter; re-deriving it from the logits, as the +DeepSeek-V3 archetype does, would drop the balance-loss gradient. Token +dispatch, the local expert GEMMs and the combine come from the generic EP +skeleton; the shared experts are added to the routed output as +``DeepseekV32MoE.forward`` does. +""" + +from typing import Any, Callable, Optional + +import torch # pylint: disable=forbidden-backend-import + +from hyper_parallel.distributed.expert_parallel.recipes import build_ep_compute +from hyper_parallel.distributed.recipe_spec import local_compute + + +@local_compute +def deepseek_v32_ep_compute_fn( + *, + module: Any, + mesh: Any, + tp_mesh: Any, + cp_mesh: Any, + ep_mesh: Any, + use_grouped_gemm: bool = False, + overlap_shared_expert: bool = False, + fix_router: bool = False, + capacity_factor: Optional[float] = None, +) -> Callable: + """Build the EP forward of one ``DeepseekV32MoE`` block. + + Expected module interface: ``gate`` returning ``(logits, weights, + indices)``, batched ``experts`` and ``shared_experts``. + + Args: + module: DeepSeek-V3.2 MoE block. + mesh: Unused; part of the local-compute factory signature. + tp_mesh: Unused. + cp_mesh: Unused. + ep_mesh: Expert mesh whose ``ep`` axis owns the routed experts. + use_grouped_gemm: Run local experts through the grouped-GEMM path. + Required when ``experts`` is the ``GroupedExperts`` replacement, + whose weights use the transposed grouped-GEMM layout. + overlap_shared_expert: Evaluate ``shared_experts`` while the dispatch + exchange is in flight. The shared branch reads only + ``hidden_states``, so the result is unchanged. + fix_router: Benchmark-only balanced routing. Loss, gradient norm and + expert-load statistics are meaningless in that mode. + capacity_factor: Per-expert slot bound of the overlapped dispatch path; + ``None`` keeps dropless routing. + + Returns: + ``compute_fn(module, hidden_states)`` with the block forward signature. + """ + del mesh, tp_mesh, cp_mesh + + def combine( + module: Any, + hidden_states: torch.Tensor, + routed: torch.Tensor, + overlapped: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """Add the shared-experts branch to the routed output.""" + shared = module.shared_experts(hidden_states) if overlapped is None else overlapped + return routed + shared + + def overlap_shared(module: Any, hidden_states: torch.Tensor) -> torch.Tensor: + """Run the shared-experts branch behind the dispatch exchange.""" + return module.shared_experts(hidden_states) + + return build_ep_compute( + module, + ep_mesh, + router_fn="topk_router_module", + fix_router=fix_router, + archetype_key="deepseek_v32_topk_router_shared", + expected_attrs=["gate", "experts", "shared_experts"], + combine=combine, + use_grouped_gemm=use_grouped_gemm, + capacity_factor=capacity_factor, + overlap_fn=overlap_shared if overlap_shared_expert else None, + ) + + +__all__ = ["deepseek_v32_ep_compute_fn"] diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index a9e6acc27e..090c625cf2 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -128,8 +128,8 @@ plan_overrides: _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper # null follows dsa_dense_warm_up; true/false forces one path for the full run. dense_warmup: null - # EP:DeepSeek-V3.2 的 router 与 DeepSeek-V3 相同,用框架内置的 V3 EP 工厂; - # router_fn 取训练 router 返回的专家与门控值,负载均衡 loss 挂在门控值上。 + # EP:模型自己的 EP 工厂直接使用 router 返回的专家与门控值(负载均衡 loss 挂在门控值上), + # token 分发、专家计算与合并沿用框架通用的 EP 骨架。 # 只匹配 MoE 层:first_k_dense_replace=3,层 0-2 为稠密 MLP,层 3-60 与 MTP 层为 MoE; # fnmatch 不支持数值区间,因此分两条 glob 覆盖 3-9 与 10-99。 # 裁剪模型改变稠密层数时需要同步调整这两条 glob。 @@ -138,8 +138,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn - router_fn: topk_router_module + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - match: "model.layers.[1-9][0-9].mlp.forward" @@ -147,8 +146,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn - router_fn: topk_router_module + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - match: "mtp.layers.*.mtp_block.mlp.forward" @@ -156,8 +154,7 @@ plan_overrides: replace: kind: method implementation: - _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn - router_fn: topk_router_module + _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index 3a8a7137ec..965fd17a72 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -131,15 +131,15 @@ def _plan_overrides() -> list: { "match": "model.layers.[1-9].mlp.forward", "when": "ep", "replace": {"kind": "method", "implementation": { - "_target_": "hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn", - "router_fn": "topk_router_module", "overlap_shared_expert": True, + "_target_": f"{_ADAPTER}.distributed.expert_parallel.deepseek_v32_ep_compute_fn", + "overlap_shared_expert": True, }}, }, { "match": "mtp.layers.*.mtp_block.mlp.forward", "when": "ep", "replace": {"kind": "method", "implementation": { - "_target_": "hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn", - "router_fn": "topk_router_module", "overlap_shared_expert": True, + "_target_": f"{_ADAPTER}.distributed.expert_parallel.deepseek_v32_ep_compute_fn", + "overlap_shared_expert": True, }}, }, ] From b54276ec375e40cb1b020c06cceb3005330b85ae Mon Sep 17 00:00:00 2001 From: hf1s Date: Mon, 9 Nov 2026 22:32:25 -0600 Subject: [PATCH 15/20] refactor(deepseek_v32): build through HyperAutoModelForCausalLM, bind 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. --- .../deepseek_v32/align_mindspeed.yaml | 2 +- .../deepseek_v32/cropped_deepseek_v32.py | 12 ++++---- .../deepseek_v32/adapter/registration.py | 18 ++++++++++++ .../deepseek_v32/modeling_deepseek_v32.py | 28 ++----------------- .../models/deepseek_v32/recipes/train.yaml | 5 ++-- .../_test_deepseek_v32_parallel.py | 9 ++++-- 6 files changed, 36 insertions(+), 38 deletions(-) diff --git a/examples/training_demo/deepseek_v32/align_mindspeed.yaml b/examples/training_demo/deepseek_v32/align_mindspeed.yaml index 7170f78f59..63be47c5ec 100644 --- a/examples/training_demo/deepseek_v32/align_mindspeed.yaml +++ b/examples/training_demo/deepseek_v32/align_mindspeed.yaml @@ -15,7 +15,7 @@ # 拓扑与完整配方相同(512 卡,ep 64 × edp 8);并行方式不改变计算语义,可以按机器调整。 model: - _target_: hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.build_model + _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained # 官方 FP8 权重反量化后的 BF16 Hugging Face 目录,MindSpeed 侧转换同一份。 pretrained_model_name_or_path: /path/to/DeepSeek-V3.2-bf16 torch_dtype: bfloat16 diff --git a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py index 89349ad230..c94b27873d 100644 --- a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py +++ b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py @@ -20,7 +20,7 @@ from transformers import AutoConfig, PretrainedConfig, PreTrainedModel -from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import build_model +from hyper_parallel.models import HyperAutoModelForCausalLM # ``DeepseekV32Config.__post_init__`` derives these per-layer lists from the # layer count and ``first_k_dense_replace``. Copying the released 61-entry @@ -119,10 +119,10 @@ def build_cropped_deepseek_v32( n_routed_experts: Routed experts per MoE layer. num_nextn_predict_layers: MTP depth; 0 disables MTP. local_files_only: Disable implicit Hub downloads when true. - **build_kwargs: Model build options, both those set in YAML - (``torch_dtype``, ``attn_implementation``, ``validate_placement``, - training objectives) and those the Trainer injects - (``distributed_setup``, ``activation_checkpoint``, ...). + **build_kwargs: ``HyperAutoModelForCausalLM.from_config`` options, both + those set in YAML (``torch_dtype``, ``attn_implementation``, + ``validate_placement``, training objectives) and those the Trainer + injects (``distributed_setup``, ``activation_checkpoint``, ...). Returns: A parallelized, randomly initialized cropped DeepSeek-V3.2 model. @@ -135,4 +135,4 @@ def build_cropped_deepseek_v32( num_nextn_predict_layers=num_nextn_predict_layers, local_files_only=local_files_only, ) - return build_model(config=config, **build_kwargs) + return HyperAutoModelForCausalLM.from_config(config, **build_kwargs) diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index 9d39710187..cfef2f1770 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -63,6 +63,23 @@ def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: return () if getattr(model, "mtp", None) is None else ("mtp",) +def bind_training_parallel_groups(model: Any, context: Any) -> None: + """Bind the CP and TP groups of the training objectives once the model is sharded. + + The framework calls the external-state provider after planning with the run's + ``MeshContext``; DeepSeek-V3.2 owns no external state, so this returns None. + + Args: + model: Sharded model before FSDP. + context: ``ExternalBuildContext`` of the build. + """ + from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=C0415 + bind_parallel_groups, + ) + + bind_parallel_groups(model, context.mesh_context) + + register_custom_model( "DeepseekV32ForCausalLM", "hyper_parallel.models.deepseek_v32.modeling_deepseek_v32", @@ -75,6 +92,7 @@ def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: replacements=_load_replacements, materialization=register_rotary_materialization, context_parallel=_load_context_parallel, + external_state=bind_training_parallel_groups, sharding_rules=build_parameter_sharding_rules, fsdp_wrap_modules=get_fsdp_wrap_modules, fsdp_excluded_subtrees=get_fsdp_excluded_subtrees, diff --git a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py index 3886fa512e..075f8316ed 100644 --- a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py +++ b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py @@ -59,7 +59,6 @@ "DeepseekV32ForCausalLM", "DeepseekV32TrainingOutput", "bind_parallel_groups", - "build_model", ] @@ -88,7 +87,7 @@ def __init__(self, config: Any, *, aux_loss_coeff: float = 0.0, enable_expert_bi self.aux_loss_coeff = float(aux_loss_coeff) self.enable_expert_bias = bool(enable_expert_bias) self.expert_bias_update_rate = float(expert_bias_update_rate) - # Context-parallel group over which one sequence is split; bound by build_model. + # Context-parallel group over which one sequence is split; bound after sharding. self.sequence_partition_group = None # TP ranks that compute this same loss and whose gradients the Trainer sums. self.aux_loss_tp_replicas = 1 @@ -268,7 +267,7 @@ def __init__(self, config: Any, *, mtp_loss_scaling_factor: float = 0.3, for module in list(self.modules()): if isinstance(module, DeepseekV32MoE): module.gate = DeepseekV32Router.from_router(module.gate, config, **router_options) - # Context-parallel group of the trunk sequence; bound by build_model. + # Context-parallel group of the trunk sequence; bound after sharding. self.sequence_group = None self._pre_norm_capture: Optional[tuple[nn.Module, Any]] = None self._pre_norm_hidden: Optional[torch.Tensor] = None @@ -421,26 +420,3 @@ def bind_parallel_groups(model: nn.Module, mesh: Any) -> None: elif hasattr(module, "kl_head_group"): module.kl_head_group = tp_group module.kl_loss_tp_replicas = tp_replicas - - -def build_model(**options: Any) -> nn.Module: - """Build the DeepSeek-V3.2 training model and bind its parallel groups. - - Args: - **options: ``pretrained_model_name_or_path`` loads a checkpoint; otherwise - ``config`` builds from a configuration. The remaining options go to - ``HyperAutoModelForCausalLM`` and, for the training options of - :class:`DeepseekV32ForCausalLM`, to the model constructor. - - Returns: - The constructed and parallelized model. - """ - from hyper_parallel.models import HyperAutoModelForCausalLM # pylint: disable=C0415 - - pretrained = options.pop("pretrained_model_name_or_path", None) - if pretrained is not None: - model = HyperAutoModelForCausalLM.from_pretrained(pretrained, **options) - else: - model = HyperAutoModelForCausalLM.from_config(options.pop("config"), **options) - bind_parallel_groups(model, getattr(options.get("distributed_setup"), "mesh_context", None)) - return model diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index 090c625cf2..f50c9ad192 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -32,8 +32,9 @@ # examples/training_demo/deepseek_v32/align_mindspeed.yaml。 model: - # 训练模型:在 Transformers 的 DeepSeek-V3.2 上加 MTP、MoE 负载均衡和 DSA indexer 训练,并绑定并行通信组。 - _target_: hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.build_model + # DeepSeek-V3.2 注册了训练模型(MTP、MoE 负载均衡、DSA indexer 训练),框架入口直接构建它; + # 随机初始化可改用 from_config 并传入 config。 + _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained pretrained_model_name_or_path: deepseek-ai/DeepSeek-V3.2 torch_dtype: bfloat16 # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index 965fd17a72..5454b0786d 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -174,10 +174,10 @@ def _build_parallel_model(reference, config): from hyper_parallel.distributed.apply import apply_sharding_plan from hyper_parallel.models._transformers.model_builder import ( _apply_fsdp2_with_external, + _create_external_state, _maybe_apply_module_replacements, instantiate_infrastructure, ) - from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import bind_parallel_groups from hyper_parallel.trainer.config import normalize_distributed_setup_overrides from hyper_parallel.trainer.runtime.distributed import create_distributed_setup_from_config @@ -201,8 +201,11 @@ def _build_parallel_model(reference, config): sequence_parallel=False, loss_parallel=mesh.loss_parallel, ) model, source_shard_info = apply_sharding_plan(model, plan, mesh) - model = _apply_fsdp2_with_external(model, fsdp_manager, source_shard_info, None) - bind_parallel_groups(model, mesh) + # The adapter binds the CP/TP groups of the training objectives at this build stage. + external = _create_external_state( + model, mesh, source_shard_info, None, False, None, False, False, setup, fsdp_manager, + ) + model = _apply_fsdp2_with_external(model, fsdp_manager, source_shard_info, external) return model, mesh, source_shard_info or {} From b6460d2d50aac41944d8f7b43ac5c8c552573e3a Mon Sep 17 00:00:00 2001 From: hf1s Date: Tue, 10 Nov 2026 00:26:19 -0600 Subject: [PATCH 16/20] refactor(deepseek_v32): keep the indexer training options out of the 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. --- .../components/modules/dsa_attention.py | 85 ++------- .../adapter/conversion/dsa_attention.py | 166 ++++++++++++++++++ .../adapter/conversion/module_replacement.py | 9 +- .../adapter/distributed/context_parallel.py | 13 +- tests/common/dsa_reference_kernels.py | 1 + .../test_deepseek_v32_training_model.py | 13 +- 6 files changed, 201 insertions(+), 86 deletions(-) create mode 100644 hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py diff --git a/hyper_parallel/components/modules/dsa_attention.py b/hyper_parallel/components/modules/dsa_attention.py index a06b32c905..5b158ad016 100644 --- a/hyper_parallel/components/modules/dsa_attention.py +++ b/hyper_parallel/components/modules/dsa_attention.py @@ -17,7 +17,6 @@ from __future__ import annotations from collections.abc import Mapping, Sequence -from functools import lru_cache from typing import Any # This package provides PyTorch-specific high-performance modules. @@ -29,15 +28,14 @@ from hyper_parallel.components.checkpoint import ConcatenateWithSections from hyper_parallel.models.replacement import module_replacement -from hyper_parallel.components.functional import aux_loss_auto_scale +from hyper_parallel.components.functional import aggregate_hidden, aux_loss_auto_scale from hyper_parallel.components.functional import apply_rotary_pos_emb, apply_rotary_pos_emb_interleave -# Exports named like their submodule come from the submodule: once that submodule -# is imported, the package attribute of that name is the module, not the function. -from hyper_parallel.components.functional.aggregate_hidden import aggregate_hidden -from hyper_parallel.components.functional.dsa_indexer import dsa_indexer -from hyper_parallel.components.functional.dsa_kl_loss import dsa_kl_loss -from hyper_parallel.components.functional.dsa_sparse_attention import dsa_sparse_attention -from hyper_parallel.components.functional.dsa_sparse_attention_rescale import dsa_sparse_attention_rescale +from hyper_parallel.components.functional import ( + dsa_indexer, + dsa_kl_loss, + dsa_sparse_attention, + dsa_sparse_attention_rescale, +) from hyper_parallel.components.functional.npu_fusion_attention import resolve_packed_sequence_lengths @@ -98,7 +96,6 @@ def _deepseek_v32_dense_attention( key, value = projected_kv.split((module.qk_nope_head_dim, module.v_head_dim), dim=-1) key_rope = key_rope.expand(-1, -1, module.num_heads, -1) need_stats = bool(module.training and not module.freeze_dsa and module.dsa_loss_coeff) - module.last_indexer_loss = None output, maximum, total = _dense_flash_attention( module, torch.cat((query, query_rope), dim=-1), torch.cat((key, key_rope), dim=-1), value, sequence_lengths, need_stats=need_stats, @@ -117,20 +114,13 @@ def _deepseek_v32_dense_attention( indexer_stats = dsa_dense_indexer_lse( index_query, index_key, weights, query_lengths=query_lengths, key_lengths=key_lengths, ) - teacher = (query, key, query_rope, key_rope) - group = module._kl_head_group() # pylint: disable=protected-access - if group is not None: - teacher = tuple(_gather_heads(tensor.detach(), 2, group) for tensor in teacher) - maximum, total = (_gather_heads(tensor.detach(), 0, group) for tensor in (maximum, total)) - query, key, query_rope, key_rope = teacher loss = dsa_dense_indexer_kl_loss( index_query, index_key, weights, query.flatten(0, 1), key.flatten(0, 1), maximum, total, indexer_stats, scale=module.scaling, query_rope=query_rope.flatten(0, 1), key_rope=key_rope.flatten(0, 1), query_lengths=query_lengths, key_lengths=key_lengths, loss_coefficient=module.dsa_loss_coeff, ) - module.last_indexer_loss = loss.detach() - output = aux_loss_auto_scale(output, loss / module.kl_loss_tp_replicas) + output = aux_loss_auto_scale(output, loss) return output @@ -204,31 +194,6 @@ def _apply_index_rope( return torch.cat((query_rot, query_pass), dim=-1), torch.cat((key_rot, key_pass), dim=-1) -@lru_cache(maxsize=8) -def _hadamard_matrix(size: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: - """Return the Sylvester-ordered ``size`` x ``size`` Hadamard matrix.""" - matrix = torch.ones(1, 1, dtype=torch.float32) - while matrix.shape[0] < size: - matrix = torch.cat((torch.cat((matrix, matrix), dim=1), torch.cat((matrix, -matrix), dim=1)), dim=0) - return matrix.to(dtype=dtype, device=device) - - -def _rotate_activation(states: torch.Tensor) -> torch.Tensor: - """Apply the orthonormal Hadamard rotation over the last dimension.""" - size = states.shape[-1] - if size & (size - 1): - raise ValueError(f"Hadamard rotation requires a power-of-two width, got {size}") - matrix = _hadamard_matrix(size, states.dtype, states.device) - return F.linear(states, matrix) * size**-0.5 # pylint: disable=not-callable - - -def _gather_heads(tensor: torch.Tensor, dim: int, group: Any) -> torch.Tensor: - """Concatenate tensor-parallel head shards along ``dim`` in rank order.""" - shards = [torch.empty_like(tensor) for _ in range(torch.distributed.get_world_size(group))] - torch.distributed.all_gather(shards, tensor.contiguous(), group=group) - return torch.cat(shards, dim=dim) - - def _absorb_query_projection( query: torch.Tensor, key_up_weight: torch.Tensor, @@ -338,12 +303,6 @@ def _initialize_options(self, module: nn.Module) -> None: self.dsa_dense_warm_up = bool( getattr(module, "dsa_dense_warm_up", getattr(config, "dsa_dense_warm_up", False)) ) - self.index_rotate_activation = bool(getattr(config, "index_rotate_activation", False)) - # Group of the tensor-parallel attention-head shards, set by the model builder, - # and the TP ranks whose identical KL gradients the Trainer sums. - self.kl_head_group = None - self.kl_loss_tp_replicas = 1 - self.last_indexer_loss = None if getattr(module, "param_sink_number", 0) > 0: raise ValueError("DeepseekV32DSAAttention does not support the parameter-sink path") if getattr(module, "use_mome", False): @@ -549,22 +508,8 @@ def _project_index_states( index_head_dim=self.index_head_dim, interleaved=self.index_rotary_interleaved, ) - if self.index_rotate_activation: - index_query, index_key = _rotate_activation(index_query), _rotate_activation(index_key) return index_query, index_key, merge_weight - def _kl_head_group(self) -> Any: - """Return the group holding the other heads of the KL teacher when TP shards them.""" - full_heads = getattr(self, "_hp_full_head_counts", {}).get("num_heads") - if full_heads is None or full_heads == self.num_heads: - return None - if self.kl_head_group is None: - raise RuntimeError( - "Tensor parallelism shards the attention heads; the DSA indexer loss " - "needs kl_head_group set to the tensor-parallel group" - ) - return self.kl_head_group - def _apply_auxiliary_loss( self, attn_output: torch.Tensor, @@ -575,30 +520,20 @@ def _apply_auxiliary_loss( actual_q_len: torch.Tensor, actual_kv_len: torch.Tensor, ) -> torch.Tensor: - """Attach the DSA KL auxiliary loss when training enables it. - - The teacher sums the attention distribution over all heads, so heads - sharded by tensor parallelism are gathered first. - """ + """Attach the DSA KL auxiliary loss when training enables it.""" if not (self.training and not self.freeze_dsa and self.dsa_loss_coeff): - self.last_indexer_loss = None return attn_output query_tnd, key_tnd, q_rot_tnd, k_rot_tnd = ( tensor.reshape(-1, tensor.shape[2], tensor.shape[3]) for tensor in attention_states ) - group = self._kl_head_group() - if group is not None: - query_tnd, q_rot_tnd = (_gather_heads(tensor.detach(), 1, group) for tensor in (query_tnd, q_rot_tnd)) - softmax_stats = tuple(_gather_heads(tensor.detach(), -1, group) for tensor in softmax_stats) aux_loss = dsa_kl_loss( *index_states, query_tnd, key_tnd, topk_indices, *softmax_stats, q_rot_tnd, k_rot_tnd, actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff, backend="cann", ) - self.last_indexer_loss = aux_loss.detach() - return aux_loss_auto_scale(attn_output, aux_loss / self.kl_loss_tp_replicas) + return aux_loss_auto_scale(attn_output, aux_loss) def _prepare_attention_states(self, hidden_states, position_embeddings): """Project attention states and apply their rotary embeddings.""" diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py new file mode 100644 index 0000000000..432c0cd907 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py @@ -0,0 +1,166 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 DSA attention with the indexer training options. + +``DeepseekV32DSAAttention`` implements the released attention. The training +model adds, on the sparse path: + +* ``index_rotate_activation``: the orthonormal Hadamard rotation that + DeepSeek-V3.2 and MindSpeed-LLM apply to the indexer query and key after RoPE; +* the indexer KL teacher over all attention heads when tensor parallelism shards + them, with the loss divided by the TP ranks whose identical gradients loss + parallelism sums; +* ``last_indexer_loss``, the KL value of the latest forward, for logging. + +The dense warm-up path keeps the released behaviour; its indexer loss is not +logged and rejects tensor-parallel heads. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from functools import lru_cache +from typing import Any, Optional + +import torch # pylint: disable=forbidden-backend-import +import torch.distributed as dist # pylint: disable=forbidden-backend-import +from torch import nn # pylint: disable=forbidden-backend-import +from torch.nn import functional as F # pylint: disable=forbidden-backend-import + +from hyper_parallel.components.functional import aux_loss_auto_scale, dsa_kl_loss +from hyper_parallel.components.modules.dsa_attention import DeepseekV32DSAAttention + + +@lru_cache(maxsize=8) +def _hadamard_matrix(size: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: + """Return the Sylvester-ordered ``size`` x ``size`` Hadamard matrix.""" + matrix = torch.ones(1, 1, dtype=torch.float32) + while matrix.shape[0] < size: + matrix = torch.cat((torch.cat((matrix, matrix), dim=1), torch.cat((matrix, -matrix), dim=1)), dim=0) + return matrix.to(dtype=dtype, device=device) + + +def rotate_activation(states: torch.Tensor) -> torch.Tensor: + """Apply the orthonormal Hadamard rotation over the last dimension.""" + size = states.shape[-1] + if size & (size - 1): + raise ValueError(f"Hadamard rotation requires a power-of-two width, got {size}") + matrix = _hadamard_matrix(size, states.dtype, states.device) + return F.linear(states, matrix) * size**-0.5 # pylint: disable=not-callable + + +def _gather_heads(tensor: torch.Tensor, dim: int, group: Any) -> torch.Tensor: + """Concatenate tensor-parallel head shards along ``dim`` in rank order.""" + shards = [torch.empty_like(tensor) for _ in range(dist.get_world_size(group))] + dist.all_gather(shards, tensor.contiguous(), group=group) + return torch.cat(shards, dim=dim) + + +class DeepseekV32TrainingDSAAttention(DeepseekV32DSAAttention): + """``DeepseekV32DSAAttention`` with the indexer options of the training model.""" + + def __init__( + self, + *, + module: nn.Module, + module_fqn: str = "", + context: Mapping[str, Any] | None = None, + ) -> None: + """Build the released replacement, then read the indexer training options.""" + super().__init__(module=module, module_fqn=module_fqn, context=context) + self.index_rotate_activation = bool(getattr(self.config, "index_rotate_activation", False)) + # Group of the tensor-parallel attention-head shards and the TP ranks whose + # identical KL gradients the Trainer sums; both are bound after sharding. + self.kl_head_group = None + self.kl_loss_tp_replicas = 1 + self.last_indexer_loss: Optional[torch.Tensor] = None + + def _project_index_states( + self, + hidden_states: torch.Tensor, + q_resid: torch.Tensor, + position_embeddings: tuple[torch.Tensor, torch.Tensor] | None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Build the indexer states, rotating the query and key when enabled.""" + index_query, index_key, merge_weight = super()._project_index_states( + hidden_states, q_resid, position_embeddings, + ) + if self.index_rotate_activation: + index_query, index_key = rotate_activation(index_query), rotate_activation(index_key) + return index_query, index_key, merge_weight + + def _indexer_loss_enabled(self) -> bool: + """Return whether this forward trains the indexer.""" + return bool(self.training and not self.freeze_dsa and self.dsa_loss_coeff) + + def _kl_head_group(self) -> Any: + """Return the group holding the other heads of the KL teacher when TP shards them.""" + full_heads = getattr(self, "_hp_full_head_counts", {}).get("num_heads") + if full_heads is None or full_heads == self.num_heads: + return None + if self.kl_head_group is None: + raise RuntimeError( + "Tensor parallelism shards the attention heads; the DSA indexer loss " + "needs kl_head_group set to the tensor-parallel group" + ) + return self.kl_head_group + + def check_dense_indexer_loss(self) -> None: + """Prepare a dense warm-up forward, which neither logs nor gathers the KL teacher.""" + self.last_indexer_loss = None + if self._indexer_loss_enabled() and self._kl_head_group() is not None: + raise NotImplementedError( + "The dense warm-up indexer loss does not gather tensor-parallel attention heads" + ) + + def _compute_attention_output(self, hidden_states, position_embeddings, actual_seq_len, kwargs): + """Run the selected dense or sparse stage.""" + if self.dsa_dense_warm_up: + self.check_dense_indexer_loss() + return super()._compute_attention_output(hidden_states, position_embeddings, actual_seq_len, kwargs) + + def _apply_auxiliary_loss( + self, + attn_output: torch.Tensor, + index_states: tuple[torch.Tensor, torch.Tensor, torch.Tensor], + attention_states: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], + topk_indices: torch.Tensor, + softmax_stats: tuple[torch.Tensor, torch.Tensor], + actual_q_len: torch.Tensor, + actual_kv_len: torch.Tensor, + ) -> torch.Tensor: + """Attach the DSA KL auxiliary loss against the attention of all heads.""" + if not self._indexer_loss_enabled(): + self.last_indexer_loss = None + return attn_output + query_tnd, key_tnd, q_rot_tnd, k_rot_tnd = ( + tensor.reshape(-1, tensor.shape[2], tensor.shape[3]) + for tensor in attention_states + ) + group = self._kl_head_group() + if group is not None: + query_tnd, q_rot_tnd = (_gather_heads(tensor.detach(), 1, group) for tensor in (query_tnd, q_rot_tnd)) + softmax_stats = tuple(_gather_heads(tensor.detach(), -1, group) for tensor in softmax_stats) + aux_loss = dsa_kl_loss( # pylint: disable=not-callable + *index_states, query_tnd, key_tnd, + topk_indices, *softmax_stats, q_rot_tnd, k_rot_tnd, + actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff, + backend="cann", + ) + self.last_indexer_loss = aux_loss.detach() + return aux_loss_auto_scale(attn_output, aux_loss / self.kl_loss_tp_replicas) + + +__all__ = ["DeepseekV32TrainingDSAAttention", "rotate_activation"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py index c24a926ef4..3e4772d728 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py @@ -42,10 +42,13 @@ def replace_deepseek_v32_dsa_attention( module_fqn: str, context: Mapping[str, Any], ) -> nn.Module: - """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module.""" - from hyper_parallel.components.modules import DeepseekV32DSAAttention # pylint: disable=C0415 + """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module and its indexer training options.""" + # pylint: disable=import-outside-toplevel + from hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention import ( + DeepseekV32TrainingDSAAttention, + ) - return DeepseekV32DSAAttention(module=module, module_fqn=module_fqn, context=context) + return DeepseekV32TrainingDSAAttention(module=module, module_fqn=module_fqn, context=context) @module_replacement diff --git a/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py b/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py index c057a04a47..6f76f395a9 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py +++ b/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py @@ -32,8 +32,10 @@ import torch from torch import nn -from hyper_parallel.components.functional.dsa_indexer import dsa_indexer -from hyper_parallel.components.functional.dsa_sparse_attention import dsa_sparse_attention +# The package exports these functions lazily under the names of their submodules; +# importing a submodule directly would leave the module object under that name for +# DeepseekV32DSAAttention, which imports the function from the package. +from hyper_parallel.components.functional import dsa_indexer, dsa_sparse_attention from hyper_parallel.components.functional.npu_fusion_attention import ( resolve_packed_sequence_lengths, ) @@ -213,9 +215,12 @@ def _run_cp_dsa_kernels( absorbed_query, kv_nope, q_rot, k_rot = attention_states actual_q_len, actual_kv_len = sequence_lengths if use_dense: + check_dense_indexer_loss = getattr(module, "check_dense_indexer_loss", None) + if check_dense_indexer_loss is not None: + check_dense_indexer_loss() return _deepseek_v32_dense_attention(module, index_states, attention_states, sequence_lengths) - topk_indices, index_query_tnd, index_key_tnd, merge_weight_tnd = dsa_indexer( + topk_indices, index_query_tnd, index_key_tnd, merge_weight_tnd = dsa_indexer( # pylint: disable=not-callable index_query, index_key, merge_weight, @@ -224,7 +229,7 @@ def _run_cp_dsa_kernels( module.index_topk, backend="cann", ) - attn_output, softmax_max, softmax_sum = dsa_sparse_attention( + attn_output, softmax_max, softmax_sum = dsa_sparse_attention( # pylint: disable=not-callable absorbed_query, kv_nope, q_rot, diff --git a/tests/common/dsa_reference_kernels.py b/tests/common/dsa_reference_kernels.py index d42cbc6c4c..7363660713 100644 --- a/tests/common/dsa_reference_kernels.py +++ b/tests/common/dsa_reference_kernels.py @@ -39,6 +39,7 @@ _STUB_MODULES = ("torch_npu", "omni_training_custom_ops", "cann_ops_transformer", "cann_ops_transformer.ops") _DSA_MODULES = ( "hyper_parallel.components.modules.dsa_attention", + "hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention", "hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel", ) # Lazy export packages cache resolved symbols in their globals. diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py index 3dd927b31d..1357c57559 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py @@ -237,12 +237,15 @@ def test_hadamard_rotation_preserves_scores(self): """ with reference_dsa_kernels(): # pylint: disable=import-outside-toplevel,protected-access - from hyper_parallel.components.modules.dsa_attention import _hadamard_matrix, _rotate_activation + from hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention import ( + _hadamard_matrix, + rotate_activation, + ) matrix = _hadamard_matrix(16, torch.float64, torch.device("cpu")) torch.testing.assert_close(matrix @ matrix.T, 16 * torch.eye(16, dtype=torch.float64)) query, key = torch.randn(5, 3, 16, dtype=torch.float64), torch.randn(7, 16, dtype=torch.float64) - torch.testing.assert_close(_rotate_activation(query) @ _rotate_activation(key).T, query @ key.T) + torch.testing.assert_close(rotate_activation(query) @ rotate_activation(key).T, query @ key.T) @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", card_mark="allcards", essential_mark="essential") @@ -255,9 +258,11 @@ def test_kl_teacher_requires_head_group_under_tensor_parallelism(self): """ with reference_dsa_kernels(): # pylint: disable=import-outside-toplevel,protected-access - from hyper_parallel.components.modules.dsa_attention import DeepseekV32DSAAttention + from hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention import ( + DeepseekV32TrainingDSAAttention, + ) - resolve = DeepseekV32DSAAttention._kl_head_group + resolve = DeepseekV32TrainingDSAAttention._kl_head_group self.assertIsNone(resolve(SimpleNamespace(num_heads=4, kl_head_group=None))) sharded = SimpleNamespace(num_heads=2, kl_head_group=None, _hp_full_head_counts={"num_heads": 4}) with self.assertRaises(RuntimeError): From 4db1f9a5527608c9115b1d066596475f474a9e97 Mon Sep 17 00:00:00 2001 From: hf1s Date: Tue, 10 Nov 2026 00:48:58 -0600 Subject: [PATCH 17/20] refactor(deepseek_v32): drop the custom model and train through adapter 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. --- docs/feature_status.md | 2 +- examples/training_demo/README.md | 89 ++-- .../deepseek_v32/cropped_deepseek_v32.py | 138 ------ .../deepseek_v32/prepare_single_card_data.py | 90 ---- .../deepseek_v32/run_single_card.sh | 36 +- .../deepseek_v32/train_single_card.yaml | 48 +- .../adapter/conversion/checkpoint_mapping.py | 79 ---- .../adapter/conversion/dsa_attention.py | 166 ------- .../adapter/conversion/module_replacement.py | 49 +- .../adapter/distributed/context_parallel.py | 3 - .../deepseek_v32/adapter/registration.py | 53 +-- .../models/deepseek_v32/adapter/router.py | 198 ++++++++ .../deepseek_v32/modeling_deepseek_v32.py | 422 ------------------ .../recipes}/align_mindspeed.yaml | 38 +- .../models/deepseek_v32/recipes/train.yaml | 52 +-- tests/common/dsa_reference_kernels.py | 1 - .../_test_deepseek_v32_parallel.py | 74 +-- .../deepseek_v32/test_cropped_deepseek_v32.py | 93 ---- .../test_deepseek_v32_adapter_contracts.py | 7 +- .../deepseek_v32/test_deepseek_v32_router.py | 123 +++++ .../test_deepseek_v32_training_model.py | 275 ------------ 21 files changed, 533 insertions(+), 1503 deletions(-) delete mode 100644 examples/training_demo/deepseek_v32/cropped_deepseek_v32.py delete mode 100644 examples/training_demo/deepseek_v32/prepare_single_card_data.py delete mode 100644 hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py delete mode 100644 hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py create mode 100644 hyper_parallel/models/deepseek_v32/adapter/router.py delete mode 100644 hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py rename {examples/training_demo/deepseek_v32 => hyper_parallel/models/deepseek_v32/recipes}/align_mindspeed.yaml (87%) delete mode 100644 tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py create mode 100644 tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py delete mode 100644 tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py diff --git a/docs/feature_status.md b/docs/feature_status.md index e64af27303..e7d480d2be 100644 --- a/docs/feature_status.md +++ b/docs/feature_status.md @@ -5,7 +5,7 @@ ## 支持模型 - [x] Qwen3-30B-A3B -- [x] DeepSeek-V3.2(DSA + MoE + MTP,含 indexer KL、序列级负载均衡 loss 与专家 bias 更新;TP/CP/EP/FSDP 在 CPU/Gloo 上与单卡结果对齐,NPU 端到端未验证) +- [x] DeepSeek-V3.2(DSA + MoE,含 indexer KL、序列级负载均衡 loss 与专家 bias 更新;TP/CP/EP/FSDP 在 CPU/Gloo 上与单卡结果对齐,NPU 端到端未验证) ## HyperShard diff --git a/examples/training_demo/README.md b/examples/training_demo/README.md index 5d837c6c43..c3e2a1bb1a 100644 --- a/examples/training_demo/README.md +++ b/examples/training_demo/README.md @@ -116,18 +116,19 @@ overrides may be appended to either command. ## DeepSeek-V3.2 single-card crop -The [single-card configuration](deepseek_v32/train_single_card.yaml) builds the -DeepSeek-V3.2 training model with random weights. It keeps the released hidden, -MLA, indexer, and vocabulary dimensions and crops the model to two decoder -layers (one dense, one MoE) and 16 routed experts, the fewest that keep the -released group routing (`n_group=8`, `topk_group=4`, top-8). The model has 3.40B -parameters; FP32 parameters, FP32 gradients and the two FP32 AdamW moments take -about 51 GiB before activations (estimated, not measured), which targets one -64 GB device such as 910B3. The MTP depth would add about 1B parameters, so the -example disables it with `num_nextn_predict_layers: 0`; the balance loss, the -expert-bias update and the indexer KL loss stay on as in the full recipe. - -Module replacements match the full +The [single-card configuration](deepseek_v32/train_single_card.yaml) builds +DeepSeek-V3.2 with `HyperAutoModelForCausalLM.from_config` and random weights. +It keeps the released hidden, MLA, indexer, and vocabulary dimensions and crops +the model to two decoder layers (one dense, one MoE) and 16 routed experts, the +fewest that keep the released group routing (`n_group=8`, `topk_group=4`, +top-8). The per-layer type lists are given with the layer count because +Transformers derives them from the released 61 layers before the override. The +model has 3.40B parameters; FP32 parameters, FP32 gradients and the two FP32 +AdamW moments take about 51 GiB before activations (estimated, not measured), +which targets one 64 GB device such as 910B3. + +Module replacements, the training router (sequence-wise balance loss and +expert-bias update) and the indexer KL weight match the full [recipe](../../hyper_parallel/models/deepseek_v32/recipes/train.yaml). Unlike its one-line-per-row default data, this example packs documents into 4096-token rows, and DSA reads their boundaries from `DeepseekV32PackedSequence` rather than a @@ -135,35 +136,32 @@ dense mask. DSA runs on the CANN backend, so load the CANN and ops-transformer environment described in the [functional README](../../hyper_parallel/components/functional/README.md#deepseek-v32-dsa) before launching. Only `config.json` and the tokenizer files of the official -checkpoint directory are read: +checkpoint directory are read; the data is a text JSONL with a `text` field: ```bash -bash examples/training_demo/deepseek_v32/run_single_card.sh /path/to/DeepSeek-V3.2 - -# Supply an existing text JSONL instead of the generated data. bash examples/training_demo/deepseek_v32/run_single_card.sh \ /path/to/DeepSeek-V3.2 /path/to/text/train.jsonl ``` -Without a dataset argument the launcher writes -`output/training_demo/deepseek_v32/single_card.jsonl`. Each generated record -tokenizes into two full 4096-token windows and a short tail: a full window is a -single document longer than `index_topk=2048`, so the indexer's top-k selection -is active, and tails from several records pack into one row to exercise the -document boundaries. The Online dataset holds `train_iters × global_batch_size` -records, so a JSONL whose records are much shorter than 4096 tokens packs -several records into each step and can run out before `train_iters`. The log is -written to `output/training_demo/deepseek_v32/run_single_card.log`. +The indexer keeps every key of a document shorter than `index_topk` (2048), so +its top-k selection only takes effect on longer documents. The Online dataset +holds `train_iters × global_batch_size` records, so a JSONL whose records are +much shorter than 4096 tokens packs several records into each step and can run +out before `train_iters`. The log is written to +`output/training_demo/deepseek_v32/run_single_card.log`. ## DeepSeek-V3.2 loss comparison with MindSpeed-LLM -[`align_mindspeed.yaml`](deepseek_v32/align_mindspeed.yaml) trains the same -objectives as MindSpeed-LLM `examples/mcore/deepseek32/pretrain_deepseek32_671b_4k_A3_ptd.sh`: -indexer top-k 1024 with KL weight 1.0 and the Hadamard rotation, the -sequence-wise balance loss (1e-4), the expert-bias update (1e-3 per step), one -MTP depth weighted 0.3, AdamW at 1e-5 with cosine decay to 1e-7 and no warmup, -and FP32 RMSNorm weights. Both sides must start from the same weights and read -the same samples: +[`align_mindspeed.yaml`](../../hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml) +trains the same objectives as MindSpeed-LLM +`examples/mcore/deepseek32/pretrain_deepseek32_671b_4k_A3_ptd.sh` except MTP: +indexer top-k 1024 with KL weight 1.0, the sequence-wise balance loss (1e-4), +the expert-bias update (1e-3 per step), AdamW at 1e-5 with cosine decay to 1e-7 +and no warmup, and FP32 RMSNorm weights. Remove `--mtp-num-layers` and +`--mtp-loss-scaling-factor` from the MindSpeed script. MindSpeed rotates the +indexer query and key with a Hadamard matrix before scoring; the rotation is +orthogonal, so the scores differ only by BF16 rounding. Both sides must start +from the same weights and read the same samples: 1. Dequantize the released FP8 checkpoint to BF16 once (for example with DeepSeek's `inference/fp8_cast_bf16.py`). HyperParallel loads this directory; @@ -171,8 +169,8 @@ the same samples: converter does not dequantize FP8. Convert to the training script's layout (`--target-tensor-parallel-size 4 --target-pipeline-parallel-size 8 --target-expert-parallel-size 64 --num-layers-per-virtual-pipeline-stage 2 - --noop-layers 7,62,63 --mtp-num-layers 1`); the shipped conversion script - uses TP 1 and `--noop-layers 61,62,63`, which do not match it. + --noop-layers 7,62,63`); the shipped conversion script uses TP 1 and + `--noop-layers 61,62,63`, which do not match it. 2. Build the Megatron `.bin/.idx` dataset with MindSpeed's `data_convert_deepseek32_pretrain.sh` and point both sides at its prefix. Both sides derive the document, sample and shuffle indices from the seed @@ -180,29 +178,26 @@ the same samples: and the sample count (`--train-iters` × `--global-batch-size`), so keep them equal; compare the first step's `lm loss` before a long run. Neither side isolates documents inside a 4096-token window. -3. Keep MindSpeed's model and optimizer flags from its script and enable its - deterministic mode (`--npu-deterministic` and `HCCL_DETERMINISTIC=true`); +3. Keep MindSpeed's other model and optimizer flags from its script and enable + its deterministic mode (`--npu-deterministic` and `HCCL_DETERMINISTIC=true`); `enable_full_determinism` does the same on the HyperParallel side. Launch it like the full recipe, on every node with its torchrun arguments: ```bash -scripts/train_lm.py examples/training_demo/deepseek_v32/align_mindspeed.yaml \ +scripts/train_lm.py hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml \ --model.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2-bf16 \ --dataset.model_assets.tokenizer.pretrained_model_name_or_path=/path/to/DeepSeek-V3.2-bf16 \ --dataset.data_path=/path/to/dataset/deepseek32_text_document ``` -| MindSpeed-LLM log | HyperParallel log | Definition differences | -| --- | --- | --- | -| `lm loss` | `foundation_loss` | None. | -| `mtp_1 loss` | `mtp_1_loss` | HyperParallel sums the step's micro-batches; divide by the gradient-accumulation count. | -| `dsa_indexer_loss` | `dsa_indexer_loss` | MindSpeed divides the layer sum by `--num-layers`, which includes no-op layers (64 for 61 layers in its script); HyperParallel averages the 61 trunk layers and sums micro-batches. | -| `load_balancing_loss` | `router_aux_loss` | HyperParallel also averages the MTP router. | - -The DSA-internal norms (`q_a_layernorm`, `kv_a_layernorm` and the indexer -`k_norm`) run with BF16 weights on the HyperParallel side, so the two runs -differ by BF16 rounding there. +Compare MindSpeed's `lm loss` with HyperParallel's `foundation_loss`. +MindSpeed's `load_balancing_loss` and HyperParallel's `router_aux_loss` are both +one data-parallel replica's balance loss averaged over micro-batches and MoE +layers, so they are noisier than the language-model loss. HyperParallel does not +log the indexer KL loss. The DSA-internal norms (`q_a_layernorm`, +`kv_a_layernorm` and the indexer `k_norm`) run with BF16 weights on the +HyperParallel side, so the two runs differ by BF16 rounding there. ## DeepSeek-V4.1 text pretraining diff --git a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py b/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py deleted file mode 100644 index c94b27873d..0000000000 --- a/examples/training_demo/deepseek_v32/cropped_deepseek_v32.py +++ /dev/null @@ -1,138 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""Build a depth- and expert-cropped DeepSeek-V3.2 model from configuration only.""" - -from __future__ import annotations - -from typing import Any - -from transformers import AutoConfig, PretrainedConfig, PreTrainedModel - -from hyper_parallel.models import HyperAutoModelForCausalLM - -# ``DeepseekV32Config.__post_init__`` derives these per-layer lists from the -# layer count and ``first_k_dense_replace``. Copying the released 61-entry -# lists into a cropped config would keep the released dense/MoE pattern, so -# they are re-derived instead. -_LAYER_DERIVED_FIELDS = ("mlp_layer_types", "layer_types") - - -def build_cropped_deepseek_v32_config( - config_path: str, - *, - num_hidden_layers: int, - first_k_dense_replace: int, - n_routed_experts: int, - num_nextn_predict_layers: int = 0, - local_files_only: bool = True, -) -> PretrainedConfig: - """Return the released DeepSeek-V3.2 configuration cropped in depth and experts. - - Hidden, MLA, indexer and vocabulary dimensions stay as released. The FP8 - ``quantization_config`` describes the released checkpoint storage rather - than this randomly initialized model, so it is dropped. - - Args: - config_path: Hugging Face DeepSeek-V3.2 directory or repository id. - num_hidden_layers: Decoder layers retained in the cropped model. - first_k_dense_replace: Leading layers that keep the dense MLP; the - remaining layers use the MoE block. - n_routed_experts: Routed experts per MoE layer. The released group - routing scores each of ``n_group`` groups by its top-2 experts and - keeps ``topk_group`` groups, so every group needs two experts and - the kept groups must hold ``num_experts_per_tok`` experts. - num_nextn_predict_layers: MTP depth; 0 disables MTP. - local_files_only: Disable implicit Hub downloads when true. - - Returns: - The cropped configuration with ``use_cache`` disabled. - """ - released = AutoConfig.from_pretrained( - config_path, - local_files_only=local_files_only, - trust_remote_code=False, - ) - if getattr(released, "model_type", None) != "deepseek_v32": - raise ValueError( - "config_path must contain a DeepSeek-V3.2 configuration; " - f"got model_type={getattr(released, 'model_type', None)!r}" - ) - if num_hidden_layers <= 0 or not 0 <= first_k_dense_replace <= num_hidden_layers: - raise ValueError( - "need num_hidden_layers > 0 and 0 <= first_k_dense_replace <= num_hidden_layers; " - f"got num_hidden_layers={num_hidden_layers}, first_k_dense_replace={first_k_dense_replace}" - ) - experts_per_group, remainder = divmod(n_routed_experts, released.n_group) - if remainder or experts_per_group < 2 or experts_per_group * released.topk_group < released.num_experts_per_tok: - raise ValueError( - f"n_routed_experts={n_routed_experts} cannot keep the released routing " - f"(n_group={released.n_group}, topk_group={released.topk_group}, " - f"num_experts_per_tok={released.num_experts_per_tok}): it must be a multiple of n_group " - "with at least two experts per group, and topk_group groups must hold num_experts_per_tok experts" - ) - - values = released.to_dict() - for name in (*_LAYER_DERIVED_FIELDS, "quantization_config"): - values.pop(name, None) - values.update( - num_hidden_layers=num_hidden_layers, - first_k_dense_replace=first_k_dense_replace, - n_routed_experts=n_routed_experts, - num_nextn_predict_layers=num_nextn_predict_layers, - use_cache=False, - ) - return type(released).from_dict(values) - - -def build_cropped_deepseek_v32( - config_path: str, - *, - num_hidden_layers: int = 2, - first_k_dense_replace: int = 1, - n_routed_experts: int = 16, - num_nextn_predict_layers: int = 0, - local_files_only: bool = True, - **build_kwargs: Any, -) -> PreTrainedModel: - """Create a randomly initialized cropped DeepSeek-V3.2 model. - - The function calls ``from_config`` instead of ``from_pretrained``: it - reads only the Hugging Face configuration from ``config_path`` and loads - no checkpoint tensor. - - Args: - config_path: Local Hugging Face DeepSeek-V3.2 directory. - num_hidden_layers: Decoder layers retained in the cropped model. - first_k_dense_replace: Leading dense-MLP layers. - n_routed_experts: Routed experts per MoE layer. - num_nextn_predict_layers: MTP depth; 0 disables MTP. - local_files_only: Disable implicit Hub downloads when true. - **build_kwargs: ``HyperAutoModelForCausalLM.from_config`` options, both - those set in YAML (``torch_dtype``, ``attn_implementation``, - ``validate_placement``, training objectives) and those the Trainer - injects (``distributed_setup``, ``activation_checkpoint``, ...). - - Returns: - A parallelized, randomly initialized cropped DeepSeek-V3.2 model. - """ - config = build_cropped_deepseek_v32_config( - config_path, - num_hidden_layers=num_hidden_layers, - first_k_dense_replace=first_k_dense_replace, - n_routed_experts=n_routed_experts, - num_nextn_predict_layers=num_nextn_predict_layers, - local_files_only=local_files_only, - ) - return HyperAutoModelForCausalLM.from_config(config, **build_kwargs) diff --git a/examples/training_demo/deepseek_v32/prepare_single_card_data.py b/examples/training_demo/deepseek_v32/prepare_single_card_data.py deleted file mode 100644 index 7dcc372d60..0000000000 --- a/examples/training_demo/deepseek_v32/prepare_single_card_data.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""Generate deterministic documents for the DeepSeek-V3.2 single-card demo.""" - -from __future__ import annotations - -import argparse -import json -import math -from pathlib import Path -from typing import Sequence - -from transformers import AutoTokenizer - - -def prepare_single_card_data( - output_path: Path, - tokenizer_path: str, - *, - num_samples: int = 64, - sequence_length: int = 4096, -) -> None: - """Write JSONL records that reach both DSA attention patterns. - - Each record tokenizes to about ``2 * sequence_length + sequence_length // 4`` - tokens, which the Online transform cuts into two full windows and a short - tail. A full window is a single document longer than ``index_topk`` (2048 - in the released config), so the indexer's top-k selection is active; the - tails of several records pack into one row and exercise the per-document - boundaries. - - Args: - output_path: JSONL file to create. - tokenizer_path: Local DeepSeek-V3.2 tokenizer directory used to size records. - num_samples: Number of records. - sequence_length: Model sequence length (``data_transform.max_seq_len``). - """ - if num_samples <= 0 or sequence_length <= 0: - raise ValueError("num_samples and sequence_length must be positive") - tokenizer = AutoTokenizer.from_pretrained(tokenizer_path, local_files_only=True, trust_remote_code=False) - target_tokens = 2 * sequence_length + sequence_length // 4 - output_path.parent.mkdir(parents=True, exist_ok=True) - with output_path.open("w", encoding="utf-8") as output_file: - for sample_index in range(num_samples): - sentence = ( - f"DeepSeek-V3.2 single-card document {sample_index}: the lightning indexer scores " - "earlier tokens and sparse attention keeps the strongest candidates. " - ) - first = len(tokenizer.encode(sentence, add_special_tokens=False)) - # Repeated sentences merge at their boundary; measure the steady-state length. - repeated = len(tokenizer.encode(sentence * 2, add_special_tokens=False)) - first - repeats = 1 + math.ceil((target_tokens - first) / repeated) - output_file.write(json.dumps({"text": sentence * repeats}) + "\n") - - -def _parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: - """Parse command-line arguments.""" - parser = argparse.ArgumentParser(description="Prepare DeepSeek-V3.2 single-card demo data") - parser.add_argument("--output", required=True) - parser.add_argument("--tokenizer-path", required=True) - parser.add_argument("--num-samples", type=int, default=64) - parser.add_argument("--sequence-length", type=int, default=4096) - return parser.parse_args(argv) - - -def main(argv: Sequence[str] | None = None) -> None: - """Generate the requested JSONL dataset.""" - args = _parse_args(argv) - prepare_single_card_data( - Path(args.output).expanduser().resolve(), - args.tokenizer_path, - num_samples=args.num_samples, - sequence_length=args.sequence_length, - ) - - -if __name__ == "__main__": - main() diff --git a/examples/training_demo/deepseek_v32/run_single_card.sh b/examples/training_demo/deepseek_v32/run_single_card.sh index 455c8e8fef..2c42aef518 100755 --- a/examples/training_demo/deepseek_v32/run_single_card.sh +++ b/examples/training_demo/deepseek_v32/run_single_card.sh @@ -16,34 +16,27 @@ set -euo pipefail -# Keep generated data and run outputs under the repository output directory. SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) PROJECT_ROOT=$(cd "${SCRIPT_DIR}/../../.." && pwd) OUTPUT_DIR=${OUTPUT_DIR:-"${PROJECT_ROOT}/output/training_demo/deepseek_v32"} -DEFAULT_DATA_PATH="${OUTPUT_DIR}/single_card.jsonl" PYTHON_BIN=${PYTHON_BIN:-python} -if [[ $# -lt 1 ]]; then - echo "Usage: $0 /path/to/DeepSeek-V3.2 [path/to/train.jsonl] [trainer overrides...]" >&2 +if [[ $# -lt 2 ]]; then + echo "Usage: $0 /path/to/DeepSeek-V3.2 /path/to/train.jsonl [trainer overrides...]" >&2 exit 1 fi # Resolve input paths before switching to the repository root. -MODEL_PATH=$1 -shift -DATA_PATH="${DEFAULT_DATA_PATH}" -if [[ $# -gt 0 && ${1} != --* ]]; then - DATA_PATH=$1 - if [[ ! -s "${DATA_PATH}" ]]; then - echo "Text JSONL data is missing or empty: ${DATA_PATH}" >&2 - exit 1 - fi - shift -fi -MODEL_PATH=$(cd "${MODEL_PATH}" 2>/dev/null && pwd) || { - echo "Model directory does not exist: ${MODEL_PATH}" >&2 +MODEL_PATH=$(cd "$1" 2>/dev/null && pwd) || { + echo "Model directory does not exist: $1" >&2 exit 1 } +DATA_PATH=$2 +shift 2 +if [[ ! -s "${DATA_PATH}" ]]; then + echo "Text JSONL data is missing or empty: ${DATA_PATH}" >&2 + exit 1 +fi if [[ "${DATA_PATH}" != /* ]]; then DATA_PATH="${PWD}/${DATA_PATH}" fi @@ -54,20 +47,13 @@ fi cd "${PROJECT_ROOT}" mkdir -p "${OUTPUT_DIR}" -# Generate deterministic text samples when the default dataset is absent. -if [[ ! -s "${DATA_PATH}" ]]; then - "${PYTHON_BIN}" -m examples.training_demo.deepseek_v32.prepare_single_card_data \ - --output "${DATA_PATH}" \ - --tokenizer-path "${MODEL_PATH}" -fi - # Launch with the YAML settings; trailing Trainer arguments override its defaults. "${PYTHON_BIN}" -m torch.distributed.run \ --standalone \ --nproc_per_node=1 \ --module examples.training_demo.train_text \ "${SCRIPT_DIR}/train_single_card.yaml" \ - --model.config_path="${MODEL_PATH}" \ + --model.config.pretrained_model_name_or_path="${MODEL_PATH}" \ --dataset.model_assets.tokenizer.pretrained_model_name_or_path="${MODEL_PATH}" \ --dataset.data_path="${DATA_PATH}" \ --checkpoint.checkpoint_dir="${OUTPUT_DIR}/checkpoints" \ diff --git a/examples/training_demo/deepseek_v32/train_single_card.yaml b/examples/training_demo/deepseek_v32/train_single_card.yaml index 66694c13f1..cf94df4672 100644 --- a/examples/training_demo/deepseek_v32/train_single_card.yaml +++ b/examples/training_demo/deepseek_v32/train_single_card.yaml @@ -9,28 +9,25 @@ # TokenBatchLoader 把多个文档拼成 4096 token 的行,文档边界由 DeepseekV32PackedSequence # 传给 DSA。单卡没有 TP/CP/EP,所以不带 `when: cp` / `when: ep` 条目。 # -# 启动(只需要官方目录里的 config.json 和 tokenizer 文件,不需要权重): -# bash examples/training_demo/deepseek_v32/run_single_card.sh /path/to/DeepSeek-V3.2 +# 启动(只读取官方目录里的 config.json 和 tokenizer 文件,不需要权重): +# bash examples/training_demo/deepseek_v32/run_single_card.sh /path/to/DeepSeek-V3.2 /path/to/train.jsonl model: - _target_: examples.training_demo.deepseek_v32.cropped_deepseek_v32.build_cropped_deepseek_v32 - config_path: /path/to/DeepSeek-V3.2 - num_hidden_layers: 2 - first_k_dense_replace: 1 - n_routed_experts: 16 - # MTP 层(DSA + 16 专家 MoE + 融合投影)再加约 1B 参数,单卡显存放不下,这里关闭。 - num_nextn_predict_layers: 0 - local_files_only: true + _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_config + config: + _target_: transformers.AutoConfig.from_pretrained + pretrained_model_name_or_path: /path/to/DeepSeek-V3.2 + local_files_only: true + num_hidden_layers: 2 + first_k_dense_replace: 1 + n_routed_experts: 16 + # Transformers 按读入时的 61 层推导逐层类型,覆盖层数后不会重新推导,因此一并给出。 + mlp_layer_types: [dense, sparse] + layer_types: [indexed_attention, indexed_attention] torch_dtype: bfloat16 # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 attn_implementation: sdpa validate_placement: false - # 训练目标与完整配方相同:序列级负载均衡 loss、专家 bias 更新、indexer KL loss。 - moe_aux_loss_coeff: 1.0e-4 - moe_router_enable_expert_bias: true - moe_router_bias_update_rate: 1.0e-3 - dsa_loss_coeff: 1.0 - index_rotate_activation: true model_init_dtype: float32 @@ -86,6 +83,16 @@ plan_overrides: implementation: _target_: >- hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + dsa_loss_coeff: 1.0 + - match: "*.mlp.gate" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_router + aux_loss_coeff: 1.0e-4 + enable_expert_bias: true + expert_bias_update_rate: 1.0e-3 - match: "*.mlp.experts" replace: kind: module @@ -116,9 +123,8 @@ dataset: text_keys: text max_seq_len: 4096 _target_: hyper_parallel.data.text.build_dataset.build_online_text_mapping_dataset - # run_single_card.sh 缺省时用 prepare_single_card_data.py 生成:每条记录切成两个完整 - # 4096 窗口(单文档,超过 index_topk=2048,走稀疏选择)和一个短尾巴(多条尾巴拼成一行)。 - data_path: ./output/training_demo/deepseek_v32/single_card.jsonl + # 由 run_single_card.sh 的第二个参数传入:每行一个 JSON,正文在 text 字段。 + data_path: /path/to/train.jsonl data_config: labels_are_shifted: true create_ltor_fields_in_dataloader: false @@ -160,8 +166,8 @@ lr_scheduler: lr_decay_style: cosine lr_config: lr: 1.0e-5 - lr_warmup_steps: 0 - min_lr: 1.0e-7 + lr_warmup_steps: 1 + min_lr: 0.0 checkpoint: save_ckpt: false diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py deleted file mode 100644 index 337d86ad73..0000000000 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/checkpoint_mapping.py +++ /dev/null @@ -1,79 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""Checkpoint key mapping for the DeepSeek-V3.2 training model.""" - -from __future__ import annotations - -from typing import Any - - -def build_training_checkpoint_mapping(mtp_first_layer: int, mtp_depth: int) -> list[Any]: - """Return the Transformers DeepSeek-V3.2 mapping plus the MTP layer renames. - - The released checkpoint stores MTP depth ``d`` as layer ``mtp_first_layer + d``: - the fusion norms and projection, the shared-head norm and an ordinary decoder - layer. Its embedding and head copies stay unmapped because the training model - shares the trunk's. - - Args: - mtp_first_layer: Checkpoint layer index of the first MTP depth. - mtp_depth: Number of MTP depths; 0 adds no renames. - - Returns: - Weight renames followed by the expert merge operations. - """ - try: - # Family registration stays importable without Transformers installed. - # pylint: disable=import-outside-toplevel - from transformers.conversion_mapping import get_checkpoint_conversion_mapping - from transformers.core_model_loading import WeightRenaming - except ImportError: - return [] - - mapping = [] - for depth in range(mtp_depth): - source = rf"^model\.layers\.{mtp_first_layer + depth}\." - target = f"mtp.layers.{depth}." - mapping.extend([ - WeightRenaming(source + r"(enorm|hnorm|eh_proj)\.", target + r"\1."), - WeightRenaming(source + r"shared_head\.norm\.", target + "post_norm."), - WeightRenaming(source + r"(self_attn|mlp|input_layernorm|post_attention_layernorm)\.", - target + r"mtp_block.\1."), - ]) - mapping.extend(get_checkpoint_conversion_mapping("deepseek_v32") or []) - return mapping - - -def register_training_checkpoint_mapping(class_name: str, mtp_first_layer: int, mtp_depth: int) -> None: - """Register the training model's mapping; its nested trunk then adds none. - - Args: - class_name: Training model class name, which takes lookup priority. - mtp_first_layer: Checkpoint layer index of the first MTP depth. - mtp_depth: Number of MTP depths. - """ - from transformers.conversion_mapping import ( # pylint: disable=import-outside-toplevel - register_checkpoint_conversion_mapping, - ) - - register_checkpoint_conversion_mapping( - class_name, build_training_checkpoint_mapping(mtp_first_layer, mtp_depth), overwrite=True, - ) - # The root mapping already covers the nested trunk; a second, scoped copy - # would merge its experts twice. - register_checkpoint_conversion_mapping("DeepseekV32Model", [], overwrite=True) - - -__all__ = ["build_training_checkpoint_mapping", "register_training_checkpoint_mapping"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py deleted file mode 100644 index 432c0cd907..0000000000 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/dsa_attention.py +++ /dev/null @@ -1,166 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""DeepSeek-V3.2 DSA attention with the indexer training options. - -``DeepseekV32DSAAttention`` implements the released attention. The training -model adds, on the sparse path: - -* ``index_rotate_activation``: the orthonormal Hadamard rotation that - DeepSeek-V3.2 and MindSpeed-LLM apply to the indexer query and key after RoPE; -* the indexer KL teacher over all attention heads when tensor parallelism shards - them, with the loss divided by the TP ranks whose identical gradients loss - parallelism sums; -* ``last_indexer_loss``, the KL value of the latest forward, for logging. - -The dense warm-up path keeps the released behaviour; its indexer loss is not -logged and rejects tensor-parallel heads. -""" - -from __future__ import annotations - -from collections.abc import Mapping -from functools import lru_cache -from typing import Any, Optional - -import torch # pylint: disable=forbidden-backend-import -import torch.distributed as dist # pylint: disable=forbidden-backend-import -from torch import nn # pylint: disable=forbidden-backend-import -from torch.nn import functional as F # pylint: disable=forbidden-backend-import - -from hyper_parallel.components.functional import aux_loss_auto_scale, dsa_kl_loss -from hyper_parallel.components.modules.dsa_attention import DeepseekV32DSAAttention - - -@lru_cache(maxsize=8) -def _hadamard_matrix(size: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: - """Return the Sylvester-ordered ``size`` x ``size`` Hadamard matrix.""" - matrix = torch.ones(1, 1, dtype=torch.float32) - while matrix.shape[0] < size: - matrix = torch.cat((torch.cat((matrix, matrix), dim=1), torch.cat((matrix, -matrix), dim=1)), dim=0) - return matrix.to(dtype=dtype, device=device) - - -def rotate_activation(states: torch.Tensor) -> torch.Tensor: - """Apply the orthonormal Hadamard rotation over the last dimension.""" - size = states.shape[-1] - if size & (size - 1): - raise ValueError(f"Hadamard rotation requires a power-of-two width, got {size}") - matrix = _hadamard_matrix(size, states.dtype, states.device) - return F.linear(states, matrix) * size**-0.5 # pylint: disable=not-callable - - -def _gather_heads(tensor: torch.Tensor, dim: int, group: Any) -> torch.Tensor: - """Concatenate tensor-parallel head shards along ``dim`` in rank order.""" - shards = [torch.empty_like(tensor) for _ in range(dist.get_world_size(group))] - dist.all_gather(shards, tensor.contiguous(), group=group) - return torch.cat(shards, dim=dim) - - -class DeepseekV32TrainingDSAAttention(DeepseekV32DSAAttention): - """``DeepseekV32DSAAttention`` with the indexer options of the training model.""" - - def __init__( - self, - *, - module: nn.Module, - module_fqn: str = "", - context: Mapping[str, Any] | None = None, - ) -> None: - """Build the released replacement, then read the indexer training options.""" - super().__init__(module=module, module_fqn=module_fqn, context=context) - self.index_rotate_activation = bool(getattr(self.config, "index_rotate_activation", False)) - # Group of the tensor-parallel attention-head shards and the TP ranks whose - # identical KL gradients the Trainer sums; both are bound after sharding. - self.kl_head_group = None - self.kl_loss_tp_replicas = 1 - self.last_indexer_loss: Optional[torch.Tensor] = None - - def _project_index_states( - self, - hidden_states: torch.Tensor, - q_resid: torch.Tensor, - position_embeddings: tuple[torch.Tensor, torch.Tensor] | None, - ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Build the indexer states, rotating the query and key when enabled.""" - index_query, index_key, merge_weight = super()._project_index_states( - hidden_states, q_resid, position_embeddings, - ) - if self.index_rotate_activation: - index_query, index_key = rotate_activation(index_query), rotate_activation(index_key) - return index_query, index_key, merge_weight - - def _indexer_loss_enabled(self) -> bool: - """Return whether this forward trains the indexer.""" - return bool(self.training and not self.freeze_dsa and self.dsa_loss_coeff) - - def _kl_head_group(self) -> Any: - """Return the group holding the other heads of the KL teacher when TP shards them.""" - full_heads = getattr(self, "_hp_full_head_counts", {}).get("num_heads") - if full_heads is None or full_heads == self.num_heads: - return None - if self.kl_head_group is None: - raise RuntimeError( - "Tensor parallelism shards the attention heads; the DSA indexer loss " - "needs kl_head_group set to the tensor-parallel group" - ) - return self.kl_head_group - - def check_dense_indexer_loss(self) -> None: - """Prepare a dense warm-up forward, which neither logs nor gathers the KL teacher.""" - self.last_indexer_loss = None - if self._indexer_loss_enabled() and self._kl_head_group() is not None: - raise NotImplementedError( - "The dense warm-up indexer loss does not gather tensor-parallel attention heads" - ) - - def _compute_attention_output(self, hidden_states, position_embeddings, actual_seq_len, kwargs): - """Run the selected dense or sparse stage.""" - if self.dsa_dense_warm_up: - self.check_dense_indexer_loss() - return super()._compute_attention_output(hidden_states, position_embeddings, actual_seq_len, kwargs) - - def _apply_auxiliary_loss( - self, - attn_output: torch.Tensor, - index_states: tuple[torch.Tensor, torch.Tensor, torch.Tensor], - attention_states: tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor], - topk_indices: torch.Tensor, - softmax_stats: tuple[torch.Tensor, torch.Tensor], - actual_q_len: torch.Tensor, - actual_kv_len: torch.Tensor, - ) -> torch.Tensor: - """Attach the DSA KL auxiliary loss against the attention of all heads.""" - if not self._indexer_loss_enabled(): - self.last_indexer_loss = None - return attn_output - query_tnd, key_tnd, q_rot_tnd, k_rot_tnd = ( - tensor.reshape(-1, tensor.shape[2], tensor.shape[3]) - for tensor in attention_states - ) - group = self._kl_head_group() - if group is not None: - query_tnd, q_rot_tnd = (_gather_heads(tensor.detach(), 1, group) for tensor in (query_tnd, q_rot_tnd)) - softmax_stats = tuple(_gather_heads(tensor.detach(), -1, group) for tensor in softmax_stats) - aux_loss = dsa_kl_loss( # pylint: disable=not-callable - *index_states, query_tnd, key_tnd, - topk_indices, *softmax_stats, q_rot_tnd, k_rot_tnd, - actual_q_len, actual_kv_len, self.scaling, self.dsa_loss_coeff, - backend="cann", - ) - self.last_indexer_loss = aux_loss.detach() - return aux_loss_auto_scale(attn_output, aux_loss / self.kl_loss_tp_replicas) - - -__all__ = ["DeepseekV32TrainingDSAAttention", "rotate_activation"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py index 3e4772d728..45d577e7bb 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py @@ -15,7 +15,7 @@ """DeepSeek-V3.2 replacements backed by shared high-performance components.""" from collections.abc import Mapping -from typing import Any +from typing import Any, Optional from torch import nn # pylint: disable=forbidden-backend-import @@ -41,14 +41,48 @@ def replace_deepseek_v32_dsa_attention( module: nn.Module, module_fqn: str, context: Mapping[str, Any], + dsa_loss_coeff: Optional[float] = None, ) -> nn.Module: - """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module and its indexer training options.""" - # pylint: disable=import-outside-toplevel - from hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention import ( - DeepseekV32TrainingDSAAttention, - ) + """Replace DeepSeek-V3.2 MLA/indexer attention with the fused DSA module. + + ``dsa_loss_coeff`` sets the weight of the indexer KL loss; ``None`` keeps + the configuration's value, which the released configuration does not set. + """ + from hyper_parallel.components.modules import DeepseekV32DSAAttention # pylint: disable=C0415 + + attention = DeepseekV32DSAAttention(module=module, module_fqn=module_fqn, context=context) + if dsa_loss_coeff is not None: + attention.dsa_loss_coeff = float(dsa_loss_coeff) + return attention + - return DeepseekV32TrainingDSAAttention(module=module, module_fqn=module_fqn, context=context) +@module_replacement +def replace_deepseek_v32_router( + *, + module: nn.Module, + module_fqn: str, + context: Mapping[str, Any], + aux_loss_coeff: float = 0.0, + enable_expert_bias: bool = False, + expert_bias_update_rate: float = 1e-3, +) -> nn.Module: + """Replace the MoE router with the training router, sharing its weight and bias. + + Args: + module: Transformers ``DeepseekV32TopkRouter``. + module_fqn: Unused. + context: Unused. + aux_loss_coeff: Weight of the sequence-wise balance loss; 0 disables it. + enable_expert_bias: Whether the selection bias follows the routed load. + expert_bias_update_rate: Bias step per optimizer step. + """ + del module_fqn, context + from hyper_parallel.models.deepseek_v32.adapter.router import DeepseekV32Router # pylint: disable=C0415 + + return DeepseekV32Router.from_router( + module, aux_loss_coeff=aux_loss_coeff, enable_expert_bias=enable_expert_bias, + expert_bias_update_rate=expert_bias_update_rate, + ) @module_replacement @@ -74,4 +108,5 @@ def replace_deepseek_v32_grouped_experts( "replace_deepseek_v32_dsa_attention", "replace_deepseek_v32_grouped_experts", "replace_deepseek_v32_rms_norm", + "replace_deepseek_v32_router", ] diff --git a/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py b/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py index 6f76f395a9..3307b06658 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py +++ b/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py @@ -215,9 +215,6 @@ def _run_cp_dsa_kernels( absorbed_query, kv_nope, q_rot, k_rot = attention_states actual_q_len, actual_kv_len = sequence_lengths if use_dense: - check_dense_indexer_loss = getattr(module, "check_dense_indexer_loss", None) - if check_dense_indexer_loss is not None: - check_dense_indexer_loss() return _deepseek_v32_dense_attention(module, index_states, attention_states, sequence_lengths) topk_indices, index_query_tnd, index_key_tnd, merge_weight_tnd = dsa_indexer( # pylint: disable=not-callable diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index cfef2f1770..f7f452a6d3 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -12,21 +12,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ -"""Architecture and lazy provider registration for DeepSeek-V3.2. - -``DeepseekV32ForCausalLM`` checkpoints build the training model -:class:`~hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.DeepseekV32ForCausalLM` -unless a recipe forces the Transformers class. -""" +"""Architecture and lazy provider registration for DeepSeek-V3.2.""" from typing import Any -from hyper_parallel.models.adapter_spec import ModelAdapterSpec, RecomputePolicy +from hyper_parallel.models.adapter_spec import ModelAdapterSpec from hyper_parallel.models.deepseek_v32.adapter.materialization import register_rotary_materialization from hyper_parallel.models.deepseek_v32.adapter.policies.sharding import ( build_parameter_sharding_rules, ) -from hyper_parallel.models.registry import register_custom_model, register_model_adapter +from hyper_parallel.models.registry import register_model_adapter def _load_replacements(): @@ -47,45 +42,32 @@ def _load_context_parallel(): return context_parallel -def build_recompute_policy() -> RecomputePolicy: - """Expose trunk decoder layers and MTP depths as recompute regions.""" - return RecomputePolicy(region_patterns=("model.layers.*", "mtp.layers.*")) - - -def get_fsdp_wrap_modules(model: Any) -> tuple[str, ...]: - """Make each MTP depth its own FSDP unit.""" - mtp = getattr(model, "mtp", None) - return () if mtp is None else tuple(f"mtp.layers.{name}" for name, _ in mtp.layers.named_children()) - - -def get_fsdp_excluded_subtrees(model: Any) -> tuple[str, ...]: - """Keep decoder discovery out of the MTP branch, which declares its own units.""" - return () if getattr(model, "mtp", None) is None else ("mtp",) - - def bind_training_parallel_groups(model: Any, context: Any) -> None: - """Bind the CP and TP groups of the training objectives once the model is sharded. + """Bind the router groups once the model is sharded; reject the indexer loss under TP. The framework calls the external-state provider after planning with the run's ``MeshContext``; DeepSeek-V3.2 owns no external state, so this returns None. + The DSA indexer KL loss compares against the attention of all heads, which + tensor parallelism splits over ranks, so that combination is rejected. Args: model: Sharded model before FSDP. context: ``ExternalBuildContext`` of the build. """ - from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=C0415 - bind_parallel_groups, + from hyper_parallel.models.deepseek_v32.adapter.router import ( # pylint: disable=C0415 + bind_router_parallel_groups, ) - bind_parallel_groups(model, context.mesh_context) + mesh = context.mesh_context + if mesh is not None and mesh.tp_size > 1 and any( + getattr(module, "dsa_loss_coeff", 0.0) for module in model.modules()): + raise NotImplementedError( + "The DSA indexer KL loss needs the attention of all heads; " + "set dsa_loss_coeff to 0 or tp_size to 1" + ) + bind_router_parallel_groups(model, mesh) -register_custom_model( - "DeepseekV32ForCausalLM", - "hyper_parallel.models.deepseek_v32.modeling_deepseek_v32", - "DeepseekV32ForCausalLM", -) - DEEPSEEK_V32_ADAPTER_SPEC = ModelAdapterSpec( architecture="DeepseekV32ForCausalLM", model_type="deepseek_v32", @@ -94,8 +76,5 @@ def bind_training_parallel_groups(model: Any, context: Any) -> None: context_parallel=_load_context_parallel, external_state=bind_training_parallel_groups, sharding_rules=build_parameter_sharding_rules, - fsdp_wrap_modules=get_fsdp_wrap_modules, - fsdp_excluded_subtrees=get_fsdp_excluded_subtrees, - recompute=build_recompute_policy, ) register_model_adapter(DEEPSEEK_V32_ADAPTER_SPEC) diff --git a/hyper_parallel/models/deepseek_v32/adapter/router.py b/hyper_parallel/models/deepseek_v32/adapter/router.py new file mode 100644 index 0000000000..ffe1ab7025 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/router.py @@ -0,0 +1,198 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 training router: sequence-wise balance loss and expert-load counts. + +The Transformers router implements inference only. This router keeps its +expert selection and checkpoint names and adds the Megatron-Core +``seq_aux_loss`` and the counts of the loss-free expert-bias update. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, Optional + +import torch # pylint: disable=forbidden-backend-import +import torch.distributed as dist # pylint: disable=forbidden-backend-import +from torch import nn # pylint: disable=forbidden-backend-import +from torch.nn import functional as F # pylint: disable=forbidden-backend-import +from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter + +from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale +from hyper_parallel.core.activation_memory.recompute_state import is_recomputing +from hyper_parallel.core.utils.communication import differentiable_all_reduce + + +class DeepseekV32Router(DeepseekV32TopkRouter): + """Top-k router with the sequence-wise balance loss and expert-load counts. + + Expert selection and gate values match ``DeepseekV32TopkRouter``. In + training, the balance loss is attached to the returned gate values and the + tokens routed to each expert are counted. The Trainer's MoE monitor sums the + counts over data-parallel ranks after each optimizer step and calls + :meth:`update_expert_bias`. + + Args: + config: DeepSeek-V3.2 configuration. + aux_loss_coeff: Weight of the sequence-wise balance loss; 0 disables it. + enable_expert_bias: Whether ``e_score_correction_bias`` follows the routed load. + expert_bias_update_rate: Bias step per optimizer step. + """ + + def __init__(self, config: Any, *, aux_loss_coeff: float = 0.0, enable_expert_bias: bool = False, + expert_bias_update_rate: float = 1e-3) -> None: + """Create the router state; the caller transfers the source weights.""" + super().__init__(config) + if aux_loss_coeff < 0 or expert_bias_update_rate < 0: + raise ValueError("aux_loss_coeff and expert_bias_update_rate must be nonnegative") + self.aux_loss_coeff = float(aux_loss_coeff) + self.enable_expert_bias = bool(enable_expert_bias) + self.expert_bias_update_rate = float(expert_bias_update_rate) + # Context-parallel group over which one sequence is split; bound after sharding. + self.sequence_partition_group = None + # TP ranks that compute this same loss and whose gradients the Trainer sums. + self.aux_loss_tp_replicas = 1 + self.last_aux_loss: Optional[torch.Tensor] = None + self._token_counts: Optional[torch.Tensor] = None + + @classmethod + def from_router(cls, router: DeepseekV32TopkRouter, **options: Any) -> "DeepseekV32Router": + """Wrap an existing router, sharing its weight and bias tensors. + + The Transformers router keeps no configuration, so the routing fields + are read from the router itself. + """ + config = SimpleNamespace( + num_experts_per_tok=router.top_k, num_local_experts=router.num_experts, + hidden_size=router.hidden_dim, routed_scaling_factor=router.routed_scaling_factor, + n_group=router.num_group, topk_group=router.topk_group, norm_topk_prob=router.norm_topk_prob, + ) + # The placeholder parameters are replaced below; build them where the source lives. + with torch.device(router.weight.device): + trained = cls(config, **options) + trained.weight = router.weight + trained.e_score_correction_bias = router.e_score_correction_bias + trained.train(router.training) + return trained + + def _select_experts(self, scores: torch.Tensor) -> torch.Tensor: + """Return the biased, group-limited top-k expert indices.""" + scores_for_choice = scores + self.e_score_correction_bias + group_scores = ( + scores_for_choice.view(-1, self.num_group, self.num_experts // self.num_group) + .topk(2, dim=-1)[0] + .sum(dim=-1) + ) + group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] + group_mask = torch.zeros_like(group_scores).scatter_(1, group_idx, 1) + score_mask = ( + group_mask.unsqueeze(-1) + .expand(-1, self.num_group, self.num_experts // self.num_group) + .reshape(-1, self.num_experts) + ) + scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) + return torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1] + + def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return router logits, gate values and expert indices for ``[B, S, H]`` tokens.""" + batch_size = hidden_states.shape[0] if hidden_states.ndim == 3 else 1 + hidden_states = hidden_states.view(-1, self.hidden_dim) + router_logits = F.linear( # pylint: disable=not-callable + hidden_states.type(torch.float32), self.weight.type(torch.float32)) + scores = router_logits.sigmoid() + topk_indices = self._select_experts(scores) + topk_weights = scores.gather(1, topk_indices) + if self.norm_topk_prob: + topk_weights = topk_weights / (topk_weights.sum(dim=-1, keepdim=True) + 1e-20) + topk_weights = topk_weights * self.routed_scaling_factor + if self.training: + if self.aux_loss_coeff: + topk_weights = self._attach_balance_loss(topk_weights, scores, topk_indices, batch_size) + if self.enable_expert_bias and not is_recomputing(): + counts = self.tokens_per_expert + counts.scatter_add_(0, topk_indices.reshape(-1), + torch.ones_like(topk_indices.reshape(-1), dtype=counts.dtype)) + return router_logits, topk_weights, topk_indices + + def _attach_balance_loss(self, weights: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor, + batch_size: int) -> torch.Tensor: + """Attach ``coeff * mean_b sum_i f_i P_i`` over each sample of the micro-batch. + + ``f_i`` is the fraction of the sample's routed slots on expert ``i`` + times the expert count, from the selection actually used (biased and + group-limited). ``P_i`` is the sample mean of the scores normalized over + all experts, without the bias. A context-parallel split sums both + statistics over the full sequence. + """ + num_tokens = scores.shape[0] + sequence_length = num_tokens // batch_size + probabilities = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) + probability_sum = probabilities.view(batch_size, sequence_length, -1).sum(dim=1) + routed = torch.zeros_like(scores).scatter_(1, indices, 1.0) + counts = routed.view(batch_size, sequence_length, -1).sum(dim=1) + group = self.sequence_partition_group + if group is not None: + dist.all_reduce(counts, group=group) + probability_sum = differentiable_all_reduce(probability_sum, "sum", group) + sequence_length *= dist.get_world_size(group) + load = counts / (sequence_length * self.top_k / self.num_experts) + loss = (load * (probability_sum / sequence_length)).sum(dim=-1).mean() + self.last_aux_loss = loss.detach() + return aux_loss_auto_scale(weights, loss * (self.aux_loss_coeff / self.aux_loss_tp_replicas)) + + @property + def tokens_per_expert(self) -> torch.Tensor: + """Expert loads routed since the last bias update.""" + counts = self._token_counts + if counts is None or counts.device != self.e_score_correction_bias.device: + counts = torch.zeros(self.num_experts, dtype=torch.int64, device=self.e_score_correction_bias.device) + self._token_counts = counts + return counts + + @torch.no_grad() + def update_expert_bias(self, lr: float, num_recomputations: int = 1) -> None: + """Move each bias by ``lr`` toward the mean load and reset the counts. + + Recomputed forwards are not counted, so ``num_recomputations`` is unused. + """ + del num_recomputations + counts = self.tokens_per_expert + offset = (counts.sum() - counts * self.num_experts).sign().to(self.e_score_correction_bias.dtype) + self.e_score_correction_bias.add_(offset, alpha=lr) + counts.zero_() + + +def bind_router_parallel_groups(model: nn.Module, mesh: Any) -> None: + """Bind the context-parallel group and loss-parallel replicas of every training router. + + Under loss parallelism the Trainer sums replicated gradients over TP ranks, + while each TP rank computes the full balance loss; the loss is therefore + divided by the TP size. + + Args: + model: Sharded DeepSeek-V3.2 model. + mesh: Trainer ``MeshContext``; ``None`` leaves single-process groups. + """ + if mesh is None: + return + cp_group = mesh.cp_mesh.get_group() if mesh.cp_size > 1 else None + tp_replicas = mesh.tp_size if mesh.loss_parallel else 1 + for module in model.modules(): + if isinstance(module, DeepseekV32Router): + module.sequence_partition_group = cp_group + module.aux_loss_tp_replicas = tp_replicas + + +__all__ = ["DeepseekV32Router", "bind_router_parallel_groups"] diff --git a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py b/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py deleted file mode 100644 index 075f8316ed..0000000000 --- a/hyper_parallel/models/deepseek_v32/modeling_deepseek_v32.py +++ /dev/null @@ -1,422 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""DeepSeek-V3.2 training model. - -``DeepseekV32ForCausalLM`` in Transformers implements inference. The training -model keeps its modules and checkpoint names and adds the DeepSeek-V3 training -objectives with Megatron-Core definitions: - -* every MoE router adds the sequence-wise balance loss and counts routed tokens - for the loss-free expert-bias update; -* multi-token prediction (MTP) runs the extra decoder depth that the released - checkpoint stores after the last trunk layer. -""" - -from __future__ import annotations - -import copy -from dataclasses import dataclass -from functools import partial -from typing import Any, Optional - -import torch # pylint: disable=forbidden-backend-import -import torch.distributed as dist # pylint: disable=forbidden-backend-import -from torch import nn # pylint: disable=forbidden-backend-import -from torch.nn import functional as F # pylint: disable=forbidden-backend-import -from transformers.masking_utils import create_causal_mask -from transformers.modeling_outputs import MoeCausalLMOutputWithPast -from transformers.models.deepseek_v32.modeling_deepseek_v32 import ( - DeepseekV32DecoderLayer, - DeepseekV32ForCausalLM as TransformersDeepseekV32ForCausalLM, - DeepseekV32MoE, - DeepseekV32RMSNorm, - DeepseekV32TopkRouter, -) - -from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale -from hyper_parallel.components.modules.mtp import MTPLayer, build_mtp -from hyper_parallel.core.activation_memory.recompute_state import is_recomputing -from hyper_parallel.core.utils.communication import differentiable_all_reduce, gather_counts_via_all_gather -from hyper_parallel.data.constants import IGNORE_INDEX -from hyper_parallel.models.deepseek_v32.adapter.conversion.checkpoint_mapping import ( - register_training_checkpoint_mapping, -) - -__all__ = [ - "DeepseekV32Router", - "DeepseekV32ForCausalLM", - "DeepseekV32TrainingOutput", - "bind_parallel_groups", -] - - -class DeepseekV32Router(DeepseekV32TopkRouter): - """Top-k router with the sequence-wise balance loss and expert-load counts. - - Expert selection and gate values match ``DeepseekV32TopkRouter``. In - training, the balance loss is attached to the returned gate values and the - tokens routed to each expert are counted. The Trainer's MoE monitor sums the - counts over data-parallel ranks after each optimizer step and calls - :meth:`update_expert_bias`. - - Args: - config: DeepSeek-V3.2 configuration. - aux_loss_coeff: Weight of the sequence-wise balance loss; 0 disables it. - enable_expert_bias: Whether ``e_score_correction_bias`` follows the routed load. - expert_bias_update_rate: Bias step per optimizer step. - """ - - def __init__(self, config: Any, *, aux_loss_coeff: float = 0.0, enable_expert_bias: bool = False, - expert_bias_update_rate: float = 1e-3) -> None: - """Create the router state; the caller transfers the source weights.""" - super().__init__(config) - if aux_loss_coeff < 0 or expert_bias_update_rate < 0: - raise ValueError("aux_loss_coeff and expert_bias_update_rate must be nonnegative") - self.aux_loss_coeff = float(aux_loss_coeff) - self.enable_expert_bias = bool(enable_expert_bias) - self.expert_bias_update_rate = float(expert_bias_update_rate) - # Context-parallel group over which one sequence is split; bound after sharding. - self.sequence_partition_group = None - # TP ranks that compute this same loss and whose gradients the Trainer sums. - self.aux_loss_tp_replicas = 1 - self.last_aux_loss: Optional[torch.Tensor] = None - self._token_counts: Optional[torch.Tensor] = None - - @classmethod - def from_router(cls, router: DeepseekV32TopkRouter, config: Any, **options: Any) -> "DeepseekV32Router": - """Wrap an existing router, sharing its weight and bias tensors.""" - trained = cls(config, **options) - trained.weight = router.weight - trained.e_score_correction_bias = router.e_score_correction_bias - return trained - - def _select_experts(self, scores: torch.Tensor) -> torch.Tensor: - """Return the biased, group-limited top-k expert indices.""" - scores_for_choice = scores + self.e_score_correction_bias - group_scores = ( - scores_for_choice.view(-1, self.num_group, self.num_experts // self.num_group) - .topk(2, dim=-1)[0] - .sum(dim=-1) - ) - group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] - group_mask = torch.zeros_like(group_scores).scatter_(1, group_idx, 1) - score_mask = ( - group_mask.unsqueeze(-1) - .expand(-1, self.num_group, self.num_experts // self.num_group) - .reshape(-1, self.num_experts) - ) - scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) - return torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1] - - def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Return router logits, gate values and expert indices for ``[B, S, H]`` tokens.""" - batch_size = hidden_states.shape[0] if hidden_states.ndim == 3 else 1 - hidden_states = hidden_states.view(-1, self.hidden_dim) - router_logits = F.linear( # pylint: disable=not-callable - hidden_states.type(torch.float32), self.weight.type(torch.float32)) - scores = router_logits.sigmoid() - topk_indices = self._select_experts(scores) - topk_weights = scores.gather(1, topk_indices) - if self.norm_topk_prob: - topk_weights = topk_weights / (topk_weights.sum(dim=-1, keepdim=True) + 1e-20) - topk_weights = topk_weights * self.routed_scaling_factor - if self.training: - if self.aux_loss_coeff: - topk_weights = self._attach_balance_loss(topk_weights, scores, topk_indices, batch_size) - if self.enable_expert_bias and not is_recomputing(): - counts = self.tokens_per_expert - counts.scatter_add_(0, topk_indices.reshape(-1), - torch.ones_like(topk_indices.reshape(-1), dtype=counts.dtype)) - return router_logits, topk_weights, topk_indices - - def _attach_balance_loss(self, weights: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor, - batch_size: int) -> torch.Tensor: - """Attach ``coeff * mean_b sum_i f_i P_i`` over each sample of the micro-batch. - - ``f_i`` is the fraction of the sample's routed slots on expert ``i`` - times the expert count, from the selection actually used (biased and - group-limited). ``P_i`` is the sample mean of the scores normalized over - all experts, without the bias. A context-parallel split sums both - statistics over the full sequence. - """ - num_tokens = scores.shape[0] - sequence_length = num_tokens // batch_size - probabilities = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) - probability_sum = probabilities.view(batch_size, sequence_length, -1).sum(dim=1) - routed = torch.zeros_like(scores).scatter_(1, indices, 1.0) - counts = routed.view(batch_size, sequence_length, -1).sum(dim=1) - group = self.sequence_partition_group - if group is not None: - dist.all_reduce(counts, group=group) - probability_sum = differentiable_all_reduce(probability_sum, "sum", group) - sequence_length *= dist.get_world_size(group) - load = counts / (sequence_length * self.top_k / self.num_experts) - loss = (load * (probability_sum / sequence_length)).sum(dim=-1).mean() - self.last_aux_loss = loss.detach() - return aux_loss_auto_scale(weights, loss * (self.aux_loss_coeff / self.aux_loss_tp_replicas)) - - @property - def tokens_per_expert(self) -> torch.Tensor: - """Expert loads routed since the last bias update.""" - counts = self._token_counts - if counts is None or counts.device != self.e_score_correction_bias.device: - counts = torch.zeros(self.num_experts, dtype=torch.int64, device=self.e_score_correction_bias.device) - self._token_counts = counts - return counts - - @torch.no_grad() - def update_expert_bias(self, lr: float, num_recomputations: int = 1) -> None: - """Move each bias by ``lr`` toward the mean load and reset the counts. - - Recomputed forwards are not counted, so ``num_recomputations`` is unused. - """ - del num_recomputations - counts = self.tokens_per_expert - offset = (counts.sum() - counts * self.num_experts).sign().to(self.e_score_correction_bias.dtype) - self.e_score_correction_bias.add_(offset, alpha=lr) - counts.zero_() - - -@dataclass -class DeepseekV32TrainingOutput(MoeCausalLMOutputWithPast): - """Causal-LM output with log-only training metrics read by the Trainer.""" - - extra_metrics: Optional[dict[str, torch.Tensor]] = None - - -def _mtp_layer_config(config: Any, layer_idx: int) -> Any: - """Return a configuration whose per-layer lists also describe ``layer_idx``.""" - layer_config = copy.copy(config) - for name in ("mlp_layer_types", "layer_types"): - values = getattr(config, name, None) - if isinstance(values, (list, tuple)) and len(values) <= layer_idx: - setattr(layer_config, name, [*values, *([values[-1]] * (layer_idx + 1 - len(values)))]) - return layer_config - - -class DeepseekV32ForCausalLM(TransformersDeepseekV32ForCausalLM): - """DeepSeek-V3.2 causal LM with MoE balancing, MTP and DSA indexer training. - - It keeps the released architecture name, so checkpoints it saves load like - the released one. - - Args: - config: DeepSeek-V3.2 configuration. ``num_nextn_predict_layers`` sets - the MTP depth; 0 disables MTP. - mtp_loss_scaling_factor: Weight of the MTP loss, divided by the depth. - mtp_checkpoint_first_layer: Checkpoint layer index of the first MTP - depth. Defaults to ``num_hidden_layers``; set it to the source - checkpoint's trunk depth when loading a truncated trunk. - moe_aux_loss_coeff: Weight of the sequence-wise balance loss. - moe_router_enable_expert_bias: Whether routers update their load bias. - moe_router_bias_update_rate: Load-bias step per optimizer step. - dsa_loss_coeff: Weight of the DSA indexer KL loss; 0 keeps the indexer fixed. - index_rotate_activation: Apply the Hadamard rotation to indexer queries - and keys before scoring. - dsa_dense_warm_up: Train the indexer against dense attention. - """ - - _no_split_modules = ["DeepseekV32DecoderLayer", "MTPLayer"] - # MTP embedding and head are copies of the trunk's; the trunk weights are used. - _keys_to_ignore_on_load_unexpected = [ - r"model\.layers\.\d+\.embed_tokens\.weight", - r"model\.layers\.\d+\.shared_head\.head\.weight", - ] - - def __init__(self, config: Any, *, mtp_loss_scaling_factor: float = 0.3, - mtp_checkpoint_first_layer: Optional[int] = None, moe_aux_loss_coeff: float = 0.0, - moe_router_enable_expert_bias: bool = False, moe_router_bias_update_rate: float = 1e-3, - dsa_loss_coeff: float = 0.0, index_rotate_activation: bool = False, - dsa_dense_warm_up: bool = False) -> None: - """Build the trunk, the MTP depths and the training routers.""" - # The DSA replacement reads its options from the configuration. - config.dsa_loss_coeff = float(dsa_loss_coeff) - config.index_rotate_activation = bool(index_rotate_activation) - config.dsa_dense_warm_up = bool(dsa_dense_warm_up) - super().__init__(config) - if mtp_loss_scaling_factor < 0: - raise ValueError("mtp_loss_scaling_factor must be nonnegative") - self.mtp_loss_scaling_factor = float(mtp_loss_scaling_factor) - first_layer = config.num_hidden_layers - self.mtp = build_mtp(getattr(config, "num_nextn_predict_layers", 0) or None, - layer_factory=lambda depth: MTPLayer( - config.hidden_size, - DeepseekV32DecoderLayer(_mtp_layer_config(config, first_layer + depth), - first_layer + depth), - norm_factory=partial(DeepseekV32RMSNorm, eps=config.rms_norm_eps), - )) - self.mtp_checkpoint_first_layer = (first_layer if mtp_checkpoint_first_layer is None - else int(mtp_checkpoint_first_layer)) - router_options = { - "aux_loss_coeff": moe_aux_loss_coeff, - "enable_expert_bias": moe_router_enable_expert_bias, - "expert_bias_update_rate": moe_router_bias_update_rate, - } - for module in list(self.modules()): - if isinstance(module, DeepseekV32MoE): - module.gate = DeepseekV32Router.from_router(module.gate, config, **router_options) - # Context-parallel group of the trunk sequence; bound after sharding. - self.sequence_group = None - self._pre_norm_capture: Optional[tuple[nn.Module, Any]] = None - self._pre_norm_hidden: Optional[torch.Tensor] = None - self._capturing_pre_norm = False - register_training_checkpoint_mapping(type(self).__name__, self.mtp_checkpoint_first_layer, - 0 if self.mtp is None else len(self.mtp.layers)) - self.post_init() - - @classmethod - def from_config(cls, config: Any, **kwargs: Any) -> "DeepseekV32ForCausalLM": - """Construct from a configuration through the shared custom-model builder.""" - return cls._from_config(config, **kwargs) - - def _capture_pre_norm_hidden(self) -> None: - """Keep the next trunk output entering the final norm, which MTP consumes.""" - self._pre_norm_hidden = None - self._capturing_pre_norm = True - norm = self.model.norm - if self._pre_norm_capture is not None and self._pre_norm_capture[0] is norm: - return - if self._pre_norm_capture is not None: - self._pre_norm_capture[1].remove() - - def keep_input(_module: nn.Module, args: tuple[Any, ...]) -> None: - """Store the final norm's input for the MTP depths during a capture.""" - if self._capturing_pre_norm: - self._pre_norm_hidden = args[0] - self._capturing_pre_norm = False - - self._pre_norm_capture = (norm, norm.register_forward_pre_hook(keep_input)) - - def _shift_left(self, tokens: torch.Tensor, pad_value: int) -> torch.Tensor: - """Shift ``[B, S]`` rows one position left; only the sequence tail is padded. - - Under context parallelism each rank holds a contiguous slice, so the new - last column comes from the first column of the next rank. - """ - group = self.sequence_group - if group is None: - return F.pad(tokens[:, 1:], (0, 1), value=pad_value) - rank, size = dist.get_rank(group), dist.get_world_size(group) - first = gather_counts_via_all_gather(tokens[:, 0].contiguous(), group, size) - tail = first[rank + 1] if rank + 1 < size else torch.full_like(first[0], pad_value) - return torch.cat((tokens[:, 1:], tail.unsqueeze(1)), dim=1) - - def _sequence_mean(self, loss_sum: torch.Tensor, count: torch.Tensor) -> torch.Tensor: - """Average a token loss sum over the full sequence across context-parallel ranks.""" - group = self.sequence_group - if group is None: - return loss_sum / count.clamp_min(1) - global_count = count.clone() - dist.all_reduce(global_count, group=group) - return differentiable_all_reduce(loss_sum, "sum", group) / global_count.clamp_min(1) - - def _mtp_loss(self, hidden: torch.Tensor, input_ids: torch.Tensor, targets: torch.Tensor, - attention_mask: Any, position_ids: torch.Tensor, kwargs: dict[str, Any], - ) -> tuple[torch.Tensor, list[torch.Tensor]]: - """Return the weighted MTP loss and each depth's unweighted loss. - - Depth ``k`` fuses the previous depth's state at position ``i`` with the - embedding of token ``i + k`` and predicts token ``i + k + 1``. Inputs and - targets keep the trunk length; the positions shifted past the end use - token 0 and are excluded from the loss. - """ - position_embeddings = self.model.rotary_emb(hidden, position_ids=position_ids) - total = torch.zeros((), device=hidden.device, dtype=torch.float32) - depth_losses = [] - for layer in self.mtp.layers: - input_ids = self._shift_left(input_ids, 0) - targets = self._shift_left(targets, IGNORE_INDEX) - hidden = layer(hidden, self.model.embed_tokens(input_ids), attention_mask=attention_mask, - position_ids=position_ids, position_embeddings=position_embeddings, **kwargs) - loss_sum = self.loss_function(logits=self.lm_head(hidden), labels=None, vocab_size=self.config.vocab_size, - num_items_in_batch=1, ignore_index=IGNORE_INDEX, shift_labels=targets) - depth_loss = self._sequence_mean(loss_sum, targets.ne(IGNORE_INDEX).sum()) - depth_losses.append(depth_loss.detach()) - total = total + depth_loss - return total * (self.mtp_loss_scaling_factor / len(self.mtp.layers)), depth_losses - - def _training_metrics(self) -> dict[str, torch.Tensor]: - """Return the trunk's mean DSA indexer loss when the indexer is trained.""" - losses = [loss for layer in self.model.layers - if (loss := getattr(layer.self_attn, "last_indexer_loss", None)) is not None] - return {"dsa_indexer_loss": torch.stack(losses).mean()} if losses else {} - - def forward(self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, - position_ids: Optional[torch.LongTensor] = None, past_key_values: Any = None, - inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, - use_cache: Optional[bool] = None, logits_to_keep: int | torch.Tensor = 0, - **kwargs: Any) -> MoeCausalLMOutputWithPast: - """Return the LM loss, plus the weighted MTP loss under ``foundation_loss/mtp``. - - Without labels, or outside training, this is the Transformers forward. - """ - if labels is None or not self.training: - return super().forward(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, - past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, - use_cache=use_cache, logits_to_keep=logits_to_keep, **kwargs) - if self.mtp is not None: - if input_ids is None: - raise ValueError("DeepSeek-V3.2 MTP training requires input_ids") - self._capture_pre_norm_hidden() - outputs = self.model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, - inputs_embeds=inputs_embeds, use_cache=False, **kwargs) - logits = self.lm_head(outputs.last_hidden_state) - loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) - metrics = self._training_metrics() - if self.mtp is not None: - hidden, self._pre_norm_hidden = self._pre_norm_hidden, None - targets = kwargs.get("shift_labels") - if targets is None: - targets = self._shift_left(labels, IGNORE_INDEX) - if position_ids is None: - position_ids = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0) - mask = create_causal_mask(config=self.config, inputs_embeds=hidden, attention_mask=attention_mask, - past_key_values=None, position_ids=position_ids, - allow_is_causal_skip=False) - mtp_loss, depth_losses = self._mtp_loss(hidden, input_ids, targets, mask, position_ids, - {k: v for k, v in kwargs.items() if k != "shift_labels"}) - # A context-parallel slice may hold no trunk target; its LM mean is then undefined. - loss = torch.where(targets.ne(IGNORE_INDEX).any(), loss, torch.zeros_like(loss)) - loss = {"foundation_loss": loss, "foundation_loss/mtp": mtp_loss} - metrics.update({f"mtp_{depth}_loss": value for depth, value in enumerate(depth_losses, start=1)}) - return DeepseekV32TrainingOutput(loss=loss, logits=logits, router_logits=None, - extra_metrics=metrics or None) - - -def bind_parallel_groups(model: nn.Module, mesh: Any) -> None: - """Bind the process groups the training objectives reduce over. - - Under loss parallelism the Trainer sums replicated gradients over TP ranks, - while each TP rank computes the full balance and indexer losses; those - losses are therefore divided by the TP size. - - Args: - model: Constructed and parallelized DeepSeek-V3.2 training model. - mesh: Trainer ``MeshContext``; ``None`` leaves single-process groups. - """ - if mesh is None: - return - cp_group = mesh.cp_mesh.get_group() if mesh.cp_size > 1 else None - tp_group = mesh.device_mesh["tp"].get_group() if mesh.tp_size > 1 else None - tp_replicas = mesh.tp_size if mesh.loss_parallel else 1 - for module in model.modules(): - if isinstance(module, DeepseekV32ForCausalLM): - module.sequence_group = cp_group - elif isinstance(module, DeepseekV32Router): - module.sequence_partition_group = cp_group - module.aux_loss_tp_replicas = tp_replicas - elif hasattr(module, "kl_head_group"): - module.kl_head_group = tp_group - module.kl_loss_tp_replicas = tp_replicas diff --git a/examples/training_demo/deepseek_v32/align_mindspeed.yaml b/hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml similarity index 87% rename from examples/training_demo/deepseek_v32/align_mindspeed.yaml rename to hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml index 63be47c5ec..29da6c0daa 100644 --- a/examples/training_demo/deepseek_v32/align_mindspeed.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml @@ -1,14 +1,15 @@ # DeepSeek-V3.2 与 MindSpeed-LLM 预训练做 loss 对比的配置。 # # 训练语义对应 MindSpeed-LLM examples/mcore/deepseek32/pretrain_deepseek32_671b_4k_A3_ptd.sh: -# DSA:index_topk 1024,indexer KL 系数 1.0,indexer q/k 打分前做 Hadamard 旋转; +# DSA:index_topk 1024,indexer KL 系数 1.0; # MoE:sigmoid 分组路由,序列级负载均衡 loss 1e-4,专家 bias 每步按负载 ±1e-3; -# MTP:1 层,loss 系数 0.3; # 优化器:AdamW lr 1e-5,cosine 衰减到 1e-7,无 warmup,weight decay 0.01, # betas (0.9, 0.999),梯度裁剪 1.0;层间 RMSNorm 权重保持 FP32(对应 --init-norm-weight-in-fp32, # DSA 内部的 q_a/kv_a/k_norm 仍为 BF16); # 数据:两边读同一份 Megatron .bin/.idx,seed 1234、split 100,0,0、seq_length 4096, # 每个 4096 窗口是一条完整的因果序列(不按文档隔离,对应未开 --reset-attention-mask)。 +# 本配置不训练 MTP:MindSpeed 侧去掉 --mtp-num-layers 与 --mtp-loss-scaling-factor。 +# MindSpeed 在 indexer 打分前对 q/k 做 Hadamard 旋转;正交变换不改变打分,两边只差 BF16 舍入。 # 两边需要一致的设置(权重与数据转换、确定性开关)和日志指标的对应关系见 # examples/training_demo/README.md 的 MindSpeed-LLM 对比小节。 # @@ -22,12 +23,6 @@ model: attn_implementation: sdpa config_overrides: index_topk: 1024 - mtp_loss_scaling_factor: 0.3 - moe_aux_loss_coeff: 1.0e-4 - moe_router_enable_expert_bias: true - moe_router_bias_update_rate: 1.0e-3 - dsa_loss_coeff: 1.0 - index_rotate_activation: true model_init_dtype: float32 @@ -65,9 +60,6 @@ fsdp_config: "*.input_layernorm.weight": {param_dtype: float32} "*.post_attention_layernorm.weight": {param_dtype: float32} model.norm.weight: {param_dtype: float32} - mtp.layers.*.enorm.weight: {param_dtype: float32} - mtp.layers.*.hnorm.weight: {param_dtype: float32} - mtp.layers.*.post_norm.weight: {param_dtype: float32} reshard_after_forward: true reshard_after_backward: true requires_grad_sync: true @@ -76,16 +68,10 @@ fsdp_config: comm_fusion: false plan_overrides: - - match: mtp.layers.*.eh_proj - params: - weight: {tp: replicate} - match: - "*.input_layernorm" - "*.post_attention_layernorm" - model.norm - - "mtp.layers.*.enorm" - - "mtp.layers.*.hnorm" - - "mtp.layers.*.post_norm" replace: kind: module implementation: @@ -97,6 +83,16 @@ plan_overrides: implementation: _target_: >- hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + dsa_loss_coeff: 1.0 + - match: "*.mlp.gate" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_router + aux_loss_coeff: 1.0e-4 + enable_expert_bias: true + expert_bias_update_rate: 1.0e-3 - match: "*.mlp.experts" replace: kind: module @@ -126,14 +122,6 @@ plan_overrides: _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - - match: "mtp.layers.*.mtp_block.mlp.forward" - when: ep - replace: - kind: method - implementation: - _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn - use_grouped_gemm: true - overlap_shared_expert: true mixed_precision: enabled: false diff --git a/hyper_parallel/models/deepseek_v32/recipes/train.yaml b/hyper_parallel/models/deepseek_v32/recipes/train.yaml index f50c9ad192..f604529812 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -5,8 +5,8 @@ # 专家区域:ep 64 × edp 8(edp = dp*cp*tp/ep)。每个 EP rank 持有 256/64 = 4 个专家, # edp 内按 edp_shard 4 × 副本 2 做 HSDP,每卡每个 MoE 层恰好 1 个专家。 # 显存估算:FP32 参数 + FP32 梯度 -# + AdamW 两个 FP32 动量 ≈ 16 B/param。主干 58 个 MoE 层加 MTP 层,每卡每层 1 个专家 -# ≈ 2.6B 参数(≈ 42 GB);dense 部分约 18B 参数切到 512 卡上约 35M(≈ 0.6 GB);激活另计。 +# + AdamW 两个 FP32 动量 ≈ 16 B/param。58 个 MoE 层 × 每卡 1 个专家 ≈ 2.55B 参数 +# (≈ 41 GB);dense 部分约 18B 参数切到 512 卡上约 35M(≈ 0.6 GB);激活另计。 # # 其它并行维度用命令行覆盖打开: # TP/loss parallel:--accelerator.tp_size=2 --accelerator.loss_parallel=true @@ -29,25 +29,15 @@ # # 单卡裁剪示例(2 层、16 个路由专家、随机初始化)见 # examples/training_demo/deepseek_v32/train_single_card.yaml;与 MindSpeed-LLM 做精度对比的配置见 -# examples/training_demo/deepseek_v32/align_mindspeed.yaml。 +# 同目录的 align_mindspeed.yaml。 model: - # DeepSeek-V3.2 注册了训练模型(MTP、MoE 负载均衡、DSA indexer 训练),框架入口直接构建它; - # 随机初始化可改用 from_config 并传入 config。 _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained pretrained_model_name_or_path: deepseek-ai/DeepSeek-V3.2 torch_dtype: bfloat16 # DSA 替换不读取稠密 mask;sdpa 让 Transformers 只构建 bool 因果 mask。 attn_implementation: sdpa - # MTP 深度取 config 的 num_nextn_predict_layers(1);MTP loss 按 0.3 / 深度加权。 - mtp_loss_scaling_factor: 0.3 - # 序列级负载均衡 loss 与无辅助损失的专家 bias 更新(每个优化步按负载 ±1e-3)。 - moe_aux_loss_coeff: 1.0e-4 - moe_router_enable_expert_bias: true - moe_router_bias_update_rate: 1.0e-3 - # 稀疏阶段的 indexer KL loss;indexer q/k 在打分前做 Hadamard 旋转。 - dsa_loss_coeff: 1.0 - index_rotate_activation: true + force_hf: true model_init_dtype: float32 @@ -87,17 +77,10 @@ fsdp_config: comm_fusion: false plan_overrides: - # MTP 融合投影([embedding; hidden] -> hidden)在 TP 下保持完整副本。 - - match: mtp.layers.*.eh_proj - params: - weight: {tp: replicate} - match: - "*.input_layernorm" - "*.post_attention_layernorm" - model.norm - - "mtp.layers.*.enorm" - - "mtp.layers.*.hnorm" - - "mtp.layers.*.post_norm" replace: kind: module implementation: @@ -111,6 +94,19 @@ plan_overrides: implementation: _target_: >- hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + # 稀疏阶段 indexer 的 KL loss 系数;TP>1 时不支持(adapter 构建时报错)。 + dsa_loss_coeff: 1.0 + # 训练版 router:选专家与 Transformers 一致,另加序列级负载均衡 loss, + # 并统计专家负载供每个优化步的 bias 更新(±expert_bias_update_rate)。 + - match: "*.mlp.gate" + replace: + kind: module + implementation: + _target_: >- + hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_router + aux_loss_coeff: 1.0e-4 + enable_expert_bias: true + expert_bias_update_rate: 1.0e-3 # 专家始终使用同一个 grouped-GEMM 实现;EP 只改变该边界外的 token 分发与合并。 - match: "*.mlp.experts" replace: @@ -131,7 +127,7 @@ plan_overrides: dense_warmup: null # EP:模型自己的 EP 工厂直接使用 router 返回的专家与门控值(负载均衡 loss 挂在门控值上), # token 分发、专家计算与合并沿用框架通用的 EP 骨架。 - # 只匹配 MoE 层:first_k_dense_replace=3,层 0-2 为稠密 MLP,层 3-60 与 MTP 层为 MoE; + # 只匹配 MoE 层:first_k_dense_replace=3,层 0-2 为稠密 MLP,层 3-60 为 MoE; # fnmatch 不支持数值区间,因此分两条 glob 覆盖 3-9 与 10-99。 # 裁剪模型改变稠密层数时需要同步调整这两条 glob。 - match: "model.layers.[3-9].mlp.forward" @@ -150,14 +146,6 @@ plan_overrides: _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn use_grouped_gemm: true overlap_shared_expert: true - - match: "mtp.layers.*.mtp_block.mlp.forward" - when: ep - replace: - kind: method - implementation: - _target_: hyper_parallel.models.deepseek_v32.adapter.distributed.expert_parallel.deepseek_v32_ep_compute_fn - use_grouped_gemm: true - overlap_shared_expert: true mixed_precision: enabled: false @@ -233,8 +221,8 @@ lr_scheduler: lr_decay_style: cosine lr_config: lr: 1.0e-5 - lr_warmup_steps: 0 - min_lr: 1.0e-7 + lr_warmup_steps: 1 + min_lr: 0.0 checkpoint: save_ckpt: false diff --git a/tests/common/dsa_reference_kernels.py b/tests/common/dsa_reference_kernels.py index 7363660713..d42cbc6c4c 100644 --- a/tests/common/dsa_reference_kernels.py +++ b/tests/common/dsa_reference_kernels.py @@ -39,7 +39,6 @@ _STUB_MODULES = ("torch_npu", "omni_training_custom_ops", "cann_ops_transformer", "cann_ops_transformer.ops") _DSA_MODULES = ( "hyper_parallel.components.modules.dsa_attention", - "hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention", "hyper_parallel.models.deepseek_v32.adapter.distributed.context_parallel", ) # Lazy export packages cache resolved symbols in their globals. diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index 5454b0786d..f750a56d54 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -14,17 +14,17 @@ # ============================================================================ """CPU/Gloo DeepSeek-V3.2 TP/CP/EP/FSDP parity against a single-process reference. -Each case builds one small DeepSeek-V3.2 training model with fixed weights, -one MTP depth and the sequence-wise balance loss, converts a copy through the -Trainer chain (recipe ``plan_overrides`` -> module replacement -> -``ShardingPlanner`` -> ``apply_sharding_plan`` -> FSDP2) and runs one +Each case builds one small DeepSeek-V3.2 model with fixed weights and the +training router (sequence-wise balance loss and expert-load counts), converts a +copy through the Trainer chain (recipe ``plan_overrides`` -> module replacement +-> ``ShardingPlanner`` -> ``apply_sharding_plan`` -> FSDP2) and runs one forward/backward on the same tokens. DSA runs the NPU sparse-attention replacement on the CPU reference kernels of ``tests.common.dsa_reference_kernels``; the NPU-only RMSNorm and grouped-expert kernels stay native. FSDP2 owns the Trainer's gradient reduction (SUM over the DP x CP domain and over TP replicas, scaled by 1 / (dp * cp * (1 if loss_parallel else tp))), so -the raw losses are backpropagated and every gradient must equal the +the raw loss is backpropagated and every gradient must equal the single-process gradient. Expert loads summed over the DP x CP domain must equal the single-process loads. """ @@ -80,7 +80,7 @@ def backward(ctx: Any, *grads: torch.Tensor) -> tuple: # pylint: disable=argume def _config() -> DeepseekV32Config: - """Return one dense layer followed by two MoE layers and one MoE MTP depth.""" + """Return one dense layer followed by two MoE layers.""" config = DeepseekV32Config.from_dict({ "vocab_size": 128, "hidden_size": 64, "intermediate_size": 96, "moe_intermediate_size": 32, "num_hidden_layers": 3, "first_k_dense_replace": 1, "num_attention_heads": 4, @@ -89,22 +89,30 @@ def _config() -> DeepseekV32Config: "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 6, "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, "attn_implementation": "sdpa", - "num_nextn_predict_layers": 1, }) config.architectures = ["DeepseekV32ForCausalLM"] return config +_ROUTER_OPTIONS = {"aux_loss_coeff": 0.1, "enable_expert_bias": True} + + def _reference_model(): - """Build the unsharded training model with nonzero expert-selection biases.""" - from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=import-outside-toplevel - DeepseekV32ForCausalLM, + """Build the unsharded model with training routers and nonzero expert-selection biases.""" + # pylint: disable=import-outside-toplevel + from transformers import DeepseekV32ForCausalLM + + from hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement import ( + replace_deepseek_v32_router, ) torch.manual_seed(7) - model = DeepseekV32ForCausalLM( - _config(), moe_aux_loss_coeff=0.1, moe_router_enable_expert_bias=True, - ).float().train() + model = DeepseekV32ForCausalLM(_config()).float().train() + for layer in model.model.layers: + if hasattr(layer.mlp, "gate"): + layer.mlp.gate = replace_deepseek_v32_router( + module=layer.mlp.gate, module_fqn="", context={}, **_ROUTER_OPTIONS, + ) with torch.no_grad(): for name, buffer in model.named_buffers(): if name.endswith("e_score_correction_bias"): @@ -113,9 +121,8 @@ def _reference_model(): def _plan_overrides() -> list: - """Return the recipe's DSA, MTP, CP and EP entries; NPU-only norm and expert kernels stay native.""" + """Return the recipe's DSA, router, CP and EP entries; NPU-only norm and expert kernels stay native.""" return [ - {"match": "mtp.layers.*.eh_proj", "params": {"weight": {"tp": "replicate"}}}, { "match": "*.self_attn", "replace": {"kind": "module", "implementation": { @@ -123,20 +130,20 @@ def _plan_overrides() -> list: }}, }, { - "match": "*.self_attn.forward", "when": "cp", - "replace": {"kind": "method", "implementation": { - "_target_": f"{_ADAPTER}.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper", + "match": "*.mlp.gate", + "replace": {"kind": "module", "implementation": { + "_target_": f"{_ADAPTER}.conversion.module_replacement.replace_deepseek_v32_router", + **_ROUTER_OPTIONS, }}, }, { - "match": "model.layers.[1-9].mlp.forward", "when": "ep", + "match": "*.self_attn.forward", "when": "cp", "replace": {"kind": "method", "implementation": { - "_target_": f"{_ADAPTER}.distributed.expert_parallel.deepseek_v32_ep_compute_fn", - "overlap_shared_expert": True, + "_target_": f"{_ADAPTER}.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper", }}, }, { - "match": "mtp.layers.*.mtp_block.mlp.forward", "when": "ep", + "match": "model.layers.[1-9].mlp.forward", "when": "ep", "replace": {"kind": "method", "implementation": { "_target_": f"{_ADAPTER}.distributed.expert_parallel.deepseek_v32_ep_compute_fn", "overlap_shared_expert": True, @@ -188,9 +195,7 @@ def _build_parallel_model(reference, config): model, _ = _maybe_apply_module_replacements( model, None, setup, None, False, get_model_conversion_mapping(model) ) - replaced_layers = [*model.model.layers, *(layer.mtp_block for layer in model.mtp.layers)] - source_layers = [*reference.model.layers, *(layer.mtp_block for layer in reference.mtp.layers)] - for replaced, source in zip(replaced_layers, source_layers): + for replaced, source in zip(model.model.layers, reference.model.layers): with torch.no_grad(): replaced.self_attn.linear_qkv.weight.copy_(torch.cat([ source.self_attn.q_a_proj.weight, source.self_attn.kv_a_proj_with_mqa.weight, @@ -247,7 +252,7 @@ def _block_diagonal_mask(boundaries): def _expert_loads(model): """Return each training router's routed-token counts by module name.""" - from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( # pylint: disable=import-outside-toplevel + from hyper_parallel.models.deepseek_v32.adapter.router import ( # pylint: disable=import-outside-toplevel DeepseekV32Router, ) @@ -282,7 +287,7 @@ def _run_case(*, tp=1, cp=1, ep=1, loss_parallel=False, packed=False): reference_mask = {"attention_mask": _block_diagonal_mask(_PACKED_BOUNDARIES)} if packed else {} expected = reference(input_ids=inputs, labels=labels, shift_labels=labels, position_ids=positions, use_cache=False, **reference_mask) - sum(expected.loss.values()).backward() + expected.loss.backward() local = slice(mesh.cp_rank * _SEQ_LEN // cp, (mesh.cp_rank + 1) * _SEQ_LEN // cp) boundaries = {} @@ -299,15 +304,12 @@ def _run_case(*, tp=1, cp=1, ep=1, loss_parallel=False, packed=False): shift_labels=labels[:, local].contiguous(), position_ids=positions[:, local], use_cache=False, **boundaries, ) - sum(output.loss.values()).backward() - - same_keys = set(output.loss) == set(expected.loss) == {"foundation_loss", "foundation_loss/mtp"} - assert same_keys, f"loss keys differ: {set(output.loss)} vs {set(expected.loss)}" - for key, value in output.loss.items(): - loss = value.detach().reshape(()).clone() - if cp > 1: - dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=mesh.device_mesh["cp"].get_group()) - torch.testing.assert_close(loss, expected.loss[key].detach(), rtol=1e-5, atol=1e-6, msg=key) + output.loss.backward() + + loss = output.loss.detach().reshape(()).clone() + if cp > 1: + dist.all_reduce(loss, op=dist.ReduceOp.AVG, group=mesh.device_mesh["cp"].get_group()) + torch.testing.assert_close(loss, expected.loss.detach(), rtol=1e-5, atol=1e-6) compared = 0 for name, grad, reference_grad in _compared_gradients(model, reference, source_shard_info): torch.testing.assert_close(grad, reference_grad, rtol=1e-4, atol=1e-6, msg=name) diff --git a/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py b/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py deleted file mode 100644 index 3ea5df81b6..0000000000 --- a/tests/ut/auto_models/models/deepseek_v32/test_cropped_deepseek_v32.py +++ /dev/null @@ -1,93 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""Single-card DeepSeek-V3.2 crop: per-layer MLP pattern and routing constraints.""" - -import importlib.util -import tempfile -import unittest -from pathlib import Path - -import torch -from transformers import DeepseekV32Config, DeepseekV32ForCausalLM -from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32MLP, DeepseekV32MoE - -from tests.common.mark_utils import arg_mark - -# Load the example by path: `examples` is also the RL package name that -# tests/ut/rl/conftest.py puts on sys.path, so importing it by name would -# bind whichever package a pytest session imports first. -_BUILDER = Path(__file__).resolve().parents[5] / "examples/training_demo/deepseek_v32/cropped_deepseek_v32.py" -_SPEC = importlib.util.spec_from_file_location("_cropped_deepseek_v32_example", _BUILDER) -_EXAMPLE = importlib.util.module_from_spec(_SPEC) -_SPEC.loader.exec_module(_EXAMPLE) -build_cropped_deepseek_v32_config = _EXAMPLE.build_cropped_deepseek_v32_config - - -def _save_released_shape(directory: str) -> None: - """Save a narrow configuration with the released depth pattern, routing and FP8 storage.""" - DeepseekV32Config.from_dict({ - "vocab_size": 96, "hidden_size": 48, "intermediate_size": 64, "moe_intermediate_size": 16, - "num_hidden_layers": 5, "first_k_dense_replace": 3, "num_attention_heads": 4, "num_key_value_heads": 4, - "n_shared_experts": 1, "n_routed_experts": 32, "n_group": 8, "topk_group": 4, "num_experts_per_tok": 8, - "kv_lora_rank": 16, "q_lora_rank": 24, "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, - "index_topk": 4, "index_head_dim": 16, "index_n_heads": 4, - "quantization_config": {"quant_method": "fp8", "fmt": "e4m3", "weight_block_size": [128, 128]}, - }).save_pretrained(directory) - - -class TestCroppedDeepseekV32Config(unittest.TestCase): - """The crop must re-derive the dense/MoE layout instead of keeping the released one.""" - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_crop_builds_one_dense_and_one_moe_layer(self): - """ - Feature: Single-card DeepSeek-V3.2 crop. - Description: Crop a released-shaped configuration to two layers, the first dense, with 16 experts. - Expectation: Layer 1 is a 16-expert MoE block, widths are unchanged and the FP8 storage is dropped. - """ - with tempfile.TemporaryDirectory() as directory: - _save_released_shape(directory) - config = build_cropped_deepseek_v32_config( - directory, num_hidden_layers=2, first_k_dense_replace=1, n_routed_experts=16, - ) - with torch.device("meta"): - model = DeepseekV32ForCausalLM(config) - self.assertIsInstance(model.model.layers[0].mlp, DeepseekV32MLP) - self.assertIsInstance(model.model.layers[1].mlp, DeepseekV32MoE) - self.assertEqual(model.model.layers[1].mlp.experts.gate_up_proj.shape[0], 16) - self.assertEqual(config.hidden_size, 48) - self.assertIsNone(getattr(config, "quantization_config", None)) - self.assertFalse(config.use_cache) - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_rejects_expert_counts_that_break_group_routing(self): - """ - Feature: Single-card DeepSeek-V3.2 crop. - Description: Request expert counts below two per group or not divisible by n_group. - Expectation: The crop fails before any model is built. - """ - with tempfile.TemporaryDirectory() as directory: - _save_released_shape(directory) - for experts in (8, 12): - with self.subTest(n_routed_experts=experts), self.assertRaisesRegex(ValueError, "n_group=8"): - build_cropped_deepseek_v32_config( - directory, num_hidden_layers=2, first_k_dense_replace=1, n_routed_experts=experts, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py index 6546d32a09..47b883d6a1 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py @@ -117,14 +117,11 @@ def test_ep_entries_target_exactly_the_moe_layers(self): """Feature: DeepSeek-V3.2 EP plan overrides. Description: Activate the recipe at EP>1 and match its MLP globs against the released depth. - Expectation: Only MoE layers, including the MTP depth, receive the EP compute; CP and EP stay - off at size one. + Expectation: Only MoE layers receive the EP compute; CP and EP stay off at size one. """ released = DeepseekV32Config() mlps = [f"model.layers.{index}.mlp" for index in range(released.num_hidden_layers)] sparse = [name for name, kind in zip(mlps, released.mlp_layer_types) if kind == "sparse"] - mlps.append("mtp.layers.0.mtp_block.mlp") - sparse.append("mtp.layers.0.mtp_block.mlp") with reference_dsa_kernels(): from hyper_parallel.trainer.config import ( # pylint: disable=import-outside-toplevel entries_to_plan_overrides, @@ -133,7 +130,7 @@ def test_ep_entries_target_exactly_the_moe_layers(self): parse_training_args, ) entries = parse_training_args([str(_RECIPE)]).plan_overrides - self.assertEqual(set(entries_to_plan_overrides(entries)), {"mtp.layers.*.eh_proj"}) + self.assertEqual(entries_to_plan_overrides(entries), {}) active = entries_to_plan_overrides(entries, cp_size=2, ep_size=2) ep_globs = [key for key, spec in active.items() if spec.local_compute_fn is not None] matched = [name for name in mlps if any(fnmatch.fnmatchcase(name, glob) for glob in ep_globs)] diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py new file mode 100644 index 0000000000..fe48cdb638 --- /dev/null +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py @@ -0,0 +1,123 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 training router: sequence-wise balance loss and expert-bias update.""" + +import unittest +from unittest.mock import patch + +import torch +from transformers import DeepseekV32Config +from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter + +from hyper_parallel.models.deepseek_v32.adapter.router import DeepseekV32Router +from tests.common.mark_utils import arg_mark + + +def _tiny_config() -> DeepseekV32Config: + """Return a configuration with two expert groups of four experts.""" + return DeepseekV32Config.from_dict({ + "vocab_size": 96, "hidden_size": 48, "intermediate_size": 64, "moe_intermediate_size": 16, + "num_hidden_layers": 2, "first_k_dense_replace": 1, "num_attention_heads": 4, + "num_key_value_heads": 4, "n_shared_experts": 1, "n_routed_experts": 8, "n_group": 2, + "topk_group": 1, "num_experts_per_tok": 2, "kv_lora_rank": 16, "q_lora_rank": 24, + "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 4, + "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, + "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, + }) + + +def _router(config, **options): + """Return a training router over a randomly initialized Transformers router.""" + torch.manual_seed(1) + source = DeepseekV32TopkRouter(config) + with torch.no_grad(): + source.weight.normal_(std=0.2) + source.e_score_correction_bias.normal_(std=0.05) + return source, DeepseekV32Router.from_router(source, **options) + + +def _reference_balance_loss(scores, indices, batch_size, top_k): + """Sequence-wise balance loss, one sample at a time.""" + num_experts = scores.shape[-1] + sequence_length = scores.shape[0] // batch_size + losses = [] + for sample in range(batch_size): + rows = slice(sample * sequence_length, (sample + 1) * sequence_length) + load = torch.zeros(num_experts) + for expert in indices[rows].reshape(-1).tolist(): + load[expert] += 1 + load = load * num_experts / (sequence_length * top_k) + probability = scores[rows] / scores[rows].sum(dim=-1, keepdim=True) + losses.append((load * probability.mean(dim=0)).sum()) + return torch.stack(losses).mean() + + +class TestDeepseekV32Router(unittest.TestCase): + """The training router keeps Transformers routing and adds the training objectives.""" + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_selection_and_balance_loss(self): + """Feature: DeepSeek-V3.2 training router. + + Description: Route two samples through the Transformers and the training router. + Expectation: Indices and gate values match; the balance loss and its router gradient + match the per-sample definition on the biased, group-limited selection. + """ + config = _tiny_config() + source, router = _router(config, aux_loss_coeff=0.5) + hidden = torch.randn(2, 6, config.hidden_size) + _, expected_weights, expected_indices = source(hidden) + router.train() + _, weights, indices = router(hidden) + torch.testing.assert_close(indices, expected_indices, rtol=0, atol=0) + torch.testing.assert_close(weights, expected_weights) + + router.weight.grad = None + (weights * 0).sum().backward() + reference_weight = router.weight.detach().clone().requires_grad_() + flat = hidden.reshape(-1, config.hidden_size) + scores = torch.nn.functional.linear(flat, reference_weight).sigmoid() # pylint: disable=not-callable + reference = _reference_balance_loss(scores, indices, batch_size=2, top_k=config.num_experts_per_tok) + torch.testing.assert_close(router.last_aux_loss, reference.detach()) + (0.5 * reference).backward() + torch.testing.assert_close(router.weight.grad, reference_weight.grad) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="allcards", essential_mark="essential") + def test_expert_bias_update(self): + """Feature: Loss-free expert-bias update. + + Description: Count routed tokens in training, skip a recomputed forward, then update. + Expectation: Each bias moves by the rate toward the mean load and the counts reset. + """ + config = _tiny_config() + _, router = _router(config, enable_expert_bias=True) + router.train() + hidden = torch.randn(1, 5, config.hidden_size) + _, _, indices = router(hidden) + with patch("hyper_parallel.models.deepseek_v32.adapter.router.is_recomputing", return_value=True): + router(hidden) + counts = torch.bincount(indices.reshape(-1), minlength=config.n_routed_experts) + torch.testing.assert_close(router.tokens_per_expert, counts) + before = router.e_score_correction_bias.clone() + router.update_expert_bias(lr=1e-3) + expected = before + 1e-3 * torch.sign(counts.float().mean() - counts.float()) + torch.testing.assert_close(router.e_score_correction_bias, expected) + self.assertEqual(int(router.tokens_per_expert.sum()), 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py deleted file mode 100644 index 1357c57559..0000000000 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_training_model.py +++ /dev/null @@ -1,275 +0,0 @@ -# Copyright 2026 Huawei Technologies Co., Ltd -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============================================================================ -"""DeepSeek-V3.2 training objectives: balance loss, expert bias, MTP and checkpoint names.""" - -import json -import tempfile -import unittest -from types import SimpleNamespace -from unittest.mock import patch - -import torch -from safetensors import safe_open -from safetensors.torch import save_file -from transformers import DeepseekV32Config -from transformers.masking_utils import create_causal_mask -from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter - -from hyper_parallel.models.deepseek_v32.modeling_deepseek_v32 import ( - DeepseekV32ForCausalLM, - DeepseekV32Router, -) -from tests.common.dsa_reference_kernels import reference_dsa_kernels -from tests.common.mark_utils import arg_mark - - -def _tiny_config(**overrides) -> DeepseekV32Config: - """Return one dense layer, one MoE layer and one MoE MTP depth.""" - values = { - "vocab_size": 96, "hidden_size": 48, "intermediate_size": 64, "moe_intermediate_size": 16, - "num_hidden_layers": 2, "first_k_dense_replace": 1, "num_attention_heads": 4, - "num_key_value_heads": 4, "n_shared_experts": 1, "n_routed_experts": 8, "n_group": 2, - "topk_group": 1, "num_experts_per_tok": 2, "kv_lora_rank": 16, "q_lora_rank": 24, - "qk_rope_head_dim": 8, "v_head_dim": 16, "qk_nope_head_dim": 16, "index_topk": 4, - "index_head_dim": 16, "index_n_heads": 4, "max_position_embeddings": 64, - "rope_parameters": {"rope_type": "default", "rope_theta": 10000.0}, "attn_implementation": "sdpa", - "num_nextn_predict_layers": 1, - } - values.update(overrides) - config = DeepseekV32Config.from_dict(values) - config.architectures = ["DeepseekV32ForCausalLM"] - return config - - -def _router(config, **options): - """Return a training router over a randomly initialized Transformers router.""" - torch.manual_seed(1) - source = DeepseekV32TopkRouter(config) - with torch.no_grad(): - source.weight.normal_(std=0.2) - source.e_score_correction_bias.normal_(std=0.05) - return source, DeepseekV32Router.from_router(source, config, **options) - - -def _reference_balance_loss(scores, indices, batch_size, top_k): - """Sequence-wise balance loss, one sample at a time.""" - num_experts = scores.shape[-1] - sequence_length = scores.shape[0] // batch_size - losses = [] - for sample in range(batch_size): - rows = slice(sample * sequence_length, (sample + 1) * sequence_length) - load = torch.zeros(num_experts) - for expert in indices[rows].reshape(-1).tolist(): - load[expert] += 1 - load = load * num_experts / (sequence_length * top_k) - probability = scores[rows] / scores[rows].sum(dim=-1, keepdim=True) - losses.append((load * probability.mean(dim=0)).sum()) - return torch.stack(losses).mean() - - -class TestDeepseekV32Router(unittest.TestCase): - """The training router keeps Transformers routing and adds the training objectives.""" - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_selection_and_balance_loss(self): - """Feature: DeepSeek-V3.2 training router. - - Description: Route two samples through the Transformers and the training router. - Expectation: Indices and gate values match; the balance loss and its router gradient - match the per-sample definition on the biased, group-limited selection. - """ - config = _tiny_config() - source, router = _router(config, aux_loss_coeff=0.5) - hidden = torch.randn(2, 6, config.hidden_size) - _, expected_weights, expected_indices = source(hidden) - router.train() - _, weights, indices = router(hidden) - torch.testing.assert_close(indices, expected_indices, rtol=0, atol=0) - torch.testing.assert_close(weights, expected_weights) - - router.weight.grad = None - (weights * 0).sum().backward() - reference_weight = router.weight.detach().clone().requires_grad_() - flat = hidden.reshape(-1, config.hidden_size) - scores = torch.nn.functional.linear(flat, reference_weight).sigmoid() # pylint: disable=not-callable - reference = _reference_balance_loss(scores, indices, batch_size=2, top_k=config.num_experts_per_tok) - torch.testing.assert_close(router.last_aux_loss, reference.detach()) - (0.5 * reference).backward() - torch.testing.assert_close(router.weight.grad, reference_weight.grad) - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_expert_bias_update(self): - """Feature: Loss-free expert-bias update. - - Description: Count routed tokens in training, skip a recomputed forward, then update. - Expectation: Each bias moves by the rate toward the mean load and the counts reset. - """ - config = _tiny_config() - _, router = _router(config, enable_expert_bias=True) - router.train() - hidden = torch.randn(1, 5, config.hidden_size) - _, _, indices = router(hidden) - with patch("hyper_parallel.models.deepseek_v32.modeling_deepseek_v32.is_recomputing", return_value=True): - router(hidden) - counts = torch.bincount(indices.reshape(-1), minlength=config.n_routed_experts) - torch.testing.assert_close(router.tokens_per_expert, counts) - before = router.e_score_correction_bias.clone() - router.update_expert_bias(lr=1e-3) - expected = before + 1e-3 * torch.sign(counts.float().mean() - counts.float()) - torch.testing.assert_close(router.e_score_correction_bias, expected) - self.assertEqual(int(router.tokens_per_expert.sum()), 0) - - -class TestDeepseekV32MultiTokenPrediction(unittest.TestCase): - """MTP depth 1 predicts token i + 2 from the trunk state at i and token i + 1.""" - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_mtp_loss_matches_truncated_depth(self): - """Feature: DeepSeek-V3.2 MTP loss. - - Description: Compare the full-length MTP loss with the depth evaluated on the first - S - 1 positions, whose last target is the final label. - Expectation: Equal losses, scaled by 0.3, with the LM loss under ``foundation_loss``. - """ - torch.manual_seed(2) - model = DeepseekV32ForCausalLM(_tiny_config()).float().train() - tokens = torch.randint(1, 96, (2, 13)) - inputs, labels = tokens[:, :-1].contiguous(), tokens[:, 1:].contiguous() - captured = {} - hook = model.model.norm.register_forward_pre_hook(lambda _, args: captured.setdefault("hidden", args[0])) - with torch.no_grad(): - output = model(input_ids=inputs, labels=labels, shift_labels=labels, use_cache=False) - hook.remove() - length = inputs.shape[1] - 1 - positions = torch.arange(length).unsqueeze(0) - embeds = model.model.embed_tokens(inputs[:, 1:]) - mask = create_causal_mask(config=model.config, inputs_embeds=embeds, attention_mask=None, - past_key_values=None, position_ids=positions, allow_is_causal_skip=False) - hidden = model.mtp.layers[0]( - captured["hidden"][:, :-1], embeds, attention_mask=mask, position_ids=positions, - position_embeddings=model.model.rotary_emb(embeds, positions), - ) - logits = model.lm_head(hidden) - expected = torch.nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]), - labels[:, 1:].reshape(-1)) - torch.testing.assert_close(output.loss["foundation_loss/mtp"], 0.3 * expected) - torch.testing.assert_close(output.extra_metrics["mtp_1_loss"], expected) - self.assertIn("foundation_loss", output.loss) - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_released_mtp_layer_round_trips(self): - """Feature: DeepSeek-V3.2 MTP checkpoint names. - - Description: Save the MTP depth under the released layer names, with per-expert - weights and its own embedding and head copies, load the training model and save it. - Expectation: Every MTP parameter is loaded and the copies are not; the saved - checkpoint has the released architecture and weight names. - """ - config = _tiny_config() - torch.manual_seed(3) - source = DeepseekV32ForCausalLM(config).float() - layer = config.num_hidden_layers - state = {} - for name, tensor in source.state_dict().items(): - name = name.replace("mtp.layers.0.mtp_block.", f"model.layers.{layer}.") - name = name.replace("mtp.layers.0.post_norm.", f"model.layers.{layer}.shared_head.norm.") - name = name.replace("mtp.layers.0.", f"model.layers.{layer}.") - if name.endswith("mlp.experts.gate_up_proj"): - gate, up = tensor.chunk(2, dim=1) - for expert in range(tensor.shape[0]): - state[name.replace("gate_up_proj", f"{expert}.gate_proj.weight")] = gate[expert].clone() - state[name.replace("gate_up_proj", f"{expert}.up_proj.weight")] = up[expert].clone() - elif name.endswith("mlp.experts.down_proj"): - for expert in range(tensor.shape[0]): - state[name.replace("down_proj", f"{expert}.down_proj.weight")] = tensor[expert].clone() - else: - state[name] = tensor.clone().contiguous() - state[f"model.layers.{layer}.embed_tokens.weight"] = torch.zeros(config.vocab_size, config.hidden_size) - state[f"model.layers.{layer}.shared_head.head.weight"] = torch.zeros(config.vocab_size, config.hidden_size) - with tempfile.TemporaryDirectory() as directory: - config.save_pretrained(directory) - save_file(state, f"{directory}/model.safetensors") - loaded, info = DeepseekV32ForCausalLM.from_pretrained( - directory, torch_dtype=torch.float32, output_loading_info=True, - ) - loaded.save_pretrained(f"{directory}/export") - with open(f"{directory}/export/config.json", encoding="utf-8") as handle: - architectures = json.load(handle)["architectures"] - with safe_open(f"{directory}/export/model.safetensors", "pt") as handle: - exported = set(handle.keys()) - self.assertEqual(info["missing_keys"], set()) - expected = source.state_dict() - for name, tensor in loaded.state_dict().items(): - if name.startswith("mtp.") or name.startswith("model.embed_tokens"): - torch.testing.assert_close(tensor, expected[name], msg=name) - self.assertEqual(architectures, ["DeepseekV32ForCausalLM"]) - copies = {f"model.layers.{layer}.embed_tokens.weight", f"model.layers.{layer}.shared_head.head.weight"} - self.assertEqual(exported, set(state) - copies) - - -class TestDeepseekV32IndexerOptions(unittest.TestCase): - """Indexer rotation and the tensor-parallel KL teacher.""" - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_hadamard_rotation_preserves_scores(self): - """Feature: Indexer Hadamard rotation. - - Description: Rotate indexer queries and keys. - Expectation: The Sylvester matrix is orthogonal up to its size and query-key dot - products are unchanged. - """ - with reference_dsa_kernels(): - # pylint: disable=import-outside-toplevel,protected-access - from hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention import ( - _hadamard_matrix, - rotate_activation, - ) - - matrix = _hadamard_matrix(16, torch.float64, torch.device("cpu")) - torch.testing.assert_close(matrix @ matrix.T, 16 * torch.eye(16, dtype=torch.float64)) - query, key = torch.randn(5, 3, 16, dtype=torch.float64), torch.randn(7, 16, dtype=torch.float64) - torch.testing.assert_close(rotate_activation(query) @ rotate_activation(key).T, query @ key.T) - - @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", - card_mark="allcards", essential_mark="essential") - def test_kl_teacher_requires_head_group_under_tensor_parallelism(self): - """Feature: DSA indexer KL under tensor parallelism. - - Description: Resolve the KL head group for whole and TP-sharded attention heads. - Expectation: Whole heads need no group; sharded heads use the bound group and - fail without one. - """ - with reference_dsa_kernels(): - # pylint: disable=import-outside-toplevel,protected-access - from hyper_parallel.models.deepseek_v32.adapter.conversion.dsa_attention import ( - DeepseekV32TrainingDSAAttention, - ) - - resolve = DeepseekV32TrainingDSAAttention._kl_head_group - self.assertIsNone(resolve(SimpleNamespace(num_heads=4, kl_head_group=None))) - sharded = SimpleNamespace(num_heads=2, kl_head_group=None, _hp_full_head_counts={"num_heads": 4}) - with self.assertRaises(RuntimeError): - resolve(sharded) - sharded.kl_head_group = "tp" - self.assertEqual(resolve(sharded), "tp") - - -if __name__ == "__main__": - unittest.main() From f6bde2322a2f9f45cfba4cec0248dc9b7c1ef8f2 Mon Sep 17 00:00:00 2001 From: hf1s Date: Tue, 10 Nov 2026 00:53:57 -0600 Subject: [PATCH 18/20] refactor(deepseek_v32): reuse the Transformers router forward in the 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. --- .../models/deepseek_v32/adapter/router.py | 40 ++++--------------- 1 file changed, 8 insertions(+), 32 deletions(-) diff --git a/hyper_parallel/models/deepseek_v32/adapter/router.py b/hyper_parallel/models/deepseek_v32/adapter/router.py index ffe1ab7025..0b59ba8192 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/router.py +++ b/hyper_parallel/models/deepseek_v32/adapter/router.py @@ -14,9 +14,10 @@ # ============================================================================ """DeepSeek-V3.2 training router: sequence-wise balance loss and expert-load counts. -The Transformers router implements inference only. This router keeps its -expert selection and checkpoint names and adds the Megatron-Core -``seq_aux_loss`` and the counts of the loss-free expert-bias update. +The Transformers router implements inference only: it selects the experts but +neither trains their balance nor updates ``e_score_correction_bias``. This +router runs the same forward and, in training, adds the Megatron-Core +``seq_aux_loss`` and the expert loads of the loss-free bias update. """ from __future__ import annotations @@ -27,7 +28,6 @@ import torch # pylint: disable=forbidden-backend-import import torch.distributed as dist # pylint: disable=forbidden-backend-import from torch import nn # pylint: disable=forbidden-backend-import -from torch.nn import functional as F # pylint: disable=forbidden-backend-import from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale @@ -87,39 +87,15 @@ def from_router(cls, router: DeepseekV32TopkRouter, **options: Any) -> "Deepseek trained.train(router.training) return trained - def _select_experts(self, scores: torch.Tensor) -> torch.Tensor: - """Return the biased, group-limited top-k expert indices.""" - scores_for_choice = scores + self.e_score_correction_bias - group_scores = ( - scores_for_choice.view(-1, self.num_group, self.num_experts // self.num_group) - .topk(2, dim=-1)[0] - .sum(dim=-1) - ) - group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1] - group_mask = torch.zeros_like(group_scores).scatter_(1, group_idx, 1) - score_mask = ( - group_mask.unsqueeze(-1) - .expand(-1, self.num_group, self.num_experts // self.num_group) - .reshape(-1, self.num_experts) - ) - scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) - return torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1] - def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """Return router logits, gate values and expert indices for ``[B, S, H]`` tokens.""" batch_size = hidden_states.shape[0] if hidden_states.ndim == 3 else 1 - hidden_states = hidden_states.view(-1, self.hidden_dim) - router_logits = F.linear( # pylint: disable=not-callable - hidden_states.type(torch.float32), self.weight.type(torch.float32)) - scores = router_logits.sigmoid() - topk_indices = self._select_experts(scores) - topk_weights = scores.gather(1, topk_indices) - if self.norm_topk_prob: - topk_weights = topk_weights / (topk_weights.sum(dim=-1, keepdim=True) + 1e-20) - topk_weights = topk_weights * self.routed_scaling_factor + router_logits, topk_weights, topk_indices = super().forward(hidden_states) if self.training: if self.aux_loss_coeff: - topk_weights = self._attach_balance_loss(topk_weights, scores, topk_indices, batch_size) + topk_weights = self._attach_balance_loss( + topk_weights, router_logits.sigmoid(), topk_indices, batch_size, + ) if self.enable_expert_bias and not is_recomputing(): counts = self.tokens_per_expert counts.scatter_add_(0, topk_indices.reshape(-1), From 93d8c49a95974631ef2fdb4f375150945681293e Mon Sep 17 00:00:00 2001 From: hf1s Date: Tue, 10 Nov 2026 01:01:47 -0600 Subject: [PATCH 19/20] refactor(deepseek_v32): name the balancing module aux_loss like other 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. --- .../deepseek_v32/adapter/{router.py => aux_loss.py} | 8 ++++---- .../deepseek_v32/adapter/conversion/module_replacement.py | 2 +- .../models/deepseek_v32/adapter/registration.py | 2 +- .../deepseek_v32/_test_deepseek_v32_parallel.py | 2 +- ...epseek_v32_router.py => test_deepseek_v32_aux_loss.py} | 4 ++-- 5 files changed, 9 insertions(+), 9 deletions(-) rename hyper_parallel/models/deepseek_v32/adapter/{router.py => aux_loss.py} (97%) rename tests/ut/auto_models/models/deepseek_v32/{test_deepseek_v32_router.py => test_deepseek_v32_aux_loss.py} (96%) diff --git a/hyper_parallel/models/deepseek_v32/adapter/router.py b/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py similarity index 97% rename from hyper_parallel/models/deepseek_v32/adapter/router.py rename to hyper_parallel/models/deepseek_v32/adapter/aux_loss.py index 0b59ba8192..c5491357bf 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/router.py +++ b/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py @@ -12,12 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ -"""DeepSeek-V3.2 training router: sequence-wise balance loss and expert-load counts. +"""DeepSeek-V3.2 sequence balancing and expert loads of the bias update. The Transformers router implements inference only: it selects the experts but -neither trains their balance nor updates ``e_score_correction_bias``. This -router runs the same forward and, in training, adds the Megatron-Core -``seq_aux_loss`` and the expert loads of the loss-free bias update. +neither trains their balance nor updates ``e_score_correction_bias``. The +training router defined here runs the same forward and, in training, adds the +Megatron-Core ``seq_aux_loss`` and the expert loads of the loss-free bias update. """ from __future__ import annotations diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py index 45d577e7bb..cbf688146c 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py @@ -77,7 +77,7 @@ def replace_deepseek_v32_router( expert_bias_update_rate: Bias step per optimizer step. """ del module_fqn, context - from hyper_parallel.models.deepseek_v32.adapter.router import DeepseekV32Router # pylint: disable=C0415 + from hyper_parallel.models.deepseek_v32.adapter.aux_loss import DeepseekV32Router # pylint: disable=C0415 return DeepseekV32Router.from_router( module, aux_loss_coeff=aux_loss_coeff, enable_expert_bias=enable_expert_bias, diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index f7f452a6d3..88367c3263 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -54,7 +54,7 @@ def bind_training_parallel_groups(model: Any, context: Any) -> None: model: Sharded model before FSDP. context: ``ExternalBuildContext`` of the build. """ - from hyper_parallel.models.deepseek_v32.adapter.router import ( # pylint: disable=C0415 + from hyper_parallel.models.deepseek_v32.adapter.aux_loss import ( # pylint: disable=C0415 bind_router_parallel_groups, ) diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index f750a56d54..a9e42f8c60 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -252,7 +252,7 @@ def _block_diagonal_mask(boundaries): def _expert_loads(model): """Return each training router's routed-token counts by module name.""" - from hyper_parallel.models.deepseek_v32.adapter.router import ( # pylint: disable=import-outside-toplevel + from hyper_parallel.models.deepseek_v32.adapter.aux_loss import ( # pylint: disable=import-outside-toplevel DeepseekV32Router, ) diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py similarity index 96% rename from tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py rename to tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py index fe48cdb638..63814d9eaa 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_router.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py @@ -21,7 +21,7 @@ from transformers import DeepseekV32Config from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter -from hyper_parallel.models.deepseek_v32.adapter.router import DeepseekV32Router +from hyper_parallel.models.deepseek_v32.adapter.aux_loss import DeepseekV32Router from tests.common.mark_utils import arg_mark @@ -108,7 +108,7 @@ def test_expert_bias_update(self): router.train() hidden = torch.randn(1, 5, config.hidden_size) _, _, indices = router(hidden) - with patch("hyper_parallel.models.deepseek_v32.adapter.router.is_recomputing", return_value=True): + with patch("hyper_parallel.models.deepseek_v32.adapter.aux_loss.is_recomputing", return_value=True): router(hidden) counts = torch.bincount(indices.reshape(-1), minlength=config.n_routed_experts) torch.testing.assert_close(router.tokens_per_expert, counts) From 5c7f86e8036d2a5f22eb2b1374b2b1a3fe723d8d Mon Sep 17 00:00:00 2001 From: hf1s Date: Tue, 10 Nov 2026 01:10:05 -0600 Subject: [PATCH 20/20] refactor(deepseek_v32): align the balancing helpers and router with DeepSeek-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. --- .../models/deepseek_v32/adapter/aux_loss.py | 242 ++++++++---------- .../adapter/conversion/module_replacement.py | 2 +- .../deepseek_v32/adapter/conversion/router.py | 171 +++++++++++++ .../deepseek_v32/adapter/registration.py | 2 +- .../_test_deepseek_v32_parallel.py | 2 +- .../test_deepseek_v32_aux_loss.py | 15 +- 6 files changed, 287 insertions(+), 147 deletions(-) create mode 100644 hyper_parallel/models/deepseek_v32/adapter/conversion/router.py diff --git a/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py b/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py index c5491357bf..0bd378c59b 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py +++ b/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py @@ -12,163 +12,131 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ -"""DeepSeek-V3.2 sequence balancing and expert loads of the bias update. - -The Transformers router implements inference only: it selects the experts but -neither trains their balance nor updates ``e_score_correction_bias``. The -training router defined here runs the same forward and, in training, adds the -Megatron-Core ``seq_aux_loss`` and the expert loads of the loss-free bias update. -""" +"""DeepSeek-V3.2 sequence balancing and expert loads.""" from __future__ import annotations -from types import SimpleNamespace -from typing import Any, Optional +from typing import Any import torch # pylint: disable=forbidden-backend-import import torch.distributed as dist # pylint: disable=forbidden-backend-import -from torch import nn # pylint: disable=forbidden-backend-import -from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter -from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale -from hyper_parallel.core.activation_memory.recompute_state import is_recomputing +from hyper_parallel.core.dtensor.dtensor import DTensor, SkipDTensorDispatch, distribute_tensor from hyper_parallel.core.utils.communication import differentiable_all_reduce -class DeepseekV32Router(DeepseekV32TopkRouter): - """Top-k router with the sequence-wise balance loss and expert-load counts. +def sequence_load_balancing_loss( + scores: torch.Tensor, + selected_experts: torch.Tensor, + sequence_ids: torch.Tensor, + num_sequences: int, + sequence_partition_groups: tuple[Any, ...] = (), +) -> torch.Tensor: + """Average ``E * sum_i(fraction_i * mean_probability_i)`` over sequences. - Expert selection and gate values match ``DeepseekV32TopkRouter``. In - training, the balance loss is attached to the returned gate values and the - tokens routed to each expert are counted. The Trainer's MoE monitor sums the - counts over data-parallel ranks after each optimizer step and calls - :meth:`update_expert_bias`. + This is Megatron-Core's ``seq_aux_loss``: the fractions count the experts + the router actually selected, with the correction bias and the group limit. Args: - config: DeepSeek-V3.2 configuration. - aux_loss_coeff: Weight of the sequence-wise balance loss; 0 disables it. - enable_expert_bias: Whether ``e_score_correction_bias`` follows the routed load. - expert_bias_update_rate: Bias step per optimizer step. + scores: Nonnegative, unbiased scores for all experts, shaped ``[T, E]``. + selected_experts: Selected experts, shaped ``[T, K]``. + sequence_ids: Sample index of each token, shaped ``[T]``. + num_sequences: Number of samples in the microbatch. + sequence_partition_groups: Groups partitioning the same samples' tokens, + such as the context-parallel group. Probability sums use a + differentiable SUM all-reduce. + + Returns: + Unweighted mean over nonempty sequences. """ - - def __init__(self, config: Any, *, aux_loss_coeff: float = 0.0, enable_expert_bias: bool = False, - expert_bias_update_rate: float = 1e-3) -> None: - """Create the router state; the caller transfers the source weights.""" - super().__init__(config) - if aux_loss_coeff < 0 or expert_bias_update_rate < 0: - raise ValueError("aux_loss_coeff and expert_bias_update_rate must be nonnegative") - self.aux_loss_coeff = float(aux_loss_coeff) - self.enable_expert_bias = bool(enable_expert_bias) - self.expert_bias_update_rate = float(expert_bias_update_rate) - # Context-parallel group over which one sequence is split; bound after sharding. - self.sequence_partition_group = None - # TP ranks that compute this same loss and whose gradients the Trainer sums. - self.aux_loss_tp_replicas = 1 - self.last_aux_loss: Optional[torch.Tensor] = None - self._token_counts: Optional[torch.Tensor] = None - - @classmethod - def from_router(cls, router: DeepseekV32TopkRouter, **options: Any) -> "DeepseekV32Router": - """Wrap an existing router, sharing its weight and bias tensors. - - The Transformers router keeps no configuration, so the routing fields - are read from the router itself. - """ - config = SimpleNamespace( - num_experts_per_tok=router.top_k, num_local_experts=router.num_experts, - hidden_size=router.hidden_dim, routed_scaling_factor=router.routed_scaling_factor, - n_group=router.num_group, topk_group=router.topk_group, norm_topk_prob=router.norm_topk_prob, - ) - # The placeholder parameters are replaced below; build them where the source lives. - with torch.device(router.weight.device): - trained = cls(config, **options) - trained.weight = router.weight - trained.e_score_correction_bias = router.e_score_correction_bias - trained.train(router.training) - return trained - - def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - """Return router logits, gate values and expert indices for ``[B, S, H]`` tokens.""" - batch_size = hidden_states.shape[0] if hidden_states.ndim == 3 else 1 - router_logits, topk_weights, topk_indices = super().forward(hidden_states) - if self.training: - if self.aux_loss_coeff: - topk_weights = self._attach_balance_loss( - topk_weights, router_logits.sigmoid(), topk_indices, batch_size, - ) - if self.enable_expert_bias and not is_recomputing(): - counts = self.tokens_per_expert - counts.scatter_add_(0, topk_indices.reshape(-1), - torch.ones_like(topk_indices.reshape(-1), dtype=counts.dtype)) - return router_logits, topk_weights, topk_indices - - def _attach_balance_loss(self, weights: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor, - batch_size: int) -> torch.Tensor: - """Attach ``coeff * mean_b sum_i f_i P_i`` over each sample of the micro-batch. - - ``f_i`` is the fraction of the sample's routed slots on expert ``i`` - times the expert count, from the selection actually used (biased and - group-limited). ``P_i`` is the sample mean of the scores normalized over - all experts, without the bias. A context-parallel split sums both - statistics over the full sequence. + num_tokens, num_experts = scores.shape + top_k = selected_experts.shape[1] + scores = scores.float() + probabilities = scores / scores.sum(dim=-1, keepdim=True).clamp_min(torch.finfo(torch.float32).tiny) + indices = sequence_ids.unsqueeze(-1) * num_experts + selected_experts + counts = scores.new_zeros(num_sequences * num_experts).scatter_add( + 0, indices.reshape(-1), scores.new_ones(num_tokens * top_k), + ).view(num_sequences, num_experts) + probability_sum = scores.new_zeros(num_sequences, num_experts).index_add(0, sequence_ids, probabilities) + for group in sequence_partition_groups: + dist.all_reduce(counts, group=group) + probability_sum = differentiable_all_reduce(probability_sum, "sum", group) + assignments = counts.sum(dim=-1, keepdim=True) + token_count = (assignments / top_k).clamp_min(1.0) + losses = num_experts * ((counts / assignments.clamp_min(1.0)) * (probability_sum / token_count)).sum(-1) + return losses.sum() / (assignments > 0).sum().clamp_min(1) + + +class _AccumulateRouterLoad(torch.autograd.Function): + """Count a training microbatch once, even when its forward is recomputed.""" + + @staticmethod + def forward(ctx: Any, weights: torch.Tensor, counts: torch.Tensor, accumulator: torch.Tensor) -> torch.Tensor: + """Keep the forward unchanged; only a consumed backward records loads. + + Args: + ctx: Autograd context holding the accumulator reference. + weights: Routing-weight gradient carrier. + counts: Immutable local microbatch counts. + accumulator: Integer step-level expert counts. """ - num_tokens = scores.shape[0] - sequence_length = num_tokens // batch_size - probabilities = scores / (scores.sum(dim=-1, keepdim=True) + 1e-20) - probability_sum = probabilities.view(batch_size, sequence_length, -1).sum(dim=1) - routed = torch.zeros_like(scores).scatter_(1, indices, 1.0) - counts = routed.view(batch_size, sequence_length, -1).sum(dim=1) - group = self.sequence_partition_group - if group is not None: - dist.all_reduce(counts, group=group) - probability_sum = differentiable_all_reduce(probability_sum, "sum", group) - sequence_length *= dist.get_world_size(group) - load = counts / (sequence_length * self.top_k / self.num_experts) - loss = (load * (probability_sum / sequence_length)).sum(dim=-1).mean() - self.last_aux_loss = loss.detach() - return aux_loss_auto_scale(weights, loss * (self.aux_loss_coeff / self.aux_loss_tp_replicas)) - - @property - def tokens_per_expert(self) -> torch.Tensor: - """Expert loads routed since the last bias update.""" - counts = self._token_counts - if counts is None or counts.device != self.e_score_correction_bias.device: - counts = torch.zeros(self.num_experts, dtype=torch.int64, device=self.e_score_correction_bias.device) - self._token_counts = counts - return counts - - @torch.no_grad() - def update_expert_bias(self, lr: float, num_recomputations: int = 1) -> None: - """Move each bias by ``lr`` toward the mean load and reset the counts. - - Recomputed forwards are not counted, so ``num_recomputations`` is unused. - """ - del num_recomputations - counts = self.tokens_per_expert - offset = (counts.sum() - counts * self.num_experts).sign().to(self.e_score_correction_bias.dtype) - self.e_score_correction_bias.add_(offset, alpha=lr) - counts.zero_() + ctx.save_for_backward(counts) + ctx.accumulator = accumulator + return weights + + @staticmethod + def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor, None, None]: + """Accumulate integer counts without retaining the model graph. + Args: + ctx: Context saved by forward. + gradient: Unchanged gradient for the routing weights. + """ + with SkipDTensorDispatch(), torch.no_grad(): + ctx.accumulator.add_(ctx.saved_tensors[0]) + return gradient, None, None -def bind_router_parallel_groups(model: nn.Module, mesh: Any) -> None: - """Bind the context-parallel group and loss-parallel replicas of every training router. - Under loss parallelism the Trainer sums replicated gradients over TP ranks, - while each TP rank computes the full balance loss; the loss is therefore - divided by the TP size. +def accumulate_router_load( + weights: torch.Tensor, + selected_experts: torch.Tensor, + accumulator: torch.Tensor, +) -> torch.Tensor: + """Attach the expert-load accumulation to the router's backward path. Args: - model: Sharded DeepSeek-V3.2 model. - mesh: Trainer ``MeshContext``; ``None`` leaves single-process groups. + weights: Routing weights used by expert combination. + selected_experts: Actual selected indices, shaped ``[T, K]``. + accumulator: Integer ``[E]`` step counter. """ - if mesh is None: - return - cp_group = mesh.cp_mesh.get_group() if mesh.cp_size > 1 else None - tp_replicas = mesh.tp_size if mesh.loss_parallel else 1 - for module in model.modules(): - if isinstance(module, DeepseekV32Router): - module.sequence_partition_group = cp_group - module.aux_loss_tp_replicas = tp_replicas + flat = selected_experts.reshape(-1) + counts = torch.zeros_like(accumulator).scatter_add(0, flat, torch.ones_like(flat, dtype=accumulator.dtype)) + if torch.is_grad_enabled() and not weights.requires_grad: + weights = weights.detach().requires_grad_() + return _AccumulateRouterLoad.apply(weights, counts, accumulator) + + +@torch.no_grad() +def update_correction_bias(bias: torch.Tensor, counts: torch.Tensor, update_rate: float) -> None: + """Update the correction bias, including a sharded tensor. + Counts must already include all DP and token partitions. Bias affects + selection only. -__all__ = ["DeepseekV32Router", "bind_router_parallel_groups"] + Args: + bias: The router's ``e_score_correction_bias``, possibly sharded. + counts: Global int64 expert assignment counts. + update_rate: Nonnegative step size for the sign update. + """ + num_experts = counts.shape[-1] + total = counts.sum(dim=-1, keepdim=True) + # Compare in integer arithmetic so rounding cannot erase small load + # differences before the sign update. + direction = (total - counts * num_experts).sign() + delta = (update_rate * direction.float()).to(device=bias.device, dtype=bias.dtype) + if isinstance(bias, DTensor): + delta = distribute_tensor(delta, bias.device_mesh, bias.placements) + bias.add_(delta) + + +__all__ = ["accumulate_router_load", "sequence_load_balancing_loss", "update_correction_bias"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py index cbf688146c..dd6e6f39d9 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/module_replacement.py @@ -77,7 +77,7 @@ def replace_deepseek_v32_router( expert_bias_update_rate: Bias step per optimizer step. """ del module_fqn, context - from hyper_parallel.models.deepseek_v32.adapter.aux_loss import DeepseekV32Router # pylint: disable=C0415 + from hyper_parallel.models.deepseek_v32.adapter.conversion.router import DeepseekV32Router # pylint: disable=C0415 return DeepseekV32Router.from_router( module, aux_loss_coeff=aux_loss_coeff, enable_expert_bias=enable_expert_bias, diff --git a/hyper_parallel/models/deepseek_v32/adapter/conversion/router.py b/hyper_parallel/models/deepseek_v32/adapter/conversion/router.py new file mode 100644 index 0000000000..8463330a50 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/conversion/router.py @@ -0,0 +1,171 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""DeepSeek-V3.2 training router replacing the Transformers router.""" + +from __future__ import annotations + +import math +from types import SimpleNamespace +from typing import Any + +import torch # pylint: disable=forbidden-backend-import +from torch import nn # pylint: disable=forbidden-backend-import +from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter + +from hyper_parallel.components.functional.aux_loss import aux_loss_auto_scale +from hyper_parallel.models.deepseek_v32.adapter.aux_loss import ( + accumulate_router_load, + sequence_load_balancing_loss, + update_correction_bias, +) + + +def _apply_router_training_state( + module: nn.Module, + hidden_states: torch.Tensor, + scores: torch.Tensor, + weights: torch.Tensor, + indices: torch.Tensor, +) -> torch.Tensor: + """Attach the sequence auxiliary gradient and the deferred expert loads.""" + module.last_aux_loss = None + if module.training and module.aux_loss_coeff: + num_sequences = hidden_states.shape[0] if hidden_states.ndim == 3 else 1 + sequence_ids = torch.arange(num_sequences, device=scores.device).repeat_interleave( + scores.shape[0] // num_sequences, + ) + aux_loss = sequence_load_balancing_loss( + scores, indices, sequence_ids, num_sequences, module.sequence_partition_groups, + ) + module.last_aux_loss = aux_loss.detach() + weights = aux_loss_auto_scale(weights, aux_loss * (module.aux_loss_coeff / module.aux_loss_tp_replicas)) + if module.training and module.enable_expert_bias: + weights = accumulate_router_load(weights, indices, module.tokens_per_expert) + return weights + + +class DeepseekV32Router(DeepseekV32TopkRouter): + """``DeepseekV32TopkRouter`` with the sequence-wise balance loss and expert loads. + + Expert selection and gate values are the Transformers router's. In + training, the balance loss is attached to the gate values and each + microbatch's expert loads are counted once in backward. The Trainer's MoE + monitor sums the loads over data-parallel ranks after each optimizer step + and calls :meth:`update_expert_bias`. + + Args: + config: DeepSeek-V3.2 routing configuration. + aux_loss_coeff: Weight of the sequence-wise balance loss; 0 disables it. + enable_expert_bias: Whether ``e_score_correction_bias`` follows the routed load. + expert_bias_update_rate: Bias step per optimizer step. + """ + + def __init__(self, config: Any, *, aux_loss_coeff: float = 0.0, enable_expert_bias: bool = False, + expert_bias_update_rate: float = 1e-3) -> None: + """Create the router state; the caller transfers the source weights.""" + super().__init__(config) + if not math.isfinite(aux_loss_coeff) or aux_loss_coeff < 0: + raise ValueError("aux_loss_coeff must be finite and nonnegative") + if not math.isfinite(expert_bias_update_rate) or expert_bias_update_rate < 0: + raise ValueError("expert_bias_update_rate must be finite and nonnegative") + self.aux_loss_coeff = float(aux_loss_coeff) + self.last_aux_loss: torch.Tensor | None = None + self.enable_expert_bias = bool(enable_expert_bias) + self.expert_bias_update_rate = float(expert_bias_update_rate) + # Groups partitioning one microbatch's tokens and the TP ranks whose identical + # balance-loss gradients the Trainer sums; both are bound after sharding. + self.sequence_partition_groups: tuple[Any, ...] = () + self.aux_loss_tp_replicas = 1 + # The replacement keeps the Transformers router's parameter and buffer names, + # so the load counter is a plain attribute created on the bias's device. + self._token_counts: torch.Tensor | None = None + + @property + def tokens_per_expert(self) -> torch.Tensor: + """Expert loads accumulated since the last bias update.""" + counts = self._token_counts + if counts is None or counts.device != self.e_score_correction_bias.device: + counts = torch.zeros(self.num_experts, dtype=torch.long, device=self.e_score_correction_bias.device) + self._token_counts = counts + return counts + + @classmethod + def from_router(cls, router: DeepseekV32TopkRouter, **options: Any) -> "DeepseekV32Router": + """Wrap an existing router, sharing its weight and bias tensors. + + The Transformers router keeps no configuration, so the routing fields + are read from the router itself. + """ + config = SimpleNamespace( + num_experts_per_tok=router.top_k, num_local_experts=router.num_experts, + hidden_size=router.hidden_dim, routed_scaling_factor=router.routed_scaling_factor, + n_group=router.num_group, topk_group=router.topk_group, norm_topk_prob=router.norm_topk_prob, + ) + # The placeholder parameters are replaced below; build them where the source lives. + with torch.device(router.weight.device): + trained = cls(config, **options) + trained.weight = router.weight + trained.e_score_correction_bias = router.e_score_correction_bias + trained.train(router.training) + return trained + + def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Return router logits, gate values and expert indices for ``[B, S, H]`` tokens.""" + router_logits, topk_weights, topk_indices = super().forward(hidden_states) + topk_weights = _apply_router_training_state( + self, hidden_states, router_logits.sigmoid(), topk_weights, topk_indices, + ) + return router_logits, topk_weights, topk_indices + + @torch.no_grad() + def update_expert_bias(self, lr: float | None = None, num_recomputations: int = 1) -> None: + """Update the selection bias once after the optimizer step. + + The shared monitor synchronizes counts first. Backward counts each + microbatch once, so checkpoint recomputation needs no correction. + + Args: + lr: Optional step size, defaulting to this router's configured rate. + num_recomputations: Shared monitor compatibility argument; unused. + """ + del num_recomputations + if lr is None: + lr = self.expert_bias_update_rate + update_correction_bias(self.e_score_correction_bias, self.tokens_per_expert, lr) + self.tokens_per_expert.zero_() + + +def bind_router_parallel_groups(model: nn.Module, mesh: Any) -> None: + """Bind the context-parallel group and loss-parallel replicas of every training router. + + Under loss parallelism the Trainer sums replicated gradients over TP ranks, + while each TP rank computes the full balance loss; the loss is therefore + divided by the TP size. + + Args: + model: Sharded DeepSeek-V3.2 model. + mesh: Trainer ``MeshContext``; ``None`` leaves single-process groups. + """ + if mesh is None: + return + groups = (mesh.cp_mesh.get_group(),) if mesh.cp_size > 1 else () + tp_replicas = mesh.tp_size if mesh.loss_parallel else 1 + for module in model.modules(): + if isinstance(module, DeepseekV32Router): + module.sequence_partition_groups = groups + module.aux_loss_tp_replicas = tp_replicas + + +__all__ = ["DeepseekV32Router", "bind_router_parallel_groups"] diff --git a/hyper_parallel/models/deepseek_v32/adapter/registration.py b/hyper_parallel/models/deepseek_v32/adapter/registration.py index 88367c3263..9de0b17732 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -54,7 +54,7 @@ def bind_training_parallel_groups(model: Any, context: Any) -> None: model: Sharded model before FSDP. context: ``ExternalBuildContext`` of the build. """ - from hyper_parallel.models.deepseek_v32.adapter.aux_loss import ( # pylint: disable=C0415 + from hyper_parallel.models.deepseek_v32.adapter.conversion.router import ( # pylint: disable=C0415 bind_router_parallel_groups, ) diff --git a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py index a9e42f8c60..447fd5a34d 100644 --- a/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -252,7 +252,7 @@ def _block_diagonal_mask(boundaries): def _expert_loads(model): """Return each training router's routed-token counts by module name.""" - from hyper_parallel.models.deepseek_v32.adapter.aux_loss import ( # pylint: disable=import-outside-toplevel + from hyper_parallel.models.deepseek_v32.adapter.conversion.router import ( # pylint: disable=import-outside-toplevel DeepseekV32Router, ) diff --git a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py index 63814d9eaa..c062b11519 100644 --- a/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py @@ -15,13 +15,12 @@ """DeepSeek-V3.2 training router: sequence-wise balance loss and expert-bias update.""" import unittest -from unittest.mock import patch import torch from transformers import DeepseekV32Config from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter -from hyper_parallel.models.deepseek_v32.adapter.aux_loss import DeepseekV32Router +from hyper_parallel.models.deepseek_v32.adapter.conversion.router import DeepseekV32Router from tests.common.mark_utils import arg_mark @@ -100,16 +99,18 @@ def test_selection_and_balance_loss(self): def test_expert_bias_update(self): """Feature: Loss-free expert-bias update. - Description: Count routed tokens in training, skip a recomputed forward, then update. - Expectation: Each bias moves by the rate toward the mean load and the counts reset. + Description: Route a microbatch twice in training, backpropagate one of the two + graphs as checkpoint recomputation does, then update. + Expectation: The loads count the microbatch once, each bias moves by the rate toward + the mean load and the counts reset. """ config = _tiny_config() _, router = _router(config, enable_expert_bias=True) router.train() hidden = torch.randn(1, 5, config.hidden_size) - _, _, indices = router(hidden) - with patch("hyper_parallel.models.deepseek_v32.adapter.aux_loss.is_recomputing", return_value=True): - router(hidden) + router(hidden) + _, weights, indices = router(hidden) + weights.sum().backward() counts = torch.bincount(indices.reshape(-1), minlength=config.n_routed_experts) torch.testing.assert_close(router.tokens_per_expert, counts) before = router.e_score_correction_bias.clone()