LLM Systems 17: System for MoE Models
0. Recap
- Pipeline Parallelism
- split by layers (horizonal split)
- eliminate the bubbles (idle)
- interleaving forward/backward
- Tensor Parallelism
- split the matrix computation over multiple GPUs
- usually within a single node
1. Transformer Mixture-of-Expert Model
1.1 Motivation
问题:大模型训练的主要挑战来自计算量,如下图所示:
- 对 Dense 模型进行扩展非常困难,因为 FLOPs 随着模型规模增加明显(考虑经典 Dense Transformer 模型,其 FLOPs 与层数 \(l\) 成线性关系,与隐藏层维度 \(h\) 成平方关系)。
- Solution:Sparse model
- 增加模型参数量与能力,而不需要显著增长计算量;
- 典型代表:MoE。
- MoE 优点:
- 更易于扩展到大参数量模型;
- 预训练比 Dense 模型快;
- 对比相同参数量的 Dense 模型,MoE 模型推理也更快。
MoE 模型结构:
- 使用以下模块替换 Transformer Layer 中的 FFN:
- 多个小的专家,每个专家是一个神经网络(如 FFN);
- 一个 门控神经网络,用于根据输入 token 决定激活哪些专家;
- MoE 不同于混合专家学习(Mixture-of-Expert learning),后者是一种学习算法,用于学习多个预测模型的均值权重。
1.2 Switch Transformer architecture
- 每个 token 只激活一个 expert,如下图所示:
- tokens (输入 shape:\([B, S,
H]\)) 经过 router 后(权重 shape 为:\([H, E]\)),输出 tensor shape 为: \([B, S, E]\) ,其中 \(B, S, H, E\) 分别表示:batch
size、sequence、hidden dim 和专家数量。选择输出的
E个 logits(经过 Softmax 变为 probs) 中最大值对应专家,激活该专家对对应 token 进行 FFN 计算。FFN 输出乘以对应的 probs,得到最终的 MoE 层输出。 - 门控网络 \(G\) 学习把 input
中的一个 token 发送给哪个 expert,具体过程形式化描述如下:
- 计算原始得分 (Logits): 输入的 token 特征 \(x\) 通过路由线性层(Router),计算出针对各个专家的原始得分(Logits)\(H(x) = x \cdot W_g\) ;
- Top-K 筛选: 使用 \(\text{KeepTopK}(H(x), k)\) 筛选出得分最高的 \(k\) 个专家(在 Switch Transformer 中 \(k=1\),即单专家路由),将未选中的专家得分设为 \(-\infty\) ;
- Softmax 归一化: 通过 Softmax 计算门控概率/权重: \(G(x) = \text{Softmax}(\text{KeepTopK}(H(x), k))\) ;
- 专家计算与加权: 最终输出 \(y\) 是 Top-k 专家输出 \(E_i(x)\) 与门控权重 \(G(x)_i\) 的乘积和: \(y = \sum_{i=1}^{k} G(x)_i E_i(x)\) 。
1.3 Shared-routed Experts
- Motivation:所有 token 总是经过一个固定的 shared expert;
- 不同专家作用:
- Shared expert:calculating common knowledge;
- Routed experts: calculated token-specific knowledge. First from Deepspeed-MoE. later in DeepSeek-MoE。
- 计算流程如下图所示:
Expert 网络学到了什么?
- Encoder experts tend to specialize in token groups or shallow concepts (e.g., punctuation, proper nouns).
- Decoder experts exhibit less specialization.
- In multilingual setups, experts do not specialize in specific languages due to token routing and load balancing.
Router 几何解释:
Router 本质可以理解为:高维特征空间中的线性超平面划分(finding linear boundaries among expert centroids)。
具体解释如下:
从数学公式看,Router 计算的是 \(H(x) = h \cdot W_g\),其中 \(h\) 是输入 Token 的高维特征向量,而 \(W_g\) 是 Router 的权重矩阵。
从几何角度来看,这相当于:
- 专家的质心/方向向量(Expert Centroids):
- 矩阵 \(W_g\) 中的每一列 \(W_{g, i}\),都可以看作是第 \(i\) 个专家在高维特征空间中的“质心(Centroid)”或标志性方向向量。
- 点积与相似度投影:
- \(h \cdot W_{g, i}\) 的点积计算,几何上等于计算 Token 向量 \(h\) 在第 \(i\) 个专家方向上的投影长度(代表相似度得分)。
- KeepTop1 划分线性决策边界(Linear Boundaries):
- KeepTop1 挑选的是点积最大的专家,即 \(\arg\max_i (h \cdot W_{g, i})\)。
- 对于任意两个专家 \(i\) 和 \(j\),分割它们领地的分界线满足 \(h \cdot W_{g, i} = h \cdot W_{g, j}\),即 \(h \cdot (W_{g, i} - W_{g, j}) = 0\)。这是一个穿过原点的高维线性超平面。
- 3 个路由专家就相当于用线性超平面将整个高维 Token 特征空间切割成了 3
个凸多面体区域(类似 Voronoi 胞腔)。
- Voronoi 胞腔:向量近似最近邻检索(Approximate Nearest Neighbor Search,ANNS)领域常见概念。
- 可以用 ANNS 中概念理解 Router:Token Hidden State = Query 向量,Router 权重 \(W_{g, i}\) = 专家的聚类质心(Centroid),Router 计算 = 最大内积搜索(MIPS)。
- BTW:Self-Attention 计算,也可以理解为 MIPS 检索(\(QK^T\));外加 Softmax 归一化以及乘以 Value。
MoE 如何在 FLOPs 不变情况下扩展假设空间
从假设空间的几何结构来看,MoE 并不是用一个高维的全局连续函数去硬拟合所有数据,而是将庞大的假设空间拆解为由 Router 门控连接的 \(N\) 个局部子假设空间(Sub-hypotheses)。
每一个输入的 Token,在运行时由 Router 动态投射到最匹配其特征的特定专家(子函数)中。
这种机制的本质,是用一组 分段局部拟合函数 去刻画极其高维、非线性的语言数据流形。因为单 Token 实际激活的子空间计算量与 Dense 模型完全一致,所以它能以常数级别的 FLOPs,在全局假设空间中记忆并建模截然不同的模式(如代码、多语言、事实知识)。
模型结构的创新,本质上是否可以理解为:在相同的约束下(FLOPs、Memory、Communication 等),提升假设空间表示的多样性/复杂性?
- 模型结构的创新,本质上就是在物理约束(FLOPs、显存带宽、通信延迟、训练稳定性)构成的帕累托边界(Pareto Frontier)内,通过重构归纳偏置(Inductive Bias),实现假设空间有效表达容量(Effective Expressive Capacity)的最大化。
2. Training and Inference for MoE
2.1 Training of MoE: Expert Parallelism
- 每个 worker/device 一个 Expert;
- 其他网络结构在不同 device 间复制(DP);
- 需要快速的 All2All 通信:
- 经过 Router/Gating 后,根据输出 probs 对 tokens 进行 All2All Dispatch;
- 每个 device 上 Expert 进行计算;
- 进行 All2All Combine 通信,将计算后结果发送给原本输入 token 所在 device;
Token 视角的 MoE forward 过程:
- token 经过 Router 可能发送给不同的 Expert 进行计算;
- Expert 计算完成后,发送给 token 输入所在 device;
- 继续进行残差连接 / Norm 计算。
Load Balancing in MoE Training
- 增加额外的损失函数:Expert-Level Balance Loss,以避免路由塌陷(routing collapse)导致的 token 全部被路由至少量 token,同时会引起负载不均,导致整体 GPU 吞吐浪费;
- 专家级负载均衡损失函数定义:
\[ L_{\text{ExpBal}} = \alpha_1 \cdot M \cdot \sum_{i=1}^{M} f_i \cdot P_i \]
其中:
- \(M\):专家的总数量(
#experts)。 - \(\alpha_1\):辅助损失的超参数权重(乘数系数),用于控制负载均衡损失在总 Training Loss 中的占比。
- \(f_i\)(实际路由占比 / 频次): \(f_i = \frac{\text{\#tokens routed to expert } i}{\text{\#tokens}}\) 代表在一个 Batch 中,真正被 Top-K 选中并分配给专家 \(i\) 的 Token 比例。
- \(P_i\)(门控概率均值): \(P_i = \frac{1}{\text{\#tokens}} \sum_{t=1}^{\text{\#tokens}} s_{i, t}\) 代表在一个 Batch 中,Router 的 Softmax 输出中分配给专家 \(i\) 的平均门控概率。
2.2 MoE Inference
- MoE 推理性能决定因素:
- 模型大小
- 激活专家数
- 显存带宽
- 默认实现:
- 所有专家都放在 GPU 显存
Optimizing MoE inference
- 系统设计目标:
- minimize the critical data path per device
- maximize the achievable aggregate memory bandwidth
- 具体实现:
- Token 路由与分组聚合:将具有相同计算路径(目标专家)的 Token 组合在一起,减少单设备的数据重组开销。
- 并行协同通信调度:针对不同并行策略重叠并优化 All-to-All 通信。
- 算子/Kernel 级融合:优化 Transformer 和 MoE 相关算子以提升单设备计算效率。
Expert Parallelism and Tensor-Parallelism
- 共 16 个 GPUs
- Attention 层:TP=4,DP=4;
- MoE 层:每个 Expert TP=2,EP=8;
- Expert 0 权重切分放置在 GPU 0 和 GPU 8;
- 完成 Attention TP 计算 + AllReduce 后,每个 DP Group 内的 4 个 GPU
上结果是完全相同的。如果直接进行 All2All
Dispatch,会导致重复发送和带宽浪费。
- Solution:将 TP 组内相同的 Token 集合按 Hidden 维度切开,或者只由 TP 组内的特定 GPU 负责分发。
- 考虑 GPU 0 完成 Attention 计算后,其将经过 Router 后的 tokens 重排,把分配给 Expert 0 的数据的 \(\frac{H}{\text{\#Attention TP} \cdot \text{\#Expert TP}} = \frac{H}{4 \cdot 2}\) 维度发送给 Expert 0 所在的 GPU 0 和 GPU 8;
- 进入 MoE FFN 之前,Expert TP Group 进行 AllGather 通信获取全量输入 \([B, S, H]\);
- 进行 Expert 内的 TP Forward 计算;
- All2All Combine 发送计算结果到 token 所在 GPU;
- 这里理论上也有通信优化:沿着 \(H\) 维度先切分做 All2All,然后 Attention TP Group 内做 AllGather 利用高速机内互联;
Optimizing MoE Kernels
- MoE Specific Optimizations:
- fuse the gating function into a single kernel
- GEMM + Softmax + Top-K + Mask & Index
- dense token-to-expert mapping table
- fuse the gating function into a single kernel
- Result: over 6x reduction in MoE Kernel related latency
Optimizing All-to-All Communication
- Expert parallelism requires all-to-all communication between all expert parallel devices; the latency increases linearly with the increase in devices.
- Optimization:
- hierarchical all-to-all communication pattern: reduces the
communication hops.
- 机内预聚合(Intra-Node Aggregation):在同一个服务器节点内部,几张 GPU 优先通过高速 NVLink,把要发往同一个远端目标节点的 Token 集中打包。
- 机间网卡传输(Inter-Node Transfer):利用节点间网卡,把打包好的大块数据包一次性跨节点发送给目标服务器(将 \(N \times N\) 的分散通信收拢为节点间的批量传输)。
- 机内解包分发(Intra-Node Distribution):目标服务器收到大包后,再通过本地 NVLink 分发给具体的专家 GPU。
- parallelism-coordinated communication optimization: schedules communications based on the model's parallelism strategy to minimize overhead.
- hierarchical all-to-all communication pattern: reduces the
communication hops.
3. DeepSeek MoE (V3 model)
3.1 Model Structure
- Fine-grained experts: each FFN is split to k smaller experts, total kN (N=original experts)
- shared experts + routing experts
- topk weighted average of routing experts (activating kM)
DeepSeek V3 MoE (670B)
| 参数名称 | 具体数值 | 架构设计含义 |
|---|---|---|
| Model Dimension (\(H\)) | 7168 | 隐层特征向量维度。 |
| Total Layers | 61 | 全模型共 61 层 Transformer Block。 |
| Dense Layers | 3 | 最底层的前 3 层为传统 Dense 层,不使用 MoE 路由,用于稳定早期特征。 |
| FFN Inter Dim | 18432 | 传统 Dense FFN 的中间层维度。 |
| MoE Dim | 2048 | 细粒度小专家的 FFN 中间维度(\(18432\) 被细分为了单专家 \(2048\) 维度)。 |
| Shared Experts | 1 个 | 1 个总是被激活的共享专家,捕获通用常识。 |
| Routed Experts | 256 个 | 全网提供高达 256 个细粒度路由专家供筛选2 |
| Activated Experts | 8 个 (\(K=8\)) | 每次前向推导从 256 个路由专家中激活得分最高的前 8 个。 |
| Expert Groups | 8 组 | 将 256 个专家划分为 8 个专家组。 |
| Limited Groups | 4 组 | 组限制路由:限制 Token 只能在最多 4 个组内挑选 8 个专家,用于优化跨卡通信拓扑。 |
Load Balancing in DeepSeek MoE
- 专家级负载均衡损失(Expert-Level Balance Loss)
- 核心公式:
\[ L_{\text{ExpBal}} = \alpha_1 \sum_{i=1}^{\#experts} f_i P_i \]
- 参数含义:
- \(f_i\):被实际分发/路由给专家 \(i\) 的 Token 硬选择比例(Fraction of tokens dispatched to expert \(i\)),归一化公式为 \(f_i = \frac{\#experts}{\#activated\_experts} \cdot \frac{\#tokens \text{ to expert } i}{\#tokens}\)。
- \(P_i\):Router 对所有 Token 预测给专家 \(i\) 的 软概率/门控权重均值(Average routing probability for expert \(i\)),公式为 \(P_i = \frac{1}{\#tokens} \sum_{t=1}^{\#tokens} s_{i,t}\)。
- 作用:在微观层面强迫 Router 将流量均匀分配给 256 个小专家中的每一个,**防止路由塌陷,确保每一个专家都能在训练中得到参数更新。
- 设备/组级负载均衡损失(Device-Level Balance Loss)
- 核心公式:
\[ L_{\text{DevBal}} = \alpha_2 \sum_{j=1}^{\#groups} f_j P_j \]
- 参数含义:
- \(f_j\):专家组(Group/Device)\(j\) 内所有专家的 \(f_i\) 平均值(代表分发给第 \(j\) 个设备/组的总体 Token 流量)。
- \(P_j\):专家组 \(j\) 内所有专家的 \(P_i\) 累加和(代表第 \(j\) 个设备/组收到的总体门控概率)。
- 背景与作用:
- 痛点:即使每个专家个体是均衡的,但如果落在某个 GPU 节点(或卡组)上的所有专家恰好被同时频繁激活,持有该节点的 GPU 算力就会被撑爆,产生“慢卡(Straggler Effect)”,导致全网等待。
- 作用:在宏观物理设备层面强迫不同 GPU 设备/节点组(Groups)之间的总体计算负担保持均衡,消除卡间计算不对等,从而最大化分布式专家并行(EP)的计算吞吐。
DeepSeek Libraries to Accelerate MOE
- DeepEP is a communication library tailored for Mixture-of-Experts (MoE) and expert parallelism (EP).
- Expert Parallelism Load Balancer (EPLB)
3.2 code walkthrough
- DeepSeek MoE:DeepSeek V3 Model
- DeepSpeed MoE:
3.2.1 DeepSeek MoE
import & file variable
1 | |
ParallelEmbedding
1 | |
- 按词表维度切分,fwd 时 AllReduce 通信。
Linear
- 支持 FP8,代码略。
Column/Row Parallel Linear
1 | |
- ColumnParallel
- 直接进行本地 forward 计算,无通信。
- RowParallel
- 本地 GEMM 计算完成后进行 AllReduce。
MLP
1 | |
- SwiGLU(Swish Gated
Linear Unit)
- 两个 ColumnParallel + 一个 RowParallel
Gate
1 | |
- 主要流程:
- GEMM + Softmax 计算 probs
- 组限制路由
- 全局 Top-K 提取与权重归一化
- weights 缩放
Expert
1 | |
- 类似 MLP,但是 Linear 层无并行
MoE
1 | |
- 见代码注释
- 不是 All2All 通信实现,而是朴素的 local 计算 + 0 占位 + AllReduce(类似 ParallelEmbedding)
TransformerBlock
1 | |
- Attention:MLA
- FFN:MLP 或者 MoE
- 前几层 Dense MLP;后续层 MoE。
Transformer
1 | |
- Transformer
- Embedding
- TransformerBlock
- LMHead + RMSNorm
3.2.2 DeepSpeed MoE
MoE
1 | |
Experts
1 | |
MoeLayer
1 | |
MoeLayerforward 的核心链路如下:
1 | |
4. Conclusion
- LLM Mixture-of-Expert Model
- Instead of a single dense FFN, using multiple FFNs (experts)
- Routing network to select one/multiple experts
- Shared-routed experts (DeepSpeed-MOE, DeepSeek MOE)
- a few dense layers, then MOE (DeepSeek MOE)
- Scalable training/inference
- expert parallelism: split experts and replicate non-expert (GShard)
- all-to-all communication for expert output
- load balancing: grouping and avoid collapse (DeepSeek)
- optimized kernel for MoE