From 96ec3d9b3349fb6ceefdb248f4edb10abbc00d2a Mon Sep 17 00:00:00 2001 From: hf1s Date: Wed, 11 Nov 2026 03:55:04 -0600 Subject: [PATCH] fix(deepseek_v32): rebuild RoPE buffers, fix the DSA CP wrapper import, add a parallel recipe - Register a materialization provider that rebuilds the non-persistent RoPE buffers (inv_freq, original_inv_freq) after HyperAutoModelForCausalLM loads weights; they were left uninitialized (zeros or NaN). - Import dsa_indexer and dsa_sparse_attention from the functional package in the DSA CP wrapper. Importing the submodules replaced the package attributes with modules, so cp_size=1 runs with a `when: cp` entry failed with "'module' object is not callable". - Add recipes/train_parallel_offline.yaml and run_parallel_offline.sh, which train an 8-layer crop on 8 NPUs with TP2 x CP2 x DP2, EP4 x EDP2 and loss parallelism. - Add the family README in English and Chinese. --- hyper_parallel/models/deepseek_v32/README.md | 141 ++++++++++++++ .../models/deepseek_v32/README.zh.md | 138 ++++++++++++++ .../adapter/distributed/context_parallel.py | 7 +- .../deepseek_v32/adapter/materialization.py | 37 ++++ .../deepseek_v32/adapter/registration.py | 2 + .../recipes/run_parallel_offline.sh | 64 +++++++ .../recipes/train_parallel_offline.yaml | 179 ++++++++++++++++++ 7 files changed, 564 insertions(+), 4 deletions(-) create mode 100644 hyper_parallel/models/deepseek_v32/README.md create mode 100644 hyper_parallel/models/deepseek_v32/README.zh.md create mode 100644 hyper_parallel/models/deepseek_v32/adapter/materialization.py create mode 100755 hyper_parallel/models/deepseek_v32/recipes/run_parallel_offline.sh create mode 100644 hyper_parallel/models/deepseek_v32/recipes/train_parallel_offline.yaml diff --git a/hyper_parallel/models/deepseek_v32/README.md b/hyper_parallel/models/deepseek_v32/README.md new file mode 100644 index 0000000000..cc7ef048e9 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/README.md @@ -0,0 +1,141 @@ +# DeepSeek-V3.2 Model-Family Integration + +**English** | [简体中文](README.zh.md) + +DeepSeek-V3.2 adds DeepSeek Sparse Attention (DSA) to the DeepSeek-V3 MLA + MoE architecture: in every layer a +lightning indexer selects `index_topk` keys for each query (2048 in the released config), and MLA attends only to +those keys. HyperParallel trains the native Transformers `DeepseekV32ForCausalLM`; this directory provides its module +replacements, parallelization rules and training recipe. + +## Registration Identity + +| Item | Value | +|---|---| +| HyperParallel family name (`models//` directory and registration identity) | `deepseek_v32` | +| HF `config.model_type` | `deepseek_v32` | +| HF `architectures` | `DeepseekV32ForCausalLM` | +| Implementation source | Native Transformers implementation (`transformers.models.deepseek_v32`), `trust_remote_code: false` | + +## Directory Structure + +```text +models/deepseek_v32/ +├── __init__.py +├── adapter/ +│ ├── conversion/ +│ │ └── module_replacement.py # Replacement factories: RMSNorm, DSA attention, GroupedExperts +│ ├── distributed/ +│ │ └── context_parallel.py # DSA context-parallel wrapper +│ ├── policies/ +│ │ └── sharding.py # TP sharding rules for MLA and the indexer +│ ├── materialization.py # Restores the RoPE buffers after weights load +│ └── registration.py # ModelAdapterSpec +├── generated/ # Model source generated by codegen, used only with codegen: true +└── recipes/ + ├── run_parallel_offline.sh # Launches train_parallel_offline.yaml on 8 NPUs + ├── train.yaml # Single-process recipe for the released checkpoint + └── train_parallel_offline.yaml # Eight-rank recipe for an 8-layer crop +``` + +## Features + +- **NPU module replacements**, selected by the recipe's `plan_overrides`: `*.input_layernorm`, + `*.post_attention_layernorm` and `model.norm` use the fused `RMSNorm`; `*.self_attn` uses `DeepseekV32DSAAttention`, + which runs the indexer and the sparse attention through CANN fused operators; `*.mlp.experts` uses `GroupedExperts`. +- **Parallelism**: FSDP, TP (with loss parallelism), CP and EP. PP and sequence parallelism are not supported. +- **Training behavior** follows the Transformers implementation: + - the router selects experts with `e_score_correction_bias` (sigmoid scores, group-limited top-k), and the bias keeps + its initial value; + - there is no load-balancing loss; + - the MTP layer (layer 61) of the released checkpoint is ignored and not trained; + - the indexer is not trained, because its output only feeds the non-differentiable top-k selection. +- **Data**: each row is one causal sequence. DSA does not read the contents of `attention_mask`, and supports no padding + mask, dropout or KV cache. + +## Requirements + +- Transformers with `deepseek_v32`: `requirements.txt` requires `transformers>=5.11.0`; validated with 5.13.1. +- Ascend NPU with CANN and `cann_ops_transformer` for the DSA operators; see the + [functional README](../../components/functional/README.md#deepseek-v32-dsa). +- Weights: `from_pretrained` loads the released FP8 checkpoint directly (it is dequantized while reading) as well as BF16 + checkpoints. The layer-61 MTP weights are ignored with a warning. + +## Usage + +### Train with the recipe + +```bash +torchrun --standalone --nproc_per_node=1 \ + scripts/train_lm.py hyper_parallel/models/deepseek_v32/recipes/train.yaml \ + --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 +``` + +Trailing arguments override YAML fields, for example `--training.train_iters=200`. + +### Multiple devices + +Set the topology with command-line overrides. The recipe's `when: cp` entry enables the DSA context-parallel wrapper +when `cp_size > 1`. For EP, add a `when: ep` entry that matches only the MoE layers, i.e. `model.layers..mlp.forward` +for `i >= first_k_dense_replace` (layers 3–60 in the released config): + +```yaml +plan_overrides: + - match: "model.layers.[3-9].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + use_grouped_gemm: true + overlap_shared_expert: true + # Repeat the entry with match: "model.layers.[1-9][0-9].mlp.forward" for layers 10-60. +``` + +For example, eight devices with TP2 × CP2 × DP2 and EP4: + +```bash +torchrun --standalone --nproc_per_node=8 \ + scripts/train_lm.py \ + --accelerator.tp_size=2 --accelerator.cp_size=2 --accelerator.ep_size=4 \ + --accelerator.loss_parallel=true \ + --fsdp_config.dp_shard_size=2 --fsdp_config.edp_shard_size=2 +``` + +Keep these constraints: `ep_size > 1` whenever `tp_size > 1`, because MoE layers shard experts only by EP; +`world_size = tp × cp × dp`; `n_routed_experts` divisible by `ep_size`; `global_batch_size` divisible by +`micro_batch_size × dp`. + +### Eight-rank recipe for an 8-layer crop + +`recipes/train_parallel_offline.yaml` trains an 8-layer crop of DeepSeek-V3.2 (3 dense + 5 MoE layers, 16 routed +experts, 8.40B parameters) on 8 NPUs: TP2 × CP2 × DP2, EP4 × EDP2, loss parallelism and FSDP, with all module +replacements. Create the crop from the released `config.json` and tokenizer files; the weights are random BF16: + +```python +import torch +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer + +source, target = "/path/to/DeepSeek-V3.2", "/path/to/DeepSeek-V3.2-8layer-crop" +released = AutoConfig.from_pretrained(source) +config = AutoConfig.from_pretrained( + source, num_hidden_layers=8, n_routed_experts=16, + # Slice the per-layer types: their names differ between Transformers versions. + layer_types=released.layer_types[:8], mlp_layer_types=released.mlp_layer_types[:8], +) +del config.quantization_config +torch.manual_seed(1234) +AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16).save_pretrained(target) +AutoTokenizer.from_pretrained(source).save_pretrained(target) +``` + +The data is an Indexed Dataset (`.bin`/`.idx`) tokenized with the DeepSeek-V3.2 tokenizer; see the +[offline preparation guide](../../../docs/guide/data/offline_preparation_guide.md). Pass the checkpoint directory and +the dataset prefix without the extension; trailing arguments override YAML fields: + +```bash +bash hyper_parallel/models/deepseek_v32/recipes/run_parallel_offline.sh \ + /path/to/DeepSeek-V3.2-8layer-crop /path/to/dataset_text_document +``` + +The log, data cache and checkpoints go to `output/deepseek_v32` unless `OUTPUT_DIR` is set. diff --git a/hyper_parallel/models/deepseek_v32/README.zh.md b/hyper_parallel/models/deepseek_v32/README.zh.md new file mode 100644 index 0000000000..67ff3c49eb --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/README.zh.md @@ -0,0 +1,138 @@ +# DeepSeek-V3.2 模型族适配 + +[English](README.md) | **简体中文** + +DeepSeek-V3.2 在 DeepSeek-V3 的 MLA + MoE 结构上加入 DeepSeek Sparse Attention(DSA):每层由 +lightning indexer 为每个 query 选出 `index_topk` 个 key(官方 config 为 2048),MLA 只在这些 key 上 +计算 attention。HyperParallel 训练的是 Transformers 原生的 `DeepseekV32ForCausalLM`,本目录提供它的 +模块替换、并行规则和训练 recipe。 + +## 注册身份 + +| 项目 | 值 | +|---|---| +| HyperParallel 族名(`models//` 目录名、注册身份) | `deepseek_v32` | +| HF `config.model_type` | `deepseek_v32` | +| HF `architectures` | `DeepseekV32ForCausalLM` | +| 实现来源 | Transformers 原生实现(`transformers.models.deepseek_v32`),`trust_remote_code: false` | + +## 目录结构 + +```text +models/deepseek_v32/ +├── __init__.py +├── adapter/ +│ ├── conversion/ +│ │ └── module_replacement.py # 替换工厂:RMSNorm、DSA attention、GroupedExperts +│ ├── distributed/ +│ │ └── context_parallel.py # DSA 的 CP wrapper +│ ├── policies/ +│ │ └── sharding.py # MLA 与 indexer 的 TP 分片规则 +│ ├── materialization.py # 加载权重后恢复 RoPE 的 buffer +│ └── registration.py # ModelAdapterSpec +├── generated/ # codegen 生成的模型代码,仅 codegen: true 时使用 +└── recipes/ + ├── run_parallel_offline.sh # 在 8 卡上启动 train_parallel_offline.yaml + ├── train.yaml # 加载官方 checkpoint 的单进程配方 + └── train_parallel_offline.yaml # 8 层裁剪模型的 8 卡配方 +``` + +## 功能 + +- **NPU 模块替换**,由 recipe 的 `plan_overrides` 选用:`*.input_layernorm`、`*.post_attention_layernorm`、 + `model.norm` 换成融合 `RMSNorm`;`*.self_attn` 换成 `DeepseekV32DSAAttention`,indexer 与稀疏 attention 走 + CANN 融合算子;`*.mlp.experts` 换成 `GroupedExperts`。 +- **并行**:FSDP、TP(含 loss parallel)、CP、EP。不支持 PP 和 sequence parallel。 +- **训练行为**与 Transformers 实现一致: + - router 用 `e_score_correction_bias` 选专家(sigmoid 分数、分组 top-k),bias 保持初始值; + - 没有负载均衡 loss; + - 官方 checkpoint 的 MTP 层(第 61 层)加载时被忽略,不训练; + - 不训练 indexer,因为它的输出只用于不可导的 top-k 选择。 +- **数据**:每行是一条因果序列。DSA 不读取 `attention_mask` 的内容,不支持 padding mask、dropout 和 KV cache。 + +## 环境要求 + +- Transformers 需要包含 `deepseek_v32`:`requirements.txt` 要求 `transformers>=5.11.0`,验证版本 5.13.1。 +- 昇腾 NPU,DSA 算子依赖 CANN 与 `cann_ops_transformer`,见 + [functional README](../../components/functional/README.md#deepseek-v32-dsa)。 +- 权重:`from_pretrained` 可以直接加载官方 FP8 checkpoint(读取时反量化),也可以加载 BF16 checkpoint。第 61 层 + MTP 的权重会被忽略并打印 warning。 + +## 使用 + +### 用 recipe 训练 + +```bash +torchrun --standalone --nproc_per_node=1 \ + scripts/train_lm.py hyper_parallel/models/deepseek_v32/recipes/train.yaml \ + --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 +``` + +末尾追加的参数会覆盖 YAML 字段,例如 `--training.train_iters=200`。 + +### 多卡 + +用命令行覆盖设置并行拓扑。recipe 里 `when: cp` 的条目在 `cp_size > 1` 时启用 DSA 的 CP wrapper。EP 需要加一个 +`when: ep` 条目,只匹配 MoE 层,即 `i >= first_k_dense_replace` 的 `model.layers..mlp.forward`(官方 config 为 +第 3–60 层): + +```yaml +plan_overrides: + - match: "model.layers.[3-9].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_ep_compute_fn + use_grouped_gemm: true + overlap_shared_expert: true + # 再用 match: "model.layers.[1-9][0-9].mlp.forward" 写一条同样的条目,覆盖第 10–60 层。 +``` + +例如 8 卡、TP2 × CP2 × DP2、EP4: + +```bash +torchrun --standalone --nproc_per_node=8 \ + scripts/train_lm.py <你的 recipe> \ + --accelerator.tp_size=2 --accelerator.cp_size=2 --accelerator.ep_size=4 \ + --accelerator.loss_parallel=true \ + --fsdp_config.dp_shard_size=2 --fsdp_config.edp_shard_size=2 +``` + +需要满足:`tp_size > 1` 时 `ep_size` 也要大于 1(MoE 层的专家只按 EP 切分);`world_size = tp × cp × dp`; +`n_routed_experts` 能被 `ep_size` 整除;`global_batch_size` 能被 `micro_batch_size × dp` 整除。 + +### 8 层裁剪模型的 8 卡 recipe + +`recipes/train_parallel_offline.yaml` 在 8 卡上训练 DeepSeek-V3.2 的 8 层裁剪模型(3 个 dense 层 + 5 个 MoE 层,16 个路由 +专家,8.40B 参数):TP2 × CP2 × DP2,EP4 × EDP2,loss parallel 加 FSDP,启用全部模块替换。裁剪模型只需要官方目录中的 +`config.json` 和 tokenizer 文件,权重为随机初始化的 BF16: + +```python +import torch +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer + +source, target = "/path/to/DeepSeek-V3.2", "/path/to/DeepSeek-V3.2-8layer-crop" +released = AutoConfig.from_pretrained(source) +config = AutoConfig.from_pretrained( + source, num_hidden_layers=8, n_routed_experts=16, + # 逐层类型从官方列表里截取:类型名在不同 Transformers 版本里不同。 + layer_types=released.layer_types[:8], mlp_layer_types=released.mlp_layer_types[:8], +) +del config.quantization_config +torch.manual_seed(1234) +AutoModelForCausalLM.from_config(config, dtype=torch.bfloat16).save_pretrained(target) +AutoTokenizer.from_pretrained(source).save_pretrained(target) +``` + +数据为用 DeepSeek-V3.2 tokenizer 处理好的 Indexed Dataset(`.bin`/`.idx`),见 +[离线数据准备指南](../../../docs/guide/data/offline_preparation_guide.zh.md)。传入 checkpoint 目录和不带扩展名的数据 +前缀,末尾追加的参数会覆盖 YAML 字段: + +```bash +bash hyper_parallel/models/deepseek_v32/recipes/run_parallel_offline.sh \ + /path/to/DeepSeek-V3.2-8layer-crop /path/to/dataset_text_document +``` + +日志、数据缓存和 checkpoint 写到 `output/deepseek_v32`,可用 `OUTPUT_DIR` 修改。 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..33e073f74e 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,7 @@ 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 +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 +214,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 +223,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/materialization.py b/hyper_parallel/models/deepseek_v32/adapter/materialization.py new file mode 100644 index 0000000000..0f302d364c --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/adapter/materialization.py @@ -0,0 +1,37 @@ +# 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 transformers.models.deepseek_v32.modeling_deepseek_v32 import DeepseekV32RotaryEmbedding + +from hyper_parallel.models.materialization import register_rebuildable_buffer + + +def register_rotary_materialization(model: nn.Module) -> None: + """Retain native CPU RoPE initialization outside storage replaced by to_empty.""" + 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..e23a0bd4c9 100644 --- a/hyper_parallel/models/deepseek_v32/adapter/registration.py +++ b/hyper_parallel/models/deepseek_v32/adapter/registration.py @@ -15,6 +15,7 @@ """Architecture and lazy provider registration for DeepSeek-V3.2.""" 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, ) @@ -43,6 +44,7 @@ def _load_context_parallel(): architecture="DeepseekV32ForCausalLM", model_type="deepseek_v32", replacements=_load_replacements, + materialization=register_rotary_materialization, context_parallel=_load_context_parallel, sharding_rules=build_parameter_sharding_rules, ) diff --git a/hyper_parallel/models/deepseek_v32/recipes/run_parallel_offline.sh b/hyper_parallel/models/deepseek_v32/recipes/run_parallel_offline.sh new file mode 100755 index 0000000000..e7a632e44f --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/recipes/run_parallel_offline.sh @@ -0,0 +1,64 @@ +#!/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. +# ============================================================================ +# +# Launch train_parallel_offline.yaml on one node with 8 NPUs: +# bash run_parallel_offline.sh /path/to/DeepSeek-V3.2-8layer-crop \ +# /path/to/dataset_text_document [trainer overrides...] +# The second argument is the Indexed Dataset prefix, without .bin/.idx. + +set -euo pipefail + +SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd) +PROJECT_ROOT=$(cd "${SCRIPT_DIR}/../../../.." && pwd) +OUTPUT_DIR=${OUTPUT_DIR:-${PROJECT_ROOT}/output/deepseek_v32} + +if [[ $# -lt 2 ]]; then + echo "Usage: $0 /path/to/DeepSeek-V3.2-8layer-crop /path/to/dataset_text_document [trainer overrides...]" >&2 + exit 1 +fi +MODEL_PATH=$(cd "$1" 2>/dev/null && pwd) || { + echo "Model directory does not exist: $1" >&2 + exit 1 +} +DATA_DIR=$(cd "$(dirname "$2")" 2>/dev/null && pwd) || { + echo "Dataset directory does not exist: $(dirname "$2")" >&2 + exit 1 +} +DATA_PATH=${DATA_DIR}/$(basename "$2") +shift 2 +if [[ ! -s "${MODEL_PATH}/config.json" ]]; then + echo "DeepSeek-V3.2 config.json is missing: ${MODEL_PATH}/config.json" >&2 + exit 1 +fi +if [[ ! -s "${DATA_PATH}.bin" || ! -s "${DATA_PATH}.idx" ]]; then + echo "Indexed Dataset is missing: ${DATA_PATH}.bin and ${DATA_PATH}.idx" >&2 + exit 1 +fi + +cd "${PROJECT_ROOT}" +mkdir -p "${OUTPUT_DIR}" +torchrun \ + --standalone \ + --nproc_per_node=8 \ + scripts/train_lm.py \ + "${SCRIPT_DIR}/train_parallel_offline.yaml" \ + --model.pretrained_model_name_or_path="${MODEL_PATH}" \ + --dataset.model_assets.tokenizer.pretrained_model_name_or_path="${MODEL_PATH}" \ + --dataset.data_path="${DATA_PATH}" \ + --dataset.data_config.data_cache_path="${OUTPUT_DIR}/data_cache" \ + --checkpoint.checkpoint_dir="${OUTPUT_DIR}/checkpoints" \ + "$@" \ + 2>&1 | tee "${OUTPUT_DIR}/run_parallel_offline.log" diff --git a/hyper_parallel/models/deepseek_v32/recipes/train_parallel_offline.yaml b/hyper_parallel/models/deepseek_v32/recipes/train_parallel_offline.yaml new file mode 100644 index 0000000000..b1eed9e260 --- /dev/null +++ b/hyper_parallel/models/deepseek_v32/recipes/train_parallel_offline.yaml @@ -0,0 +1,179 @@ +# Eight-rank DeepSeek-V3.2 training on an 8-layer crop with TP + CP + EP, FSDP, +# fused DSA, and grouped routed experts. +# +# The crop keeps 3 dense + 5 MoE layers and 16 routed experts; README.md +# describes how to create it. The data is an Indexed Dataset tokenized with the +# DeepSeek-V3.2 tokenizer. run_parallel_offline.sh fills in both paths. + +model: + _target_: hyper_parallel.models.HyperAutoModelForCausalLM.from_pretrained + pretrained_model_name_or_path: /path/to/DeepSeek-V3.2-8layer-crop + torch_dtype: bfloat16 + attn_implementation: sdpa + validate_placement: false + +model_init_dtype: float32 + +training: + train_iters: 50 + train_samples: null + eval_iters: 0 + global_batch_size: 2 + 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: 2 + cp_size: 2 + ep_size: 4 + pp_size: 1 + sequence_parallel: false + loss_parallel: true + +fsdp_config: + dp_shard_size: 2 + edp_shard_size: 2 + replicate_params: [] + mix_precision: + param_dtype: bfloat16 + reduce_dtype: float32 + cast_forward_inputs: false + reshard_after_forward: true + reshard_after_backward: true + requires_grad_sync: true + forward_prefetch_depth: 1 + backward_prefetch_depth: 1 + comm_fusion: false + +plan_overrides: + - match: + - "*.input_layernorm" + - "*.post_attention_layernorm" + - model.norm + replace: + kind: module + implementation: + _target_: hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_rms_norm + - match: "*.self_attn" + replace: + kind: module + implementation: + _target_: hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_dsa_attention + - match: "*.mlp.experts" + replace: + kind: module + implementation: + _target_: hyper_parallel.models.deepseek_v32.adapter.conversion.module_replacement.replace_deepseek_v32_grouped_experts + - 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: null + # MoE layers of the crop: layers 3-7 (first_k_dense_replace = 3). + - match: "model.layers.[3-7].mlp.forward" + when: ep + replace: + kind: method + implementation: + _target_: hyper_parallel.distributed.expert_parallel.recipes.deepseekv3_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-8layer-crop + local_files_only: true + tokenizer_type: pretokenized + vocab_size: 129280 + eod_token_id: 1 + _target_: hyper_parallel.data.text.build_dataset.build_indexed_text_dataset + data_path: /path/to/dataset_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 + data_cache_path: ./outputs/deepseek_v32/data_cache + low_level_dataset: + _target_: hyper_parallel.data.indexed.indexed_pretrain_dataset.GPTDataset + +dataloader: + _target_: hyper_parallel.data.batching.FixedBatchDataLoader + collate_fn: + _target_: hyper_parallel.data.batching.build_indexed_collate_fn + get_batch: + _target_: hyper_parallel.data.batching.TextParallelBatch + source_type: indexed + 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 + swap: + enabled: true + +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/checkpoints + restore_from: null + +debug: + check_nan_inf: false + check_dataset: null