Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
57a9e18
feat(deepseek_v32): complete TP/CP/EP/FSDP integration
hf1s Oct 28, 2026
512000a
test(deepseek_v32): give DSA reference stand-ins module specs
hf1s Nov 9, 2026
9d25864
feat(deepseek_v32): add single-card cropped training example
hf1s Nov 9, 2026
02cfbab
fix(dsa): import same-named DSA functions from their submodules
hf1s Nov 9, 2026
c97bdb0
test(deepseek_v32): load the single-card example by file path
hf1s Nov 9, 2026
b6e26fb
fix(deepseek_v32): run every recipe step and correct the expert shard…
hf1s Nov 9, 2026
775c300
refactor(deepseek_v32): drop adapter code the framework covers; check…
hf1s Nov 9, 2026
b32679d
chore(deepseek_v32): trim process remarks from recipe and import comm…
hf1s Nov 9, 2026
69bb3d7
feat(dsa): Hadamard indexer rotation and KL teacher over tensor-paral…
hf1s Nov 9, 2026
6a1efbc
feat(deepseek_v32): train MTP, sequence balance loss and expert bias
hf1s Nov 9, 2026
f1f64f8
docs(deepseek_v32): loss comparison against MindSpeed-LLM pretraining
hf1s Nov 9, 2026
7411a15
fix(deepseek_v32): save the training model under the released archite…
hf1s Nov 9, 2026
a17635f
docs(deepseek_v32): MindSpeed conversion layout for the loss comparison
hf1s Nov 9, 2026
aa05698
refactor(deepseek_v32): own the EP compute factory in the model adapter
hf1s Nov 10, 2026
b54276e
refactor(deepseek_v32): build through HyperAutoModelForCausalLM, bind…
hf1s Nov 10, 2026
b6460d2
refactor(deepseek_v32): keep the indexer training options out of the …
hf1s Nov 10, 2026
4db1f9a
refactor(deepseek_v32): drop the custom model and train through adapt…
hf1s Nov 10, 2026
f6bde23
refactor(deepseek_v32): reuse the Transformers router forward in the …
hf1s Nov 10, 2026
93d8c49
refactor(deepseek_v32): name the balancing module aux_loss like other…
hf1s Nov 10, 2026
5c7f86e
refactor(deepseek_v32): align the balancing helpers and router with D…
hf1s Nov 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions docs/feature_status.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
86 changes: 86 additions & 0 deletions examples/training_demo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
61 changes: 61 additions & 0 deletions examples/training_demo/deepseek_v32/run_single_card.sh
Original file line number Diff line number Diff line change
@@ -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"
179 changes: 179 additions & 0 deletions examples/training_demo/deepseek_v32/train_single_card.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading