在 06 3D 并行深度 中,我们从显存、通信量与流水线气泡三个数学约束拆解了 DP / TP / PP / SP / CP / EP / ZeRO 的原理(跨节点网络带宽与 NCCL 调优详见 04 互联与网络)。当参数跨过 \(1\text{B}\) 量级,生产团队几乎不再重复手写原生通信逻辑,而是站在 Megatron-Core、DeepSpeed、PyTorch FSDP2 / TorchTitan 等成熟底座之上。
本篇不再重复基础并行公式,而是直接下潜到训练框架的内部设计、张量切分机制、优化器与检查点实现、配置陷阱以及各自在生态演进中的边界:
- Megatron-Core:
ModuleSpec组合模式、f/g成对autograd.Function、DistributedOptimizer、dist_checkpointing与 MCore MoE / DeepEP 调度。 - DeepSpeed:ZeRO-1/2/3/ZeRO++ 精确通信差异、CPU/NVMe Offload 配置依赖与 Ulysses 布局转置。
- PyTorch FSDP2 & TorchTitan:从
FlatParameter到原生DTensor二维切分、Symmetric Memory Async-TP、FlexAttention与torchaoFP8。 - 平台与国产栈:NVIDIA NeMo
2.0(
nemo-run+Megatron-Bridge)、Colossal-AI、MindSpeed、InternEvo、PaddleNLP / PaddleFleetX、veScale 与 Ray Train。
一、训练框架全景:三条技术路线与核心对比
训练框架的本质,是在尽量隐藏分布式复杂度的前提下,把 PyTorch 的计算图与状态张量映射为多卡上的集合通信与分段调度。围绕「侵入性 vs 极限硬件利用率」,业内演化出三条主线:
- PyTorch 原生路线(DDP → FSDP1 → FSDP2 /
TorchTitan):Meta 主导。早期 FSDP1 用
FlatParameter将模块参数压扁切分;2024 年起的 FSDP2 基于DTensor按参数原生切分,并与parallelize_module(TP)、torch.distributed.pipelining(PP)及torch.compile组合使用。 - NVIDIA 垂直协同路线(Megatron-LM → Megatron-Core → NeMo 2.0):自顶向下围绕 Transformer / MoE / Mamba 结构与 CUDA 算子栈协同设计(cuBLASLt、Transformer Engine、FlashAttention、NVSHMEM / DeepEP),牺牲一部分动态图自由度换取极高的计算-通信重叠上限。
- Microsoft 零侵入显存路线(DeepSpeed
ZeRO):以
deepspeed.initialize接管原生nn.Module与 JSON 配置,凭借 ZeRO-1/2/3、CPU/NVMe Offload(ZeRO-Offload / Infinity)与通信压缩(ZeRO++)覆盖从单机微调到多机训练的广泛场景。
1.1 主流训练框架能力对比
| 维度 | PyTorch FSDP2 | Megatron-Core | DeepSpeed | TorchTitan | Colossal-AI |
|---|---|---|---|---|---|
| 维护主体 | Meta / PyTorch | NVIDIA | Microsoft | Meta / PyTorch | 潞晨科技 |
| 核心并行组合 | DP + ZeRO-3 / HSDP(可叠 TP/PP) | TP + SP + PP + CP + EP + ZeRO-1 | ZeRO-1/2/3 + EP + Ulysses | FSDP2 + TP + PP + CP | ZeRO(Gemini)+ 1D/2D/3D TP |
| 模型代码侵入性 | 低(就地 fully_shard) |
高(须适配 ModuleSpec / 层协议) |
极低(JSON + Engine 包装) | 中(参考模型定义) | 中(Booster 插件体系) |
| CPU / NVMe Offload | 支持(CPU Offload) | 实验性激活 offload | 成熟(ZeRO-Offload / Infinity) | 无 | 支持(Gemini 异构卸载) |
| MoE 原生优化 | 需外部或手工接入 | 内置 GroupedMLP + DeepEP
调度 |
内置 DeepSpeed-MoE | 实验/持续演进中 | 内置基础 MoE |
| FP8 支持路径 | 通过 torchao +
torch.compile |
成熟(Transformer Engine 1.x/2.x) | 实验性支持(MS-AMP / TE 集成) | torchao 原生转换器 |
实验性支持 |
| 长上下文并行 | DTensor / Ring CP |
SP + Ring CP | Ulysses All-to-All | Ring CP(Llama 模型模板) | 序列并行插件 |
| 运维与源码门槛 | 低–中 | 高 | 低–中 | 中 | 中 |
上表侧重架构职责与生态支持现状,不脱离具体硬件代际、集群规模与模型形状直接对比无限定条件的 MFU 榜单。
1.2 其他重要生态项目
| 框架 / 工具链 | 机构 / 社区 | 工程定位 |
|---|---|---|
NeMo 2.0(nemo-run +
Megatron-Bridge) |
NVIDIA | 基于 Megatron-Core 的端到端生产平台、配方管理与 HF 双向转换桥 |
| HAI-LLM(含开源组件 DualPipe / DeepEP) | DeepSeek | 自研高性能训练栈,已开源 MoE 双向流水线与通信内核 |
| InternEvo | 上海 AI Lab | 面向 InternLM 系列的开源分布式训练框架(支持长上下文与异步检查点) |
| MindSpeed | 华为 | 面向昇腾(Ascend + CANN / HCCL)生态的 Megatron 移植与加速库 |
| PaddleNLP / PaddleFleetX | 百度 | 飞桨生态大模型并行套件 |
| veScale | 字节跳动 | 基于 DTensor 思想的自动化多维并行框架 |
| Ray Train / Axolotl / LLaMA-Factory | 社区 | 分布式任务编排(Ray)与 SFT/LoRA 微调工作流封装 |
| Pax / MaxText | JAX / XLA + TPU 原生训练参考栈 |
二、Megatron-Core 内部架构:ModuleSpec、并行原语与 MoE 调度
早期 Megatron-LM
把模型定义、训练循环和脚本参数耦合在一起,下游团队只能 hard
fork。2023 年 NVIDIA 将核心原语拆分为可独立安装的
megatron.core(MCore),把重心从「跑通官方脚本」转向「作为底层库嵌入各家训练平台」。其目录与职责划分清晰:
megatron/core/transformer/:ModuleSpec、TransformerLayerSpec、Attention、MLP 与 Norm 抽象;megatron/core/tensor_parallel/:ColumnParallelLinear、RowParallelLinear及序列并行通信原语;megatron/core/pipeline_parallel/:1F1B、Interleaved 1F1B 调度(Zero Bubble 调度在开源衍生分支如sail-sg/zero-bubble-pipeline-parallelism中通过--enable-zero-bubble/--zero-bubble-v-schedule提供,MCore 内部则支持通用调度编排);megatron/core/transformer/moe/:MoELayer、GroupedMLP与多模式TokenDispatcher;megatron/core/optimizer/&distributed/:DistributedDataParallel参数桶与DistributedOptimizer;megatron/core/dist_checkpointing/:支持按不同并行拓扑离线/在线重切分(resharding)的分布式检查点格式。
2.1
ModuleSpec 与可替换层规范
Megatron-Core 最核心的软件工程改造是
ModuleSpec(TransformerLayerSpec)。它像一份声明式蓝图,允许在不修改
GPTModel 主干代码的前提下,将同一层内的 Linear
/ Norm / Attention 在 纯
PyTorch/本地算子(get_gpt_layer_local_spec)与
NVIDIA Transformer Engine 融合 FP8
算子(get_gpt_layer_with_transformer_engine_spec)之间无缝切换。例如启用
TE 时,LayerNorm 与列切线性层会被自动替换并融合为
TELayerNormColumnParallelLinear,直接消除中间显存读写并打开
--tp-comm-overlap 通道。
2.2
ColumnParallel / RowParallel 的
f/g 伴随算子对
理解 Megatron TP 实现时,千万不要以为在
forward() 里直接调一句
dist.all_reduce(out) 就完事了——PyTorch
的默认 autograd
引擎无法自动把集合通信反传成正确的梯度同步(如果前向没有通信,反向却需要对输入梯度求和;如果前向做了
AllReduce,反向则应当直接透传梯度)。
Megatron-Core 通过成对自定义的
torch.autograd.Function(论文记为共轭函数
\(f\) 与 \(g\))保证前向与反向梯度数学严格等价:
ColumnParallelLinear入口处的 \(f\)(_CopyToModelParallelRegion):前向为恒等映射(Identity),反向执行AllReduce(把各个列切分片传回的输入梯度 \(\nabla_X L = \sum_i \nabla_{Y_i} L \cdot A_i^\top\) 累加);RowParallelLinear出口处的 \(g\)(_ReduceFromModelParallelRegion):前向执行AllReduce汇总局部矩阵乘结果,反向为恒等映射(所有 rank 直接拿到相同的完整输出梯度去乘各自的行切分片 \(B_i\))。
import torch
import torch.distributed as dist
class _CopyToTPRegion(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor, group) -> torch.Tensor:
ctx.group = group
return x # Identity in forward
@staticmethod
def backward(ctx, grad_out: torch.Tensor):
grad = grad_out.clone()
dist.all_reduce(grad, group=ctx.group) # Sum input grads across TP ranks
return grad, None
class _ReduceFromTPRegion(torch.autograd.Function):
@staticmethod
def forward(ctx, x: torch.Tensor, group) -> torch.Tensor:
out = x.clone()
dist.all_reduce(out, group=group) # Sum partial matmul outputs in forward
return out
@staticmethod
def backward(ctx, grad_out: torch.Tensor):
return grad_out, None # Identity in backward开启 --sequence-parallel 后,\(f\) 与 \(g\) 自动切换为
_GatherFromSequenceParallelRegion(前向
AllGather、反向 ReduceScatter)与
_ReduceScatterToSequenceParallelRegion(前向
ReduceScatter、反向
AllGather),使 LayerNorm、Dropout
与残差张量的激活显存直接降至 \(1/\text{TP}\)。
2.3
Context Parallel(Ring Attention)、非均匀 PP 与
DistributedOptimizer
- Context Parallelism(CP):Megatron-Core 的 CP 基于 Ring Attention 机制实现——每个 rank 固定持有序列的局部查询块 \(Q_i\),沿环形进程组 P2P 传递 \((K_j, V_j)\) 分片,利用 online softmax rescaling 在本地迭代累加精确输出(并非先把所有注意力的输出 all-gather 再拼接),支持与因果 Zig-Zag 负载均衡及 FP8 叠加。
- 非均匀流水线与
ModelParallelConfig:并行与通信策略统一收口在ModelParallelConfig(TransformerConfig继承自该配置类)。针对首尾 stage 因 Embedding / LM Head / MTP 导致的显存与算力偏斜,现代 Megatron-Core 使用--decoder-first-pipeline-num-layers、--decoder-last-pipeline-num-layers或声明式的--pipeline-model-parallel-layout。 - Megatron
DistributedOptimizer:等价于针对静态状态优化的 ZeRO-1,但切分粒度更彻底——它沿着 DP 维度切分全部 \(12\Psi\) 优化器状态(不仅切 FP32 一阶矩 \(m\) 与二阶矩 \(v\),也同时切分 FP32 master weights),配合连续ParamAndGradBuffer分桶将静态显存从 \(16\Psi\) 降至 \(4\Psi + \frac{12\Psi}{D}\)。默认配置支持在 DP 组内用 FP32 归约梯度(--accumulate-allreduce-grads-in-fp32/grad_reduce_in_fp32)保证数值累加无漂移,而层内 TP 通信保持计算精度(BF16)。
2.4
MCore MoE、DeepEP 分发器与
dist_checkpointing
在 MoE 支持上,Megatron-Core 把 MoELayer
拆解为 Router、Token Dispatcher 与
GroupedMLP:
- Token
Dispatcher:提供基于局部填充收集的
allgather模式(适合小规模 TP+EP)、标准alltoall模式,以及接入 DeepEP(DeepSeek 开源的定制通信库)的flex分发器——结合 NVSHMEM / RDMA 实现高吞吐(低延迟)非对称 FP8 dispatch 与 BF16 combine 调度。 dist_checkpointing:支持异步持久化与拓扑无关重切分。你可以用TP=8, PP=4保存训练中间态,在扩容或缩容后直接用TP=4, PP=8恢复训练,彻底解耦检查点文件与集群并行拓扑(原理详见 10 Checkpoint 与故障容忍)。
三、DeepSpeed 深度:ZeRO 状态切分、Offload 与 Ulysses
3.1 ZeRO-1/2/3 与 ZeRO++ 的通信精确账
ZeRO 家族沿着 DP 维渐进切分状态(详细推导表见 06 §3):
- ZeRO-1:按 DP 切分全部 \(12\Psi\) 优化器状态(master
weight + \(m\) + \(v\)),单卡静态显存降至 \(4\Psi +
\frac{12\Psi}{D}\);每步先做梯度
ReduceScatter再AllGather更新后权重,总逻辑通信量与 DDP 同为 \(2\Psi\)。 - ZeRO-2:在 ZeRO-1 基础上进一步按 DP
切分 BF16 梯度(静态显存降至 \(2\Psi +
\frac{14\Psi}{D}\));由于本来就执行「反向梯度
ReduceScatter+ 更新后权重AllGather」,ZeRO-2 的每步逻辑通信量依然保持 \(2\Psi\),并没有比 ZeRO-1 或 DDP 多出通信总量。 - ZeRO-3:进一步切分模型参数本身(静态显存降至
\(\frac{16\Psi}{D}\)),但前向与反向均需按层即时
AllGather权重,使逻辑通信量升至 \(3\Psi\)(\(1.5\times\) DDP)。 - ZeRO++(Wang et al., ICLR
2024):针对跨机带宽受限下 ZeRO-3 的
AllGather瓶颈,引入权重 INT8 量化拉取(qwZ)、节点内权重冗余副本仅做机内拉取(hpZ)与梯度量化归约(qgZ),在低互联带宽下大幅压低跨节点流量。
3.2 ZeRO-Offload 与 ZeRO-Infinity 的配置真相
- ZeRO-Offload(Ren et al., USENIX ATC 2021):将优化器状态与计算下放到主机 CPU DRAM,适合单机多卡低成本微调。
- ZeRO-Infinity(Rajbhandari et al., SC 2021):借助异步 NVMe I/O 引擎支持将参数、梯度与优化器同时卸载到 NVMe SSD 阵列——论文实测在 \(512\) 张 V100(\(64\) 节点)上可扩展至 \(32\text{T}\) 参数,在单台 \(16\) 卡 DGX-2 节点上可跑通 \(1\text{T}\) 参数(注意并非单机 32T),代价值得正视:PCIe 与 SSD 带宽制约下吞吐远低于纯 HBM 训练,几乎只用于极端显存受限的微调或消融验证。
工程实践中,在 DeepSpeed JSON 里配置 CPU/NVMe Offload
必须同时声明兼容 CPU 步进的
"optimizer"(如 AdamW,配合
DeepSpeedCPUAdam)以及 NVMe 所需的
"aio" 异步 I/O 引擎块,缺一不可:
{
"train_micro_batch_size_per_gpu": 2,
"gradient_accumulation_steps": 16,
"bf16": { "enabled": true },
"optimizer": {
"type": "AdamW",
"params": { "lr": 1e-4, "betas": [0.9, 0.95], "weight_decay": 0.1 }
},
"zero_optimization": {
"stage": 3,
"offload_optimizer": { "device": "cpu", "pin_memory": true },
"offload_param": { "device": "nvme", "nvme_path": "/mnt/nvme", "buffer_count": 5 },
"overlap_comm": true,
"contiguous_gradients": true,
"reduce_bucket_size": 5e8,
"stage3_prefetch_bucket_size": 5e8,
"stage3_param_persistence_threshold": 1e6
},
"aio": {
"block_size": 1048576,
"queue_depth": 8,
"thread_count": 1,
"single_submit": false,
"overlap_events": true
}
}3.3 DeepSpeed-Ulysses 与 DeepSpeed-MoE
DeepSpeed-Ulysses(Jacobs et al., 2023) 的精髓是在计算注意力前后插入两次轻量级 All-to-All 完成布局转置:将 \((B, S/P, H)\) 沿序列维度切分的激活转置为 \((B, S, H/P)\) 沿注意力头维度切分的张量,在本地用 FlashAttention 计算所辖头的完整序列后,再转回 \((B, S/P, H)\)。单次 All-to-All 通信量为 \(\mathcal{O}\left(\frac{B S H}{P}\right)\)(共 4 个阶段合计随 \(S/P\) 扩展,详细与 Ring Attention / USP 的互补边界见 06 §2.5 与 16 长上下文工程)。
尽管微软近期将部分核心贡献重心转向 PyTorch FSDP2,DeepSpeed 在 NVMe Offload、Hugging Face Trainer 一键集成 以及 Ulysses 长序列微调 上仍是不可替代的工程工具箱。
四、PyTorch FSDP2 与 TorchTitan:基于 DTensor 的可组合栈
4.1 从
FlatParameter(FSDP1)到原生
DTensor(FSDP2)
PyTorch 1.11 推出的 FSDP1 把一个 wrapped module
内所有参数拍平拼接成一个巨大的 1D FlatParameter
再切分,带来了诸多痛点:难以对单参数设置不同学习率/冻结(如
LoRA)、难以与 TP
二维张量切分自然组合、torch.compile
图切分频繁,以及 FULL_STATE_DICT
易在保存时爆主机内存。
PyTorch 2.4+ 推出、2.6+ 趋于成熟的
FSDP2(公开入口
torch.distributed.fsdp.fully_shard)
彻底弃用了
FlatParameter,让每个权重保持独立张量并表达为原生的
DTensor:
- 二维切分正交组合:FSDP2 默认沿着第 0
维(
Shard(0))跨 DP 组切分参数;当模型同时启用 PyTorch TP 时,ColwiseParallel按输出维(第 0 维)切分线性层权重、RowwiseParallel按输入维(第 1 维)切分线性层权重——两者自动组合成 2DDTensor放置策略,且所有参数独立保留原始命名结构。 - 可控重释放(
reshard_after_forward):默认True(等价 ZeRO-3,前向算完立即释放完整权重分片);若设为False(或只对 root 设False),前向后保留完整权重直至反向结束,行为切换为类似 ZeRO-2 的低通信模式。 - Async-TP 与 Symmetric Memory:借助
torch.distributed._symmetric_memory与 NVLink 直接内存访问,PyTorch 原生栈已支持在torch.compile编译图内将 TP 的AllGather/ReduceScatter与矩阵乘按微块异步流水重叠(Async-TP),不再只能依赖 Megatron + TE。 - 零爆内存初始化与精确掩码:面对超过单机内存的大模型,应结合
with torch.device("meta"):构建骨架后再按分片逐层物化权重(to_empty+reset_parameters),配合torch.float32模型初始化 +MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)保持 FP32 master weight,并在损失函数处显式忽略 padding token(ignore_index=-100)。
下图对比了 FSDP1 FlatParameter、FSDP2 原生
2D DTensor 与 Megatron-Core
ModuleSpec 分层栈在内部抽象上的本质差异:
4.2 TorchTitan:生产验证的 PyTorch 原生 4D 参考栈
pytorch/torchtitan 起初定位为「5000
行级代码量演示 Llama 3 4D 并行」的官方参考实现,整合了
FSDP2 + TP (Async-TP) + PP
(torch.distributed.pipelining) + CP (Ring
Attention) + FlexAttention +
torch.compile + torchao
FP8。需要修正一个过时印象:TorchTitan
早已不再只是教学玩具,Meta
及多个开源研究团队已在数千卡规模的真实集群上用它验证 Llama 3
/ MoE 预训练配方。
现代 TorchTitan 通过 [model] 下的
converters 列表挂载 torchao Float8
转换器(早期为 "float8",新版细分路径为
"quantize.linear.float8"),并由
[compile] 控制 torch.compile
算子融合:
[model]
name = "llama3"
flavor = "70B"
converters = ["quantize.linear.float8"]
[parallelism]
data_parallel_replicate_degree = 1
data_parallel_shard_degree = 64
tensor_parallel_degree = 8
pipeline_parallel_degree = 2
context_parallel_degree = 1
[training]
seq_len = 8192
mixed_precision_param = "bfloat16"
[compile]
enable = true
[quantize.linear.float8]
recipe_name = "tensorwise"
enable_fsdp_float8_all_gather = true五、NeMo 2.0、Colossal-AI 与多生态训练栈
5.1
NVIDIA NeMo 2.0:nemo-run 与
Megatron-Bridge
早期 NeMo 1.x 重度依赖 PyTorch Lightning + 多层嵌套 YAML(Hydra)命令行覆写,维护和二次开发极其繁琐。NeMo 2.0 进行了彻底重构,转向 Python-first「代码即配置」:
Megatron-Bridge:打通 Hugging Face 模型与 Megatron-Core 并行格式的双向转换与训练桥接(例如AutoBridge直接将 HF 的 Llama / Qwen / DeepSeek 权重映射为 MCore TP/PP/EP 分片并在训练后导出回 HF)。nemo-run:纯 Python 作业编排库,同一套配置可无缝提交到本地多卡、Slurm 或 Kubernetes 集群,并用于训练 NVIDIA 自研开源模型家族(如 Nemotron-4 340B、Llama-3.1-Nemotron 与混合 Mamba-Transformer 架构的 Nemotron-H)。
各组件的依赖流向统一如下(底层库向上层产品与模型输出):
flowchart TB
CORE["Megatron-Core (pip Library: TP / PP / SP / CP / EP / DistOptim)"] -->|"examples & research"| LM["Megatron-LM (Reference Scripts)"]
CORE -->|"recipes & HF conversion"| BRIDGE["Megatron-Bridge & NeMo 2.0 (nemo-run)"]
BRIDGE -->|"trains & releases"| NEMO_MOD["Nemotron Family (Nemotron-4 340B / Llama-3.1-Nemotron / Nemotron-H)"]
5.2 Colossal-AI、国产栈与公开工程线索分层
- Colossal-AI:主打
Booster插件接口与自研Gemini异构内存管理器(动态块驱逐与 CPU Offload),在中小规模科研与微调场景友好;但在超大规模定制重叠调度上不如直接修改 MCore 灵活。 - 国产芯片与云生态:昇腾生态主要通过 MindSpeed(结合 CANN 与 HCCL)承接 Megatron 编程模型;百度生态提供 PaddleNLP / PaddleFleetX;上海 AI Lab 开源 InternEvo;字节跳动体系采用自研 veScale 与 Ray Train 类弹性编排。
- 公开材料证据边界:GPT-3 / OPT / BLOOM /
GPT-NeoX 明确记载了 Megatron 或 Megatron-DeepSpeed(如 BLOOM
384 张 A100 使用
TP=4, PP=12, DP=8)的历史路线;Llama 3 报告公开使用了 TP + PP + CP + FSDP 组合;DeepSeek-V3 披露了 HAI-LLM 配合开源的 DualPipe / DeepEP 组件;而其他未公开底层仓库的闭源商业模型,本文不将社区猜测当作既定事实。
六、工程选型矩阵与边界解读
选型绝不是「看谁跑分榜高」,而是把模型参数量、工作负载形态(预训练 vs 微调 vs RL)、集群互连拓扑与团队内核研发人数放进同一张决策图里权衡:
解读这张矩阵时,必须守住四条工程边界(否则图上的推荐会变成踩坑根源):
- TP 严格锁死在机内 NVLink/HCCS
域内:永远保持
TP <= 单节点 GPU 数(例如 \(8\)),一旦需要跨节点扩展模型内存,应当切给 PP 或 FSDP/ZeRO-3,绝不让 TP 跨出高速机内互联。 - PP 的启用门槛取决于单节点显存容量而非盲目的 128
卡红线:一旦模型权重 + 优化器 +
激活无法塞进单机(例如 \(70\text{B}\) 稠密模型在 \(8 \times 80\text{GB}\) 集群上做
\(16\text{–}32\)
卡预训练),
TP=8, PP=2/4就已经具备实操价值,而不是等到 \(128\) 卡才考虑 PP;而 \(< 10\text{B}\) 规模在现代 \(80\text{GB}\) 卡上通常仅用 FSDP2 即可吃满。 - SFT / LoRA 与 Pre-train 分道扬镳:Pre-train 追求持续数周的稳定极值吞吐,团队有动力啃 Megatron-Core;SFT/LoRA 周期短、结构多变,DeepSpeed ZeRO-3 Offload 或 FSDP2 + PEFT 的开发效率收益远大于几个百分点的算子优化。
- 跨框架迁移的真正壁垒是 Checkpoint
转换:FSDP2 的 PyTorch DCP 与 Megatron-Core 的
dist_checkpointing并不原生兼容,切换框架往往意味着通过 Hugging Facesafetensors作为中间枢纽做全量权重重映射与精度回归校验,开训前务必锁定主线栈。
七、实操对比:骨架代码、显存精算与排障清单
7.1 7B BF16 显存账本(纠正优化器切分口径)
以 \(\Psi = 7\text{B}\) 稠密模型、BF16 计算与 FP32 master weights(静态总额 \(16\Psi = 112\text{ GB}\),其中权重 \(14\text{ GB}\) + 梯度 \(14\text{ GB}\) + FP32 优化器状态 \(84\text{ GB}\))为例,对比 \(8\) 卡配置:
- DDP:每卡 \(112\text{ GB}\) 静态 + 激活 → 直接超出 \(80\text{ GB}\) 显存。
- ZeRO-1 / Megatron
DistributedOptimizer(DP=8):由于全部 \(84\text{ GB}\) 优化器状态(FP32 master + \(m\) + \(v\))均按 \(8\) 份切分,每卡优化器状态降至 \(84 / 8 = 10.5\text{ GB}\),加上本地完整权重 \(14\text{ GB}\) 与梯度 \(14\text{ GB}\),每卡静态显存合计 \(38.5\text{ GB}\)(为激活留出近 \(40\text{ GB}\) 空间)。 - ZeRO-3 /
FSDP2(
DP=8):静态显存按 \(8\) 份均摊至 \(112 / 8 = \mathbf{14.0\text{ GB}}\),代价值得注意——每层前反向需多出共计 \(3\Psi\) 的参数AllGather与梯度ReduceScatter。
7.2 三大框架训练代码骨架对照
(1)PyTorch 2.6+ FSDP2 骨架(含
torch.float32 主权重、-100 Padding
掩码与 meta 提示)
import os
import torch
import torch.distributed as dist
from torch.distributed.fsdp import MixedPrecisionPolicy, fully_shard
from transformers import AutoConfig, AutoModelForCausalLM
def run_fsdp2_skeleton(dataloader):
dist.init_process_group("nccl")
local_rank = int(os.environ.get("LOCAL_RANK", 0))
torch.cuda.set_device(local_rank)
# For models > single-GPU RAM, initialize inside `with torch.device("meta"):` and materialize per shard.
cfg = AutoConfig.from_pretrained("meta-llama/Llama-3.1-8B")
model = AutoModelForCausalLM.from_config(cfg, torch_dtype=torch.float32).cuda()
mp = MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32)
for layer in model.model.layers:
fully_shard(layer, mp_policy=mp)
fully_shard(model, mp_policy=mp)
optim = torch.optim.AdamW(model.parameters(), lr=1e-4, betas=(0.9, 0.95), weight_decay=0.1)
model.train()
for batch in dataloader:
ids = batch["input_ids"].cuda(non_blocking=True)
attn_mask = batch["attention_mask"].cuda(non_blocking=True)
# Mask out pad tokens with -100 so loss ignores padding positions
labels = ids.masked_fill(attn_mask == 0, -100)
loss = model(input_ids=ids, attention_mask=attn_mask, labels=labels).loss
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
optim.step()
optim.zero_grad(set_to_none=True)
dist.destroy_process_group()(2)Megatron-Core GPTModel
骨架(完整 transformer_layer_spec 与
ModelType)
from functools import partial
import torch
from megatron.core.enums import ModelType
from megatron.core.models.gpt.gpt_model import GPTModel
from megatron.core.models.gpt.gpt_layer_specs import get_gpt_layer_with_transformer_engine_spec
from megatron.core.transformer.transformer_config import TransformerConfig
from megatron.training import pretrain
def model_provider(pre_process: bool = True, post_process: bool = True) -> GPTModel:
cfg = TransformerConfig(
num_layers=32, hidden_size=4096, num_attention_heads=32,
bf16=True, tensor_model_parallel_size=2, pipeline_model_parallel_size=1,
sequence_parallel=True,
)
layer_spec = get_gpt_layer_with_transformer_engine_spec()
return GPTModel(
config=cfg, transformer_layer_spec=layer_spec,
vocab_size=128256, max_sequence_length=4096,
pre_process=pre_process, post_process=post_process,
)
def loss_func(loss_mask: torch.Tensor, output_tensor: torch.Tensor):
losses = output_tensor.float()
loss = torch.sum(losses * loss_mask) / loss_mask.sum().clamp_min(1.0)
return loss, {"lm_loss": loss.detach()}
def forward_step(data_iter, model):
batch = next(data_iter)
output_tensor = model(
input_ids=batch["tokens"], position_ids=batch["position_ids"],
attention_mask=batch["attention_mask"], labels=batch["labels"],
)
return output_tensor, partial(loss_func, batch["loss_mask"])
# Launched via Megatron entry script with dataset_provider
# pretrain(train_valid_test_dataset_provider, model_provider, ModelType.encoder_or_decoder, forward_step)(3)NeMo 2.0 / Megatron-Bridge
启动与 DeepSpeed 启动对照
# PyTorch FSDP2 / TorchTitan
torchrun --nproc_per_node=8 --nnodes=$NNODES train.py
# Megatron-LM / Megatron-Core
torchrun --nproc_per_node=8 --nnodes=$NNODES pretrain_gpt.py \
--tensor-model-parallel-size 8 --pipeline-model-parallel-size 2 --log-memory-to-tensorboard
# DeepSpeed (hostfile launcher)
deepspeed --hostfile=hostfile --num_gpus=8 train.py --deepspeed --deepspeed_config ds_zero3.json# NeMo 2.0 + nemo-run programmatic recipe launch (replaces legacy NeMo 1.0 YAML CLI)
import nemo_run as run
def launch_nemo2_job(recipe):
executor = run.SlurmExecutor(nodes=16, ntasks_per_node=8, gpus_per_node=8)
run.run(recipe, executor=executor)7.3 计算-通信重叠开关与数值/排障要点
| 重叠机制 | Megatron-Core 开关 | DeepSpeed 配置 | FSDP2 / PyTorch |
|---|---|---|---|
| DP 梯度归约与反向重叠 | --overlap-grad-reduce |
"overlap_comm": true |
默认异步触发 |
| 参数拉取与前向重叠 | --overlap-param-gather |
"stage3_prefetch_bucket_size" |
forward_prefetch(或自定义 stream) |
| TP 通信与 GEMM 重叠 | --tp-comm-overlap(TE) |
不内置 | torch.compile +
SymmetricMemory Async-TP |
排障与数值稳定性核对(重点修正过时认识):
- FP8 缩放机制不再强制依赖 Delayed
Scaling:Transformer Engine 2.x 已支持即时
Current Scaling 与
MXFP8,DeepSeek-V3 也证明了在线 tile/block
缩放(
1×128/128×128)在 14.8T tokens 上无需依赖历史amax_history即可稳定收敛。 - 区分 DP 与 TP 归约精度:Megatron 开启
--accumulate-allreduce-grads-in-fp32后,DP 维度的梯度归约在 FP32 下完成,防止多卡累积精度损失;而层内 TP 激活 AllReduce/ReduceScatter 仍保持在计算精度(BF16)。 - 如何读懂不同模型的 MFU:切忌用「7B 模型比 70B 模型 MFU 更高」之类的倒置经验表——在计算受限的稠密训练中,更宽隐藏维与更高算术强度(70B vs 7B)往往能把 Tensor Core 喂得更饱、带来更高的单 GEMM 效率,除非跨机通信或重计算配置拖垮全局比例。任何 MFU 对比必须固定硬件代际、序列长度、重计算模式及精确峰值分母(BF16 vs FP8)。
- 调试工具链:开启
--log-throughput、--log-memory-to-tensorboard(非不存在的--log-memory),配合nsys profile、PyTorch Profiler、nccl-tests与py-spy dump。
八、学界争论与开放问题
- 垂直协同栈(Megatron-Core + TE)vs
可组合编译器栈(FSDP2 +
DTensor+torch.compile):Megatron-Core 凭借手工调度与深度捆绑 CUDA/PTX 内核长期把持万卡前沿 MFU,但模型修改成本高;PyTorch 原生路线试图借助DTensor与编译器 Pass(Inductor + Symmetric Memory)自动生成等价通信重叠,两套路线短期内将在「极致性能控制权」与「框架组合敏捷度」之间持续拉锯,而不会凭空统一成一套 API。 - 显式手工集合通信 vs SPMD
编译器自动并行:JAX
pjit/shard_map与 PyTorchDTensor致力于在声明式网格切分下由编译器自动推导最优集体原语;而 DeepSeek-V3(DualPipe 20 SMs warp specialization)表明,在受限网络带宽下突破硬件上限依然高度依赖贴近 PTX 与网卡拓扑的显式底层编排。 - 跨规模、跨框架的 Checkpoint
无损迁移成本:随着千亿模型周期性进行跨云迁移与后训练分支切换,如何在不通过全量反序列化成
HF
safetensors的前提下,让dist_checkpointing与 PyTorch DCP 互操作并保持精确优化器动量状态,仍是工程界未彻底闭环的痛点。
九、小结
选择训练框架的本质,是在硬件榨取度、显存下限、改模自由度与团队源码维护能力之间划定边界:
- 中小规模、SFT 与快速原型:优先 PyTorch
FSDP2(
fully_shard+DTensor)或 DeepSpeed(需 CPU/NVMe Offload 时)。 - 中大规模稠密预训练与高并发
MoE:Megatron-Core(配合
ModuleSpec、TE、DistributedOptimizer与dist_checkpointing)与 TorchTitan 各自代表 CUDA 垂直极限与 PyTorch 原生组合两条稳健路线;昇腾等异构集群优先选型 MindSpeed 等原生适配底座。 - 算准再开跑:开工前算清 BF16/FP32 状态显存与 TP/PP/DP/EP 通信预算(06 3D 并行深度),锁定 Checkpoint 格式契约,再投入大规模集群运行。
下一篇进入 08 MoE 训练工程,深入拆解稀疏专家模型特有的门控均衡、Expert Parallel 与 DeepEP All-to-All 优化。
参考资料
核心论文
- Shoeybi, M. et al. Megatron-LM: Training Multi-Billion Parameter Language Models Using Model Parallelism. 2019(arXiv 预印本,未经 peer review).
- Narayanan, D. et al. Efficient Large-Scale Language Model Training on GPU Clusters Using Megatron-LM (PTD-P). SC 2021.
- Korthikanti, V. et al. Reducing Activation Recomputation in Large Transformer Models. MLSys 2023.
- Qi, P. et al. Zero Bubble (Almost) Pipeline Parallelism. ICLR 2024.
- Rajbhandari, S. et al. ZeRO: Memory Optimizations Toward Training Trillion Parameter Models. SC 2020.
- Ren, J. et al. ZeRO-Offload: Democratizing Billion-Scale Model Training. USENIX ATC 2021.
- Rajbhandari, S. et al. ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning. SC 2021.
- Wang, G. et al. ZeRO++: Extremely Efficient Collective Communication for Giant Model Training. ICLR 2024.
- Jacobs, S. et al. DeepSpeed Ulysses: System Optimizations for Enabling Training of Extreme Long Sequence Transformer Models. 2023(arXiv 预印本,未经 peer review).
- Liang, W. et al. TorchTitan: One-stop PyTorch Native Solution for Production Ready LLM Pre-training. ICLR 2025(含早先 2024 arXiv 预印本).
- DeepSeek-AI. DeepSeek-V3 Technical Report. 2024(arXiv 预印本,未经 peer review).
- Grattafiori, A. / Dubey, A. et al. (Meta Llama Team). The Llama 3 Herd of Models. 2024(arXiv 预印本,未经 peer review).
- BigScience Workshop. BLOOM: A 176B-Parameter Open-Access Multilingual Language Model. 2022(arXiv 预印本,未经 peer review).
- Zhang, S. et al. OPT: Open Pre-trained Transformer Language Models. 2022(arXiv 预印本,未经 peer review).
- Black, S. et al. GPT-NeoX-20B: An Open-Source Autoregressive Language Model. ACL Workshop on Challenges & Perspectives in Creating Large Language Models, 2022.
规范、源码与官方文档
- NVIDIA Megatron-LM / Megatron-Core 官方仓库 与 Transformer Engine 文档
- NVIDIA
NeMo 2.0 / Megatron-Bridge /
nemo-run文档 - Microsoft DeepSpeed 官方文档
- PyTorch
FSDP2 (
fully_shard) /DTensor/ DCP 官方文档 与 TorchTitan 仓库 - DeepSeek DualPipe 与 DeepEP 开源仓库
- Colossal-AI、InternEvo、PaddleNLP / PaddleFleetX、MindSpeed
- 站内关联阅读:04 互联与网络、06 3D 并行深度、08 MoE 训练工程、09 RLHF 与对齐流水线、16 长上下文工程
上一篇:3D 并行深度:数据 / 张量 / 流水 / 序列 / ZeRO 下一篇:MoE 训练工程:GShard、Switch、Mixtral、DeepSeek
源码下载
本文相关源码已整理,共 1 个文件。
文章导航
读完这篇,下一步读什么
优先读同系列或同问题的下一篇,把单篇消费变成主题集群。
【大模型基础设施工程】08:MoE 训练工程
混合专家(MoE)训练工程实战:从 GShard、Switch、Mixtral、DeepSeek-V3 到 Qwen3-MoE,拆解门控路由、无辅助损失负载均衡、Expert Parallel、DeepEP All-to-All 与 FP8/DualPipe。
【大模型基础设施工程】06:3D 并行深度——数据 / 张量 / 流水 / 序列 / ZeRO
系统拆解 DP、TP、PP、SP/CP、EP 与 ZeRO/FSDP2 的显存、集合通信与流水线气泡数学,结合 4-stage 时空调度、175B 账本与 PyTorch/Megatron 实操给出选型边界。
【大模型基础设施工程】05:训练全景:Pre-train、SFT、RLHF、DPO、蒸馏
以工程视角串联现代 LLM 的四阶段训练栈——预训练、中训、SFT 与对齐——覆盖数据、Tokenizer、优化器、混合精度、Scaling Law、观测与 FSDP2 最小训练闭环。
【大模型基础设施工程】18:向量库与图 RAG
深入 HNSW、IVF-PQ、DiskANN 与 RaBitQ 量化边界,解析 Filtered ANN 选择率拐点、pgvectorscale、LazyGraphRAG、LightRAG、HippoRAG 与多引擎实操骨架。