diff --git a/.agent/skills/parallel-strategy-analyzer/references/known-models.md b/.agent/skills/parallel-strategy-analyzer/references/known-models.md index 365b6cfdea..bd01404a94 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. 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 `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..e7d480d2be 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,含 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 0d68019a96..c3e2a1bb1a 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,91 @@ 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 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 +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; 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 /path/to/text/train.jsonl +``` + +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`](../../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; + MindSpeed converts it with `ckpt_convert_deepseek32_hf2mcore.sh`, whose + 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`); 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 + (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 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 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 +``` + +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 The [text configuration](deepseek_v41/train_deepseek_v41_online.yaml) retains all 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..2c42aef518 --- /dev/null +++ b/examples/training_demo/deepseek_v32/run_single_card.sh @@ -0,0 +1,61 @@ +#!/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 + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +PROJECT_ROOT=$(cd "${SCRIPT_DIR}/../../.." && pwd) +OUTPUT_DIR=${OUTPUT_DIR:-"${PROJECT_ROOT}/output/training_demo/deepseek_v32"} +PYTHON_BIN=${PYTHON_BIN:-python} + +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=$(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 +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}" +# 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.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" \ + "$@" \ + 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..cf94df4672 --- /dev/null +++ b/examples/training_demo/deepseek_v32/train_single_card.yaml @@ -0,0 +1,179 @@ +# 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)。 +# +# 模块替换与完整配方 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 /path/to/train.jsonl + +model: + _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 + +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 + 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 + 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 的第二个参数传入:每行一个 JSON,正文在 text 字段。 + data_path: /path/to/train.jsonl + data_config: + labels_are_shifted: true + 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 只检查 attention_mask 的形状、不读内容;文档边界由下面的 runtime adapter 以 cu_seq_lens 传入。 + 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/adapter/aux_loss.py b/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py new file mode 100644 index 0000000000..0bd378c59b --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/aux_loss.py @@ -0,0 +1,142 @@ +# 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 sequence balancing and expert loads.""" + +from __future__ import annotations + +from typing import Any + +import torch # pylint: disable=forbidden-backend-import +import torch.distributed as dist # pylint: disable=forbidden-backend-import + +from hyper_parallel.core.dtensor.dtensor import DTensor, SkipDTensorDispatch, distribute_tensor +from hyper_parallel.core.utils.communication import differentiable_all_reduce + + +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. + + 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: + 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. + """ + 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. + """ + 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 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: + weights: Routing weights used by expert combination. + selected_experts: Actual selected indices, shaped ``[T, K]``. + accumulator: Integer ``[E]`` step counter. + """ + 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. + + 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 c24a926ef4..dd6e6f39d9 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,11 +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.""" + """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 - return DeepseekV32DSAAttention(module=module, module_fqn=module_fqn, context=context) + 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 + + +@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.conversion.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 @@ -71,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/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/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/context_parallel.py b/hyper_parallel/models/deepseek_v32/adapter/distributed/context_parallel.py index c057a04a47..3307b06658 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, ) @@ -215,7 +217,7 @@ def _run_cp_dsa_kernels( if use_dense: 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 +226,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/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/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..9de0b17732 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -14,7 +14,10 @@ # ============================================================================ """Architecture and lazy provider registration for DeepSeek-V3.2.""" +from typing import Any + 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, ) @@ -39,11 +42,39 @@ def _load_context_parallel(): return context_parallel +def bind_training_parallel_groups(model: Any, context: Any) -> None: + """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.adapter.conversion.router import ( # pylint: disable=C0415 + bind_router_parallel_groups, + ) + + 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) + + DEEPSEEK_V32_ADAPTER_SPEC = ModelAdapterSpec( architecture="DeepseekV32ForCausalLM", model_type="deepseek_v32", replacements=_load_replacements, + materialization=register_rotary_materialization, context_parallel=_load_context_parallel, + external_state=bind_training_parallel_groups, sharding_rules=build_parameter_sharding_rules, ) register_model_adapter(DEEPSEEK_V32_ADAPTER_SPEC) diff --git a/hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml b/hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml new file mode 100644 index 0000000000..29da6c0daa --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/recipes/align_mindspeed.yaml @@ -0,0 +1,229 @@ +# 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; +# MoE:sigmoid 分组路由,序列级负载均衡 loss 1e-4,专家 bias 每步按负载 ±1e-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 对比小节。 +# +# 拓扑与完整配方相同(512 卡,ep 64 × edp 8);并行方式不改变计算语义,可以按机器调整。 + +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 + attn_implementation: sdpa + config_overrides: + index_topk: 1024 + +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} + 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 + 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 + 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.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 + +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 015610bce4..f604529812 100644 --- a/hyper_parallel/models/deepseek_v32/recipes/train.yaml +++ b/hyper_parallel/models/deepseek_v32/recipes/train.yaml @@ -1,29 +1,50 @@ -# DeepSeek-V3.2 single-device Trainer recipe. +# DeepSeek-V3.2 训练配方。 # -# 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)。每个 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);激活另计。 # -# 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: +# 其它并行维度用命令行覆盖打开: +# 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 切分。 +# 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 整除、 +# 256/ep_size 可被 edp_shard_size 整除(否则 FSDP 按第 0 维切专家时会补齐空数据), +# 且 global_batch_size 可被 micro_batch_size*dp 整除。 +# +# 默认加载公开 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 +# +# 单卡裁剪示例(2 层、16 个路由专家、随机初始化)见 +# examples/training_demo/deepseek_v32/train_single_card.yaml;与 MindSpeed-LLM 做精度对比的配置见 +# 同目录的 align_mindspeed.yaml。 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 +53,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: 4 + 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 +86,37 @@ 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 + # 稀疏阶段 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: 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 +125,27 @@ 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:模型自己的 EP 工厂直接使用 router 返回的专家与门控值(负载均衡 loss 挂在门控值上), + # token 分发、专家计算与合并沿用框架通用的 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 + 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,20 +181,21 @@ dataset: config_name: wikitext-2-raw-v1 cache_dir: null labels_are_shifted: true - create_attention_mask_in_dataloader: true 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 - attention_mode: dense + # DSA 只检查 attention_mask 的形状、不读内容;文档边界由下面的 runtime adapter 以 cu_seq_lens 传入。 + 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 +207,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..d42cbc6c4c --- /dev/null +++ b/tests/common/dsa_reference_kernels.py @@ -0,0 +1,334 @@ +# 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 importlib.machinery +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_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 = _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 = _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 = _stub_module("cann_ops_transformer", is_package=True) + cann_ops_transformer.ops = ops + return { + "torch_npu": torch_npu, + "omni_training_custom_ops": _stub_module("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: + """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 ( + _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: + 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. + + 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 the stand-in namespaces are restored to their state before entry. + """ + 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: + 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..447fd5a34d --- /dev/null +++ b/tests/torch/auto_models/deepseek_v32/_test_deepseek_v32_parallel.py @@ -0,0 +1,350 @@ +# 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/CP/EP/FSDP parity against a single-process reference. + +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 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. +""" +# 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 +from unittest.mock import patch + +import torch +import torch.distributed as dist +import torch.distributed.nn.functional as dist_nn +import yaml +from transformers import DeepseekV32Config + +from tests.common.dsa_reference_kernels import reference_dsa_kernels + +_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): + """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 + + +_ROUTER_OPTIONS = {"aux_loss_coeff": 0.1, "enable_expert_bias": True} + + +def _reference_model(): + """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()).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"): + buffer.copy_(torch.randn_like(buffer) * 0.05) + return model + + +def _plan_overrides() -> list: + """Return the recipe's DSA, router, 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", + }}, + }, + { + "match": "*.mlp.gate", + "replace": {"kind": "module", "implementation": { + "_target_": f"{_ADAPTER}.conversion.module_replacement.replace_deepseek_v32_router", + **_ROUTER_OPTIONS, + }}, + }, + { + "match": "*.self_attn.forward", "when": "cp", + "replace": {"kind": "method", "implementation": { + "_target_": f"{_ADAPTER}.distributed.context_parallel.deepseek_v32_dsa_attention_cp_wrapper", + }}, + }, + { + "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, + }}, + }, + ] + + +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 + + 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": 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" + path.write_text(yaml.safe_dump(recipe), encoding="utf-8") + return parse_training_args([str(path)]) + + +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, + _create_external_state, + _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) + ) + 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=False, loss_parallel=mesh.loss_parallel, + ) + model, source_shard_info = apply_sharding_plan(model, plan, 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 {} + + +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, 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 + + for name, parameter in model.named_parameters(): + 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)) + 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 _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 _expert_loads(model): + """Return each training router's routed-token counts by module name.""" + from hyper_parallel.models.deepseek_v32.adapter.conversion.router 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 + 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) + try: + # 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, loss_parallel) + model, mesh, source_shard_info = _build_parallel_model(reference, config) + 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) + 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() + + local = slice(mesh.cp_rank * _SEQ_LEN // cp, (mesh.cp_rank + 1) * _SEQ_LEN // cp) + 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() + ) + 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, **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) + 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() + + +def test_cp2_dsa(): + """CP2 through the DSA all-gather wrapper.""" + _run_case(cp=2) + + +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 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.""" + _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 new file mode 100644 index 0000000000..daffca3b4a --- /dev/null +++ b/tests/torch/auto_models/deepseek_v32/test_deepseek_v32_parallel.py @@ -0,0 +1,48 @@ +# 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_cp2_dsa", 2), + ("test_cp2_dsa_packed", 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 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"}): + 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..47b883d6a1 --- /dev/null +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_adapter_contracts.py @@ -0,0 +1,206 @@ +# 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) + 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_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 and the indexer projections replicate 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)) + 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) + + +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 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) + 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) + + +if __name__ == "__main__": + unittest.main() 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 new file mode 100644 index 0000000000..c062b11519 --- /dev/null +++ b/tests/ut/auto_models/models/deepseek_v32/test_deepseek_v32_aux_loss.py @@ -0,0 +1,124 @@ +# 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 + +import torch +from transformers import DeepseekV32Config +from transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32TopkRouter + +from hyper_parallel.models.deepseek_v32.adapter.conversion.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: 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) + 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() + 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()