Ascend NPU 对 Qwen3.5-9B 的分布式训练适配:CP 与 PP 并行方案详解
作者:昇腾实战派
知识地图:https://blog.csdn.net/Lumos_Lovegood/article/details/161489952
目录
1. 背景与目标
在完成 FSDP+TP 并行训练的基础上,我们进一步为 Qwen3.5-9B 模型适配了 Context Parallel (CP) 和 Pipeline Parallel (PP) 两种并行策略,并对多种分布式策略组合进行了性能对比分析。
原始训练命令 (FSDP+TP)
NGPU=8 MODULE=qwen3_5 CONFIG=qwen35_9b ./run_train.sh \
--parallelism.data_parallel_shard_degree=-1 \
--parallelism.tensor_parallel_degree=1 \
--parallelism.pipeline_parallel_degree=1 \
--training.local_batch_size=1 \
--training.seq_len=4096 \
--training.steps=100 \
--metrics.log_freq=1 \
--checkpoint.enable \
--checkpoint.initial_load_model_only
目标
- 完成 CP 适配,支持混合注意力架构与多模态输入
- 完成 PP 适配,实现 VLM pipeline split
- 生成 FSDP+TP+CP+PP 组合的性能对比数据
- 输出完整的适配文档与性能分析图表
2. 环境信息
| 组件 | 版本 |
|---|---|
| 硬件 | Atlas 800I A2 × 8 (64GB HBM/NPU) |
| 模型 | Qwen3.5-9B Dense (32 layers, dim=4096, 16 heads, 4 KV heads) |
| 注意力 | 混合: 75% GatedDeltaNet (FLA) + 25% Full Attention (FlexAttention) |
| 视觉编码器 | 27 层 ViT (SDPA, is_causal=False) |
| PyTorch | 2.13.0 |
| torch_npu | 2.13.0 |
| TorchTitan | 0.2.2(社区版本,含本地适配) |
| 序列长度 | 4096 |
| Local Batch Size | 1 |
| 数据集 | cc12m (webdataset, 多模态) |
3. Qwen3.5 架构与并行挑战
3.1 混合注意力架构
Qwen3.5-9B 采用混合注意力机制:每 4 层中 1 层使用 Full Attention (SDPA/FlexAttention),其余 3 层使用 GatedDeltaNet (FLA 线性注意力)。
Layer 0: GDN (FLA chunk_gated_delta_rule)
Layer 1: GDN
Layer 2: GDN
Layer 3: Full Attention (FlexAttention + 输出门控 + 部分 RoPE)
Layer 4: GDN
...
Layer 31: Full Attention
- Full Attention 层: 8/32 = 25% (layers 3, 7, 11, 15, 19, 23, 27, 31)
- GDN 层: 24/32 = 75%
3.2 CP 挑战
| 挑战 | 原因 | 解决方案 |
|---|---|---|
| GDN 需要完整序列 | GatedDeltaNet 维护跨序列的递归状态,不能简单按序列维度切分 | GDN 层入口 allgather 隐藏状态,处理完整序列,再重新切分输出 |
| 多模态 CP | Vision scatter 必须在 CP 切分之前完成(需要完整 token 序列定位 image token) | 分割 forward:先在完整序列上执行 vision scatter,再 CP 切分 embeddings |
3.3 PP 挑战
| 挑战 | 原因 | 解决方案 |
|---|---|---|
| VLM pipeline split | Vision encoder 必须与第一个 PP stage 共置 | pipeline_vlm 自动注入 vision_encoder 到 stage 0 |
| Stage 负载不均 | Vision encoder 增加第一个 stage 的计算量 | 调整 pipeline_parallel_first_stage_less_layers |
4. CP 适配方案
4.1 整体架构
训练器 post_dataloading_process (CP enabled, model handles CP):
├── 检测 model.cp_mesh (由 parallelize_qwen3_5 设置)
├── 跳过 token 切分 (保留完整 token 序列)
├── 连续切分 labels (dim=1)
├── 连续切分 positions / mrope_positions (dim=1)
└── 切分 attention_masks (BlockMask, Q 维度)
模型 forward (CP mode):
├── _prepare_multimodal_embeds(tokens, pixel_values, ...)
│ └── 在完整序列上执行 vision scatter
├── _cp_shard_forward_inputs(x) ← 连续切分 embeddings (dim=1)
└── for layer in layers:
├── Full Attention 层:
│ └── _cp_sdpa_forward(q, k, v, **kwargs)
│ ├── allgather K, V across CP ranks
│ └── original_forward(q, global_k, global_v)
└── GDN 层:
└── _cp_gdn_forward(x_BLD, attention_masks)
├── allgather x_BLD across CP ranks
├── original_forward(full_x, attention_masks) ← 完整序列
└── re-shard output (local CP shard)
4.2 SDPA/FlexAttention 层 CP
对 Full Attention 层的 inner_attention 模块,采用手动 K/V allgather 方式实现:
def _wrap_sdpa_for_cp(sdpa_module, cp_mesh):
original_forward = sdpa_module.forward
pg = cp_mesh.get_group()
cp_world_size = cp_mesh.size()
def _cp_sdpa_forward(q, k, v, **kwargs):
# Allgather K and V across CP ranks
k_list = [torch.empty_like(k) for _ in range(cp_world_size)]
v_list = [torch.empty_like(v) for _ in range(cp_world_size)]
dist.all_gather(k_list, k.contiguous(), group=pg)
dist.all_gather(v_list, v.contiguous(), group=pg)
global_k = torch.cat(k_list, dim=1)
global_v = torch.cat(v_list, dim=1)
# Run attention with local Q and global K/V
return original_forward(q, global_k, global_v, **kwargs)
sdpa_module.forward = _cp_sdpa_forward
设计决策:不使用 apply_cp_to_forward (DTensor CP dispatcher),原因如下:
- DTensor CP dispatcher 创建的 BlockMask 与 CP 切分后的 query 长度不匹配
- NPU 上的 FlexAttention 使用
torch.compile,与 DTensor CP dispatcher 不兼容 - 手动 allgather 更直观,且与 FlexAttention CP 路径 (
flex_cp_allgather) 方案一致
4.3 GDN 层 CP
对 GatedDeltaNet 层,使用 allgather/re-shard wrapper:
def _wrap_gdn_for_cp(gdn_module, cp_mesh):
original_forward = gdn_module.forward
pg = cp_mesh.get_group()
cp_world_size = cp_mesh.size()
def _cp_gdn_forward(x_BLD, attention_masks=None):
# Allgather hidden state across CP ranks
tensor_list = [torch.empty_like(x_BLD) for _ in range(cp_world_size)]
dist.all_gather(tensor_list, x_BLD.contiguous(), group=pg)
full_x = torch.cat(tensor_list, dim=1)
# Run GDN on full sequence (correct recurrent state)
out_full = original_forward(full_x, attention_masks)
# Re-shard output to local CP shard
local_rank = cp_mesh.get_local_rank()
shard_size = full_x.shape[1] // cp_world_size
start = local_rank * shard_size
return out_full[:, start:start+shard_size, ...].contiguous()
gdn_module.forward = _cp_gdn_forward
代价:GDN 层不减少激活显存(需要完整序列),但 Full Attention 层仍受益于 CP 的 K/V allgather。
4.4 多模态 CP
# Qwen35Model.forward (CP mode)
def forward(self, tokens, *, pixel_values=None, ...):
rope_positions = mrope_positions if mrope_positions is not None else positions
if self.tok_embeddings is not None:
x = self._prepare_multimodal_embeds(tokens, pixel_values=...) # 完整序列
if self.cp_mesh is not None and self.cp_mesh.size() > 1:
x = self._cp_shard_forward_inputs(x) # CP 切分 embeddings
else:
x = tokens # PP 后续 stage: 已切分
for layer in self.layers.values():
x = layer(x, attention_masks, rope_positions)
...
4.5 训练器集成
# trainer.py post_dataloading_process (CP enabled, model handles CP)
if model_handles_cp:
# 跳过 token 切分,保留完整序列供 vision scatter
# 切分 labels, positions, mrope_positions, attention_masks
labels = _cp_contiguous_shard(labels)
for pos_key in ("positions", "mrope_positions"):
extra_kwargs[pos_key] = _cp_contiguous_shard(extra_kwargs[pos_key])
# 切分 BlockMask (Q 维度)
extra_kwargs["attention_masks"] = cp_shard(cp_mesh, (), attn_masks, ...)
5. PP 适配方案
5.1 pipeline_vlm 接入
Qwen3.5 在 __init__.py 中已注册 pipeline_vlm 作为 pipelining_fn:
# torchtitan/models/qwen3_5/__init__.py
return ModelSpec(
name="qwen3_5",
parallelize_fn=parallelize_qwen3_5,
pipelining_fn=pipeline_vlm, # ← PP 入口
...
)
5.2 pipeline_vlm 工作流程
pipeline_vlm(model, parallel_dims, parallelism, model_config, ...):
├── 生成 LLM stage split FQN 列表 (tok_embeddings, layers.*, norm, lm_head)
├── 注入 vision_encoder 到第一个 stage 的 FQN 列表
└── pipeline_llm(model, ...):
├── _pipeline_module_split() → 分割模型为 PP stages
├── 对每个 stage 调用 parallelize_qwen3_5() (TP, AC, compile, FSDP)
└── _build_pipeline_schedule() → 1F1B 调度
5.3 FSDP 与 PP 的交互
# parallelize_qwen3_5 中传递 pp_enabled:
apply_fsdp_to_decoder(
model,
dp_mesh,
pp_enabled=parallel_dims.pp_enabled, # ← PP 时不 reshard after forward
...
)
apply_fsdp_to_vision_encoder(
model.vision_encoder,
dp_mesh,
pp_enabled=parallel_dims.pp_enabled, # ← PP 时不 reshard after forward
...
)
PP 时 pp_enabled=True → FSDP 在 forward 后不 reshard 参数(因为 pipeline schedule 需要跨 stage 传递激活)。
5.4 PP + CP 联合
- 第一个 PP stage 拥有
tok_embeddings+vision_encoder,其 forward 执行 CP 切分 - 后续 PP stage 接收已切分的激活,不重复 CP 切分
- 训练器的 loss mesh 包含 DP+CP 维度,正确归约梯度
6. 代码修改清单
| 文件 | 修改内容 |
|---|---|
models/qwen3_5/parallelize.py | 移除 CP NotImplementedError;新增 _wrap_gdn_for_cp (GDN allgather CP);新增 _wrap_sdpa_for_cp (SDPA/Flex K/V allgather CP);新增 _apply_cp_to_qwen35 (混合注意力 CP 包装);设置 model.cp_mesh |
models/qwen3_5/model.py | 新增 cp_mesh 属性;forward 中 _prepare_multimodal_embeds 后调用 _cp_shard_forward_inputs 切分 embeddings;PP 后续 stage 不重复切分 |
torchtitan/trainer.py | post_dataloading_process 检测 model.cp_mesh,跳过 token 切分,切分 labels/positions/mrope_positions/attention_masks |
scripts/benchmarks/qwen35_cp_pp_benchmark.sh | 新增:FSDP+TP+CP+PP 组合基准测试脚本 |
scripts/benchmarks/parse_qwen35_cp_pp_benchmark.py | 新增:基准测试结果解析和图表生成 |
scripts/benchmarks/gen_cp_pp_comparison.py | 新增:综合性能对比图表生成 |
7. 性能对比
7.1 测量结论 (FSDP+TP, 已有基准)
实测结果显示,在 FSDP 与 TP 的组合中,FSDP-only(FSDP8+TP1)的全局吞吐与 MFU 最优;引入 TP 后,随 TP 度数增大,全局吞吐与 MFU 呈下降趋势,单卡显存占用随之下降。
7.2 CP/PP 数据 (估算)
CP/PP 组合数据基于架构层面分析估算,仅用于趋势参考,不作为实测数据发布。总体趋势:FSDP-only 吞吐最高;CP 因 GDN 层(占比 75%)需要完整序列,allgather 通信开销较大、收益有限;PP 引入 pipeline bubble 开销;TP 与 CP/PP 叠加时通信开销进一步累积,吞吐继续下降。
8. CP/PP 性能分析
8.1 CP 性能特征
通信开销分析:
| 层类型 | 占比 | CP 通信 | 计算节省 | 净效益 |
|---|---|---|---|---|
| Full Attention (SDPA) | 25% | K/V allgather (每层 2 次) | 激活显存显著下降 | 长序列场景收益明显 |
| GDN | 75% | 隐藏状态 allgather (每层 1 次) | 无(需要完整序列) | 以通信开销为主 |
CP=2 估算:
- 吞吐低于 FSDP-only,GDN 层(75%)的 allgather 通信是主要开销来源
- 显存方面,SDPA 层(25%)的激活显存明显下降,整体显存收益有限
适用场景:CP 在长序列时收益增加,因为:
- SDPA 层的 K/V allgather 通信量与序列长度成正比,但计算量随序列长度超线性增长 → 通信/计算比降低
- GDN 的 allgather 开销与序列长度成正比,计算量也与序列长度成正比 → 通信/计算比不变
8.2 PP 性能特征
Bubble 开销分析:
1F1B 调度的 bubble 比例满足:
bubble_ratio = (stages - 1) / (stages - 1 + microbatches)
即 bubble 比例随 PP 度数增加而上升,随微批次数增加而下降。
PP=2 估算:
- 吞吐低于 FSDP-only,开销来自 bubble、FSDP 通信与 vision encoder 负载不均
- 显存方面,模型参数分片使显存占用明显下降
8.3 组合策略对比
| 策略 | 通信开销 | 计算效率 | 显存效率 | 适用场景 |
|---|---|---|---|---|
| FSDP only | 最低 (all-gather + reduce-scatter) | 最高 | 中 | 显存可容纳时首选 |
| FSDP+TP | 中 (TP all-reduce 逐层) | 中 | 高 (激活减半) | 单层显存不足 |
| FSDP+CP | 高 (GDN allgather) | 低-中 | 中 (SDPA 层减半) | 长序列 |
| FSDP+PP | 中 (bubble + 激活传递) | 低-中 | 高 (模型减半) | 大模型 |
| FSDP+TP+CP | 最高 | 低 | 高 | 超大模型 + 长序列 |
| FSDP+CP+PP | 高 | 低 | 最高 | 极限显存场景 |
8.4 策略选择建议
- 首选 FSDP-only:显存可容纳时,通信开销最低,吞吐最高
- 次选 FSDP+CP:长序列场景,CP 减少激活显存(但 Qwen3.5 的 GDN 限制收益)
- 次选 FSDP+PP:大模型场景,PP 减少模型显存(但有 bubble 开销)
- 避免 TP:除非单层显存不足,TP 的逐层 all-reduce 开销大
- 多维组合谨慎使用:CP+PP 或 TP+CP+PP 的通信开销叠加,需实测验证
9. 已知问题与限制
9.1 FlexAttention/Triton 兼容性
问题:Qwen3.5 默认使用 attn_backend="flex" (FlexAttention),FlexAttention 内部使用 torch.compile,在特定版本组合下,NPU 环境 Triton autotuning 阶段可能触发 TypeError: unhashable type: 'list',影响相关训练配置(包括 FSDP-only)的运行,当前可通过改选 SDPA/Varlen Attention 后端规避,后续版本持续优化。
解决方案:
- 方案 A:重新应用 SDPA backend 修改(之前的 benchmark 已验证可行)
- 方案 B:修复 Triton autotuning 的 unhashable config 问题
- 方案 C:使用
attn_backend="varlen"(VarlenAttention, 不使用 FlexAttention)
9.2 CP allgather 与 Activation Checkpointing 的同步问题
问题:GDN/SDPA 层的 CP allgather 在激活重计算(activation checkpoint recomputation)路径中可能与其他 rank 不同步,引发集合通信超时;该现象与特定版本组合相关,可结合上述方案规避。
解决方案:
- 方案 A:对 CP 层禁用 activation checkpointing
- 方案 B:将 CP allgather 移到 checkpoint 边界外
- 方案 C:使用
use_reentrant=True的 checkpoint(可能解决同步问题)
9.3 CP BlockMask 切分
问题:FlexAttention 的 BlockMask 需要在 CP 切分时同步切分 Q 维度,否则 shape 不匹配。
当前实现:使用 cp_shard(load_balancer_type=None) 进行连续切分。
说明:当前采用连续切分方式;head-tail 交错切分(常用于平衡计算负载)可作为后续优化方向。
更多推荐




所有评论(0)