混合专家(MoE)

Dive into Deep Learning · §11.7

稀疏混合专家(MoE)Transformer
存储容量对比激活容量 · top-k 路由 · 固定容量缓冲区 · 辅助损失对比偏置控制 · 细粒度与共享专家

打破容量与 FLOPs 的绑定

动机

  • 稠密 Transformer:每个词元都要乘以全部权重矩阵(N_{\text{active}} = N_{\text{total}})。
  • 稀疏混合专家(MoE):用一组 E 个并行 FFN 专家替换每个块的 FFN(12d^2 参数中的 8d^2),并将每个词元仅路由给其 top-k 个专家(1 \le k \ll E)。
  • 前沿规模:DeepSeek-V3 存储 671\text{B} 参数,但每个词元仅激活 37\text{B}。

混合专家层内的 Top-k 路由

MoE 层剖析

  • 线性路由器(\mathbf{W}_r \in \mathbb{R}^{d \times E}):将词元 \mathbf{x} \in \mathbb{R}^d 映射为专家概率 \mathbf{p}(\mathbf{x}) = \mathrm{softmax}(\mathbf{x}\mathbf{W}_r) \in \Delta^{E-1}。
  • 稀疏 top-k 选择:挑出得分最高的 k 个专家索引集 \mathcal{T}_k(\mathbf{x}) \subset \{1, \dots, E\} 并求加权和: \mathrm{MoE}(\mathbf{x}) = \sum_{e \in \mathcal{T}_k(\mathbf{x})} p_e(\mathbf{x}) \, \mathrm{FFN}_e(\mathbf{x})
  • 未选中专家零计算:其余 E - k 个专家留在内存中,不对词元 \mathbf{x} 执行任何浮点运算。
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

存储参数(N_total)对比激活参数(N_active)

参数核算

在含 E 个中间宽度为 w 的路由 SwiGLU 专家(每专家 3 d w 权重)和 E_{\text{shared}} 个始终激活共享专家的 L 块 MoE 中:

        ours:   2.1M in experts, 0.264M active per token, ratio  7.9x
 DeepSeek-V3:   656B in experts,  23.1B active per token, ratio 28.4x
Mixtral 8x7B:  45.1B in experts,  11.3B active per token, ratio  4.0x
              with attention and embeddings: 46.7B stored, 12.9B active
资源 / 瓶颈 主导量 原因
训练与预填充 FLOPs N_{\text{active}} 每个词元仅执行 k + E_{\text{shared}} 个专家(C \approx 6 N_{\text{active}} D)
GPU 显存容量 N_{\text{total}} 全部 E + E_{\text{shared}} 个专家均须常驻设备 HBM
批处理解码带宽 N_{\text{active}} \to N_{\text{total}} 当批量大小 B \gg E/k 时,批量内词元并集几乎触及全部 E 个专家

路由器如何穿过离散 Top-k 选择进行学习

路由器梯度

  • 可微门控 p_e(\mathbf{x}):对每个选中专家 e \in \mathcal{T}_k(\mathbf{x}),链式法则穿过标量权重 p_e(\mathbf{x}) 求导: \frac{\partial \mathcal{L}}{\partial p_e(\mathbf{x})} = \bigl(\nabla_{\mathrm{MoE}(\mathbf{x})} \mathcal{L}\bigr)^\top \mathrm{FFN}_e(\mathbf{x})
  • 关键的 k = 1 重归一化陷阱:若在 k = 1 时重新归一化,则 g_{e^*} = p_{e^*} / p_{e^*} \equiv 1,导致 \partial \mathrm{MoE}(\mathbf{x}) / \partial \mathbf{W}_r = \mathbf{0},路由器完全学不到东西。

固定容量缓冲区与词元丢弃

编译分派

  • 静态缓冲区容量 S(\gamma \ge 1):编译后的 GPU/TPU 核预分配形状为 (E, S, d) 的静态缓冲区: S = \left\lceil \gamma \cdot \frac{n k}{E} \right\rceil 其中 \gamma = 1.25 在均匀负载之上提供 25\% 的缓冲余量。
  • 溢出与词元丢弃:队列位置 \text{rank} \ge S 的指派被丢入哑溢出槽位,原样经残差流通过。

向量化分派、批量 SwiGLU 与汇聚

MoELayer 实现

MoELayer.forward 通过独热累积和为每个词元的队列位置编号,将词元散布到 buf(以槽位 E * S 作为哑溢出汇),用一次批量 bmm 运行全部 E 个专家,再将结果汇聚回来:

e = idx.flatten()                              # (n*k,) selected expert indices
onehot = F.one_hot(e, E)                       # (n*k, E) assignment indicator
rank = (onehot.cumsum(0) * onehot).sum(1) - 1  # Queue position 0, 1, ... in expert e
slot = torch.where(rank < S, e * S + rank, E * S)  # Slot E*S absorbs dropped tokens
buf = x.new_zeros(E * S + 1, d)
buf[slot] = x.repeat_interleave(k, 0)
Y = self.run_experts(buf[:-1].reshape(E, S, d)).reshape(E * S, d)
Y = torch.cat([Y, Y.new_zeros(1, d)])[slot]    # Dropped slots read zero row
weights = P.gather(-1, idx)                    # (n, k) raw probabilities p_e(x)
out = (weights[..., None] * Y.reshape(n, k, d)).sum(1)

将 MoELayer 接入 TransformerBlock

MoELayer 实现

blk = d2l.TransformerBlock(256, num_heads=8,
                           ffn_factory=lambda: MoELayer(256, 8, 2))
X = torch.randn(4, 100, 256)
d2l.check_shape(blk(X), X.shape)  # The expert layer fits into the block
moe = MoELayer(256, num_experts=8, num_active=2)
print(f'{d2l.num_params(moe)} parameters stored, '
      f'{active_params(moe)} active per token')
4198400 parameters stored, 1051136 active per token

路由失衡的成因:偏斜与反馈

路由坍缩

  • 1. 输入分布偏斜(t = 0):高频字节(' ' 占 WikiText-103 的 18.9\%,已超 \gamma / E = 15.6\%)与共享均值表示把初始对数几率推向 1–2 个专家。
  • 2. 强者愈强的正反馈:最忙的专家获得更多梯度更新、更快降低损失,并被 \nabla_{\mathbf{W}_r}\mathcal{L} 赋予更高的 p_e(\mathbf{x}),可能令空闲专家因词元太少而无法学习。

对策 1:Switch 辅助负载均衡损失

辅助损失均衡

  • Switch Transformer(Fedus 等,2022)添加辅助惩罚 \alpha \mathcal{L}_{\text{aux}}(\alpha = 0.01): \mathcal{L}_{\mathrm{aux}} = E \sum_{e=1}^{E} f_e \, \bar{p}_e
  • 由于 f_e 截断梯度而 \bar{p}_e 可微,\partial \mathcal{L}_{\text{aux}} / \partial \bar{p}_e = E f_e 会压低过载专家(f_e > 1/E),在均匀路由下达到最小值 \mathcal{L}_{\text{aux}} = 1。

对策 2:无损失动态路由器偏置控制

无损失均衡

  • DeepSeek-V3 无损失偏置控制器(Wang 等,2024): \mathcal{T}_k(\mathbf{x}) = \operatorname{argtop}_k\bigl(\mathbf{p}(\mathbf{x}) + \mathbf{b}\bigr), \qquad b_e \leftarrow b_e + \eta_b \, \mathrm{sign}\!\left(\frac{1}{E} - f_e\right)
  • 仅平移 \operatorname{argtop}_k 选择阈值,同时令 \sum_{e \in \mathcal{T}_k} p_e(\mathbf{x})\,\mathrm{FFN}_e(\mathbf{x}) 中的门控权重 p_e(\mathbf{x}) 完全无偏(零梯度干扰)。

在 WikiText-103 上对比五种路由方案

负载均衡消融

我们在五种路由配置(各两个种子)下训练 2 块、8 专家 Top-1 字节级 GPT(d = 128, \gamma = 1.25)800 步:

spaces: 18.9% of the validation bytes
  two runs each    loss     no drops    busiest   dropped
 initialization  5.63 5.49  5.63 5.49  2.5x 2.8x  22% 20%
   no balancing  1.75 1.81  1.70 1.73  3.3x 3.9x  24% 36%
  frozen router  1.71 1.72  1.67 1.67  2.8x 2.1x  14% 17%
 auxiliary loss  1.59 1.54  1.59 1.54  1.3x 1.2x   0%  0%
bias controller  1.58 1.56  1.57 1.55  1.3x 1.5x   0%  2%
  • 无均衡与初始偏斜:initialization 与 no balancing 都将均匀份额的 2.4\text{--}3.9\times(全部词元的 30\%\text{--}49\%)送往最忙的单个专家,并丢弃 20\%\text{--}36\% 的指派。
  • 两种对策均治愈坍缩:auxiliary loss(\alpha = 0.01)与 bias controller(\eta_b = 0.01)都将最忙专家压在理想份额的 2\times 以下,丢弃率至多几个百分点,并将验证损失降低约 0.1\text{--}0.25\text{ nats/byte}。

可视化各方法下的专家负载份额

负载分布

  • 排序后的专家份额(从最忙专家 1 到最闲专家 8):在 no balancing(C0)下,前 3 个专家占据约 70\% 的词元,最闲专家几乎为零。
  • 均匀利用(1/8 = 12.5\%):Switch 辅助损失(C1)与无损失偏置控制器(C2)在全部 8 个专家上均紧贴 12.5\% 的水平黑线。

IsoFLOP 设置:8 专家 MoE 对比匹配稠密 GPT

对照基准设置

在完全相同的激活参数量与单词元 FLOPs 下,稀疏条件容量能否胜过稠密 Transformer?我们在 6{,}000 步(49\text{M} 字节)上对比 2 块稠密 GPT 与 8 专家 Top-1 MoE GPT(\gamma = 2):

capacity = {'dense': None, 'MoE': 2}  # The dense model has no buffers
models = {name: small_gpt(len(data.vocab), capacity_factor=c)
          for name, c in capacity.items()}
for name, model in models.items():
    print(f'{name:>5}: {d2l.num_params(model) / 1e6:5.2f}M parameters, '
          f'{active_params(model) / 1e6:.2f}M active per token')
dense:  0.43M parameters, 0.43M active per token
  MoE:  2.26M parameters, 0.43M active per token
  • 相同的激活计算量(每词元 0.43\text{M} 激活参数):在两个模型中,每个词元执行的注意力与 FFN 矩阵乘法次数完全相同。
  • 5.3\times 存储参数容量:MoE 模型存储 2.26\text{M} 参数(每层 8 个而非 1 个专家 FFN),同时使用容量因子 \gamma = 2 以免早期高频字节突发导致指派被丢弃。

MoE 在相同激活 FLOPs 下反超稠密 GPT

IsoFLOP 学习曲线

  • 早期预热滞后(第 0\text{--}1{,}500 步):MoE 模型起步略落后,因为 8 个专家各自每步仅见到 \sim 1/8 的梯度更新,且输出被 p_e(\mathbf{x}) \approx 1/8 缩放。
  • 交叉反超与 \sim 0.05\text{-nat} 增益:在前 2{,}000 步内,专业化专家反超稠密 FFN,最终在各随机种子上均低 0.05\text{ nats/byte}——相当于把稠密模型 FLOPs 扩大三倍的收益。

run 1: dense 1.321, MoE 1.277; MoE ahead from step 2000, 0.0% dropped at the end
run 2: dense 1.327, MoE 1.265; MoE ahead from step 750, 0.0% dropped at the end

细粒度专家切分与共享专家

现代 MoE 设计

  • 1. 细粒度切分(DeepSeekMoE,Dai 等,2024):将 E = 16 个全宽专家(k = 2)切分为 m E = 64 个四分之一宽度专家(m k = 8),存储与激活参数均不变,而激活组合数从 \binom{16}{2} = 120 激增至 \binom{64}{8} \approx 4.4 \times 10^9。
  • 2. 始终激活的共享专家:专设 E_{\text{shared}} \ge 1 个专家在每个词元上运行,吸收通用句法变换,让路由专家避免冗余。
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

前沿开源权重 MoE 的专家配置

前沿对比

  • 粗粒度路由(Mixtral 8x7B,2024):E = 8 个全宽专家,激活 top-2(总计 47\text{B} / 激活 13\text{B},3.6\times 容量比)。
  • 细粒度专家(Qwen3、DeepSeek-V3、gpt-oss):128\text{--}256 个窄专家(w/d \in [0.29, 1.0])配 top-4 或 top-8 路由,达到 11\times\text{--}23\times 存储/激活容量比;DeepSeek-V3 另配一个共享专家。

概念检验:MoE 容量、损失与数据预算

检验理解

完成以下三道 MoE 设计计算:

  1. 激活专家比例:某层含 E = 64 个宽度为 w 的路由专家,每词元激活 k = 6 个,并含 E_{\text{shared}} = 2 个同宽度 w 的始终激活共享专家。单个词元执行该层专家参数的多大比例?
  2. 计算 Switch 辅助损失:在 4 专家层(E = 4)中,某小批量将 50\% 槽位路由给专家 1(f_1 = \bar{p}_1 = 1/2),并将 1/6 分别路由给专家 2、3、4(f_e = \bar{p}_e = 1/6)。\mathcal{L}_{\text{aux}} = E \sum_{e=1}^4 f_e \bar{p}_e 等于多少?
  3. 每个专家见到的词元数:在我们的 6{,}000 步 WikiText-103 运行(64 \times 128 = 8{,}192 字节/步)中,稠密 FFN 与均衡 8 专家 Top-1 MoE 层的每个专家分别见过多少训练字节?

答案:

  1. (k + E_{\text{shared}}) / (E + E_{\text{shared}}) = (6 + 2) / (64 + 2) = 8 / 66 \approx \mathbf{12.1\%}(外加轻量级 d \times 64 路由器矩阵)。
  2. \mathcal{L}_{\text{aux}} = 4 \times \bigl(\frac{1}{2}\cdot\frac{1}{2} + 3 \cdot \frac{1}{6}\cdot\frac{1}{6}\bigr) = 4 \times \bigl(\frac{1}{4} + \frac{1}{12}\bigr) = 4 \times \frac{1}{3} \approx \mathbf{1.333}(高于均衡最小值 1.000)。
  3. 6{,}000 \times 8{,}192 \approx \mathbf{49.2\text{M}\text{ bytes}} 通过稠密 FFN,而每个 Top-1 专家仅见到 49.2\text{M} / 8 \approx \mathbf{6.1\text{M}\text{ bytes}}——这解释了为何 MoE 在极小数据集上极易过拟合,需要大规模预训练语料。

小结:稀疏混合专家 Transformer

核心要点

  • Top-k 条件计算:\mathrm{MoE}(\mathbf{x}) = \sum_{e \in \mathcal{T}_k(\mathbf{x})} p_e(\mathbf{x})\,\mathrm{FFN}_e(\mathbf{x}) 将存储容量 N_{\text{total}} 与单词元 FLOPs N_{\text{active}} 解耦。
  • 静态缓冲区与均衡:固定容量 S = \lceil \gamma n k / E \rceil 配合 Switch 辅助损失或无损失动态偏置控制 b_e。
  • 细粒度专家:E \to mE, k \to mk 切分是前沿 MoE 的主流模式;DeepSeek-V3 另加共享专家。