def moe_accounting(name, d, width, num_experts, num_active, num_layers,
shared=0, unit=1e9):
"""Expert parameters stored, and expert and router parameters active
per token, in a stack of SwiGLU expert layers."""
per_expert = 3 * d * width # SwiGLU: three d x width matrices
store = num_layers * (num_experts + shared) * per_expert
active = num_layers * ((num_active + shared) * per_expert
+ d * num_experts) # + the router
tag = 'B' if unit == 1e9 else 'M'
print(f'{name:>12}: {store/unit:5.3g}{tag} in experts, '
f'{active/unit:5.3g}{tag} active per token, '
f'ratio {store/active:4.1f}x')
return store, active
moe_accounting('ours', 128, 341, 8, 1, 2, unit=1e6)
moe_accounting('DeepSeek-V3', 7168, 2048, 256, 8, 58, shared=1)
store, active = moe_accounting('Mixtral 8x7B', 4096, 14336, 8, 2, 32)
attn = 32 * (2 * 4096 * 4096 + 2 * 4096 * 1024) # GQA: 32 Q, 8 KV heads
emb = 2 * 32000 * 4096 # embedding + output head
print(f'{"":>12} with attention and embeddings: '
f'{(store + attn + emb)/1e9:.1f}B stored, '
f'{(active + attn + emb)/1e9:.1f}B active')11.7 混合专家(MoE)
在稠密 Transformer(11.6 节)中,每个词元都要使用全部参数:将模型容量 \(N \approx 12 L d^2\) 翻倍,训练成本(\(6 N\) FLOPs/词元)与推理计算量(\(2 N\) FLOPs/词元)也会随之翻倍。我们能否在不增加每个词元执行的激活参数量 \(N_{\textrm{active}}\) 的前提下,扩大模型存储的参数容量 \(N_{\textrm{total}}\)?
回顾 11.1 节,前馈网络占据了稠密块三分之二的参数(\(12 d^2\) 中的 \(8 d^2\)),并且逐位置独立作用于每个词元向量 \(\mathbf{x} \in \mathbb{R}^d\)。稀疏混合专家(MoE)层 (Jacobs 等 1991年; Shazeer 等 2017年; Lepikhin 等 2021年; Fedus 等 2022年) 正是利用了这种独立性(图 11.7.1):它用一组 \(E\) 个并行 FFN 专家 \(\{\textrm{FFN}_1, \dots, \textrm{FFN}_E\}\) 替换块中的单个 FFN,并用一个轻量级线性路由器 \(\mathbf{W}_r \in \mathbb{R}^{d \times E}\) 将每个词元 \(\mathbf{x}\) 仅分派给其得分最高的 top-\(k\) 个专家(\(1 \le k \ll E\))。
11.7.1 条件计算:存储参数与激活参数
在一个 \(L\) 层 MoE Transformer 中,若每个块包含 \(P_{\textrm{attn}}\) 个注意力参数、\(E\) 个中间宽度为 \(w\) 的路由 SwiGLU 专家(每个专家 \(P_{\textrm{exp}} = 3 d w\) 个参数)以及 \(E_{\textrm{shared}}\) 个始终激活的共享专家 (Dai 等 2024年),那么全部 \(E + E_{\textrm{shared}}\) 个专家都必须存放在内存中(\(N_{\textrm{total}}\)),但每个词元只执行 \(k + E_{\textrm{shared}}\) 个专家(\(N_{\textrm{active}}\)):
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
def moe_accounting(name, d, width, num_experts, num_active, num_layers,
shared=0, unit=1e9):
"""Expert parameters stored, and expert and router parameters active
per token, in a stack of SwiGLU expert layers."""
per_expert = 3 * d * width # SwiGLU: three d x width matrices
store = num_layers * (num_experts + shared) * per_expert
active = num_layers * ((num_active + shared) * per_expert
+ d * num_experts) # + the router
tag = 'B' if unit == 1e9 else 'M'
print(f'{name:>12}: {store/unit:5.3g}{tag} in experts, '
f'{active/unit:5.3g}{tag} active per token, '
f'ratio {store/active:4.1f}x')
return store, active
moe_accounting('ours', 128, 341, 8, 1, 2, unit=1e6)
moe_accounting('DeepSeek-V3', 7168, 2048, 256, 8, 58, shared=1)
store, active = moe_accounting('Mixtral 8x7B', 4096, 14336, 8, 2, 32)
attn = 32 * (2 * 4096 * 4096 + 2 * 4096 * 1024) # GQA: 32 Q, 8 KV heads
emb = 2 * 32000 * 4096 # embedding + output head
print(f'{"":>12} with attention and embeddings: '
f'{(store + attn + emb)/1e9:.1f}B stored, '
f'{(active + attn + emb)/1e9:.1f}B active') 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
注意 \(N_{\textrm{total}}\) 与 \(N_{\textrm{active}}\) 分别支配不同的系统资源:
- 单词元浮点运算量(训练与预填充)随 \(N_{\textrm{active}}\) 缩放(\(C_{\textrm{train}} \approx 6 N_{\textrm{active}} D\))。
- 显存容量随 \(N_{\textrm{total}}\) 缩放,因为全部 \(E\) 个专家都必须常驻设备显存。
- 批处理解码带宽:在批量大小 \(B = 1\) 时,单个词元只需从 HBM 流式读取 \(k\) 个专家(\(N_{\textrm{active}}\) 字节权重)。但跨 \(B\) 个词元的批量时,不同词元会激活不同专家:一旦 \(B \gg E / k\),几乎全部 \(E\) 个专家都会被批量中至少一个词元触及,因此每步解码要从 HBM 流式读取近乎 \(N_{\textrm{total}}\) 字节权重,而执行的浮点运算仅 \(2 B N_{\textrm{active}}\) 次。
11.7.2 混合专家层
11.7.2.1 Top-\(k\) 路由
对每个词元 \(\mathbf{x} \in \mathbb{R}^d\),路由器计算概率 \(\mathbf{p}(\mathbf{x}) = \textrm{softmax}(\mathbf{x}\mathbf{W}_r) \in \Delta^{E-1}\),选出得分最高的 \(k\) 个专家集合 \(T(\mathbf{x}) \subset \{1, \dots, E\}\),直接保留其原始概率作为权重 \(g_e(\mathbf{x}) = p_e(\mathbf{x})\)(在 \(T(\mathbf{x})\) 上重新归一化会让 top-1 路由器失去梯度;见 1),并形成加权和:
\[ \textrm{MoE}(\mathbf{x}) \;=\; \sum_{e \in T(\mathbf{x})} g_e(\mathbf{x}) \, \textrm{FFN}_e(\mathbf{x}). \tag{11.7.1}\]
11.7.2.2 将词元分派至固定容量的专家缓冲区
在编译或分布式训练中,针对含 \(n\) 个词元的批量,每个专家 \(e \in \{1, \dots, E\}\) 预分配容量为 \(S = \lceil \gamma \cdot n k / E \rceil\) 个槽位的固定缓冲区,其中 \(n k / E\) 是完全均衡时每个专家的负载,\(\gamma \ge 1\) 称为容量因子(设 \(\gamma = E\) 则 \(S = n k\),从而禁用丢弃)。如果指向专家 \(e\) 的词元-专家指派超过 \(S\) 条,超出部分会被丢弃(对 式 11.7.1 贡献为零,相应词元直接经外围块的残差跳跃连接通过)。图 11.7.2 追踪了六个词元经历这一分派的过程。
MoELayer 实现了路由器、向容量 \(S\) 槽位缓冲区的分派以及丢弃规则:
class MoELayer(nn.Module):
"""Token-choice top-k mixture of SwiGLU d2l.FeedForward experts, each
with a buffer of S = capacity_factor * n k / E slots for n tokens."""
def __init__(self, num_hiddens, num_experts, num_active,
capacity_factor=1.25):
super().__init__()
self.num_experts, self.num_active = num_experts, num_active
self.capacity_factor = capacity_factor
self.router = nn.Linear(num_hiddens, num_experts, bias=False)
self.experts = nn.ModuleList([d2l.FeedForward(num_hiddens)
for _ in range(num_experts)])
# Added to the probabilities for the selection only; zero until a
# balancing method moves it
self.register_buffer('expert_bias', torch.zeros(num_experts))
# Assignments per expert, dropped or not, and the dropped ones,
# counted by record() until reset_stats()
self.register_buffer('load', torch.zeros(num_experts))
self.register_buffer('dropped', torch.zeros(()))
def forward(self, X):
x = X.reshape(-1, X.shape[-1]) # (n, d): the tokens
(n, d), E, k = x.shape, self.num_experts, self.num_active
S = math.ceil(self.capacity_factor * n * k / E) # slots per expert
P = F.softmax(self.router(x), -1) # (n, E)
idx = (P + self.expert_bias).topk(k).indices # (n, k)
e = idx.flatten() # expert of each pair
onehot = F.one_hot(e, E) # (n k, E)
rank = (onehot.cumsum(0) * onehot).sum(1) - 1 # place in its queue
slot = torch.where(rank < S, e * S + rank, E * S) # E S: dropped
buf = x.new_zeros(E * S + 1, d) # + an overflow row
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: zeros
weights = P.gather(-1, idx) # (n, k): the p_i
out = (weights[..., None] * Y.reshape(n, k, d)).sum(1)
self.record(onehot.sum(0), (rank >= S).sum(), P)
return out.reshape(X.shape)
def run_experts(self, H):
"""Each expert's SwiGLU on its own buffer: (E, S, d) -> (E, S, d)."""
W = lambda name: torch.stack( # (E, d_in, d_out): one per expert
[getattr(e, name).weight for e in self.experts]).mT
return (F.silu(H @ W('W_g')) * (H @ W('W_1'))) @ W('W_2')
def record(self, counts, num_dropped, P):
"""Add a batch's assignments per expert and drops to the totals,
and keep its balancing loss, a measure of imbalance."""
self.load += counts
self.dropped += num_dropped
f = counts / counts.sum() # this batch's shares
self.aux_loss = self.num_experts * (f * P.mean(0)).sum()
def reset_stats(self):
self.load.zero_()
self.dropped.zero_()class MoELayer(nnx.Module):
"""Token-choice top-k mixture of SwiGLU d2l.FeedForward experts, each
with a buffer of S = capacity_factor * n k / E slots for n tokens."""
def __init__(self, num_hiddens, num_experts, num_active,
capacity_factor=1.25, *, rngs):
self.num_experts, self.num_active = num_experts, num_active
self.capacity_factor = capacity_factor
self.router = d2l.Linear(num_hiddens, num_experts, use_bias=False,
rngs=rngs)
self.experts = nnx.List([d2l.FeedForward(num_hiddens, rngs=rngs)
for _ in range(num_experts)])
# Added to the probabilities for the selection only; zero until a
# balancing method moves it
self.expert_bias = nnx.Variable(jnp.zeros(num_experts))
# Assignments per expert, dropped or not, and the dropped ones,
# counted by record() until reset_stats(); the last batch's
# balancing loss
self.load = nnx.Variable(jnp.zeros(num_experts))
self.dropped = nnx.Variable(jnp.zeros(()))
self.aux_loss = nnx.Variable(jnp.zeros(()))
def __call__(self, X):
x = X.reshape(-1, X.shape[-1]) # (n, d): the tokens
(n, d), E, k = x.shape, self.num_experts, self.num_active
S = math.ceil(self.capacity_factor * n * k / E) # slots per expert
P = jax.nn.softmax(self.router(x), -1) # (n, E)
_, idx = jax.lax.top_k(P + self.expert_bias[...], k) # (n, k)
e = idx.ravel() # expert of each pair
onehot = jax.nn.one_hot(e, E, dtype=jnp.int32) # (n k, E)
rank = (onehot.cumsum(0) * onehot).sum(1) - 1 # place in its queue
slot = jnp.where(rank < S, e * S + rank, E * S) # E S: dropped
buf = jnp.zeros((E * S, d), x.dtype).at[slot].set(
jnp.repeat(x, k, 0), mode='drop')
Y = self.run_experts(buf.reshape(E, S, d)).reshape(E * S, d)
Y = Y.at[slot].get(mode='fill', fill_value=0) # dropped: zeros
weights = jnp.take_along_axis(P, idx, -1) # (n, k): the p_i
out = (weights[..., None] * Y.reshape(n, k, d)).sum(1)
self.record(onehot.sum(0), (rank >= S).sum(), P)
return out.reshape(X.shape)
def run_experts(self, H):
"""Each expert's SwiGLU on its own buffer: (E, S, d) -> (E, S, d)."""
W = lambda name: jnp.stack( # (E, d_in, d_out): one per expert
[getattr(e, name).kernel[...] for e in self.experts])
return (jax.nn.silu(H @ W('W_g')) * (H @ W('W_1'))) @ W('W_2')
def record(self, counts, num_dropped, P):
"""Add a batch's assignments per expert and drops to the totals,
and keep its balancing loss, a measure of imbalance."""
self.load[...] += counts
self.dropped[...] += num_dropped
f = counts / counts.sum() # this batch's shares
self.aux_loss[...] = self.num_experts * (f * P.mean(0)).sum()
def reset_stats(self):
self.load[...] = jnp.zeros_like(self.load[...])
self.dropped[...] = jnp.zeros(())两个小工具函数 moe_layers(model) 与 active_params(model) 负责收集网络中全部 MoELayer 子模块,并统计单个词元前向传播参与的参数量(专家库的 \(k / E\) 加上全部共享参数):
def moe_layers(model):
"""The MoELayer modules of a model."""
return [m for m in model.modules() if isinstance(m, MoELayer)]
def active_params(model):
"""Parameters used per token: all but the unselected experts."""
return d2l.num_params(model) - sum(
d2l.num_params(l.experts) * (l.num_experts - l.num_active)
// l.num_experts for l in moe_layers(model))def moe_layers(model):
"""The MoELayer modules of a model."""
return [m for _, m in nnx.iter_graph(model) if isinstance(m, MoELayer)]
def active_params(model):
"""Parameters used per token: all but the unselected experts."""
return d2l.num_params(model) - sum(
d2l.num_params(l.experts) * (l.num_experts - l.num_active)
// l.num_experts for l in moe_layers(model))由于 d2l.TransformerBlock(11.1 节)接受 ffn_factory 钩子,用 8 专家 Top-2 MoELayer 替换稠密 FFN 只需传入一行 lambda:
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
blk = d2l.TransformerBlock(
256, num_heads=8, rngs=nnx.Rngs(d2l.get_key()),
ffn_factory=lambda rngs: MoELayer(256, 8, 2, rngs=rngs))
X = jax.random.normal(d2l.get_key(), (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,
rngs=nnx.Rngs(d2l.get_key()))
print(f'{d2l.num_params(moe)} parameters stored, '
f'{active_params(moe)} active per token')4198400 parameters stored, 1051136 active per token
11.7.3 路由坍缩与负载均衡
11.7.3.1 负载不均与正反馈
即便在初始化时,随机路由器权重也会把更多词元送往某些专家而非另一些。若训练时不加负载均衡机制,正反馈循环会将这种不对称放大为路由坍缩 (Shazeer 等 2017年):第 1 步收到更多词元的专家获得更大的梯度更新,第 2 步降低语言建模损失更快,第 3 步被 \(\nabla_{\mathbf{W}_r}\mathcal{L}\) 奖励以更高的路由器对数几率。若放任不管,该循环最终会让少数专家占据绝大多数 top-\(k\) 槽位,而其余专家因收到的词元过少而什么也学不到。
11.7.3.2 两种方案:辅助均衡损失对比无损失偏置控制器
Switch 辅助负载均衡损失 (Fedus 等 2022年):令 \(f_e = \frac{1}{n k} \sum_{t=1}^n \mathbb{I}[e \in T(\mathbf{x}_t)]\) 表示含 \(n\) 个词元的批量中分派给专家 \(e\) 的路由槽位经验比例,令 \(\bar{p}_e = \frac{1}{n}\sum_{t=1}^n p_e(\mathbf{x}_t)\) 表示赋予专家 \(e\) 的平均路由器概率。在训练损失中加入 \(\alpha \mathcal{L}_{\textrm{aux}}\),其中
\[ \mathcal{L}_{\textrm{aux}} \;=\; E \sum_{e=1}^{E} f_e \, \bar{p}_e, \tag{11.7.2}\]
对高负载专家(大 \(f_e\))的高概率 \(\bar{p}_e\) 施加惩罚,并在对所有 \(e\) 满足 \(f_e = 1/E\) 时达到最小值 \(\mathcal{L}_{\textrm{aux}} = 1\)。
无损失动态路由器偏置控制(Wang 等 (2024年),DeepSeek-V3 (DeepSeek-AI 等 2024年) 采用):由于 \(\nabla \mathcal{L}_{\textrm{aux}}\) 即使在专业化能降低语言建模损失时也会把词元表示推向均匀路由,该方法在不引入辅助梯度的情况下均衡负载(DeepSeek-V3 仅在其旁保留一个极小的序列级均衡损失)。具体而言,每个专家维护一个不可微的选择偏置 \(b_e\),仅在 top-\(k\) 选择内部加上(\(T(\mathbf{x}) = \textrm{argtop}_k(\mathbf{p}(\mathbf{x}) + \mathbf{b})\),保持门控权重 \(g_e(\mathbf{x})\) 无偏),并在每步后由速率为 \(\eta_b\) 的符号控制器更新:
\[ b_e \;\leftarrow\; b_e \;+\; \eta_b \, \textrm{sign}\!\left(\frac{1}{E} - f_e\right). \tag{11.7.3}\]
11.7.3.3 负载均衡方法对比
我们为 MoELayer 添加 balance(rate),并在 WikiText-103 上用 2 块字节级 GPT(\(E = 8, k = 1\),每个专家均为全宽 FFN,从而 1 个激活专家等价于 1 个稠密 FFN)训练 800 步,对比五种配置:(1)初始化,(2)无均衡,(3)冻结路由器对照(检验坍缩是否需要路由器-专家反馈),(4)Switch 辅助损失(\(\alpha = 0.01\)),以及(5)无损失偏置控制(\(\eta_b = 10^{-2}\)):
@d2l.add_to_class(MoELayer)
@torch.no_grad() # Not a gradient step
def balance(self, rate):
"""The controller: move each bias one step toward the even load, then
count the next batch's assignments afresh."""
self.expert_bias += rate * torch.sign(self.load.mean() - self.load)
self.load.zero_()
def train_moe_lm(model, data, optimizer, num_steps, aux_weight=0.0,
bias_rate=0.0):
"""d2l.train_steps with a balancing loss and the bias controller."""
device = d2l.try_gpu()
model.to(device)
layers, losses = moe_layers(model), []
for l in layers:
l.reset_stats()
while len(losses) < num_steps:
for X, Y in data.train_dataloader():
ce = F.cross_entropy(model(X.to(device)).flatten(0, 1),
Y.to(device).flatten())
optimizer.zero_grad()
(ce + aux_weight * sum(l.aux_loss for l in layers)).backward()
optimizer.step()
for l in layers:
l.balance(bias_rate)
losses.append(ce.detach())
if len(losses) == num_steps:
return torch.stack(losses).tolist()@d2l.add_to_class(MoELayer)
def balance(self, rate):
"""The controller: move each bias one step toward the even load, then
count the next batch's assignments afresh."""
load = self.load[...]
self.expert_bias[...] += rate * jnp.sign(load.mean() - load)
self.load[...] = jnp.zeros_like(load)
@nnx.jit # aux_weight and bias_rate are traced: one compilation for all
def moe_train_step(model, optimizer, X, Y, aux_weight, bias_rate):
def loss_fn(model):
ce = optax.softmax_cross_entropy_with_integer_labels(
model(X), Y).mean()
aux = sum(l.aux_loss[...] for l in moe_layers(model))
return ce + aux_weight * aux, ce
(_, ce), grads = nnx.value_and_grad(loss_fn, has_aux=True)(model)
optimizer.update(model, grads)
for l in moe_layers(model): # The controller: not a gradient step
l.balance(bias_rate)
return ce
def train_moe_lm(model, data, optimizer, num_steps, aux_weight=0.0,
bias_rate=0.0):
"""d2l.train_steps with a balancing loss and the bias controller."""
for l in moe_layers(model):
l.reset_stats()
losses = []
while len(losses) < num_steps:
for X, Y in data.train_dataloader():
losses.append(moe_train_step(model, optimizer, jnp.asarray(X),
jnp.asarray(Y), aux_weight,
bias_rate))
if len(losses) == num_steps:
return [float(l) for l in jax.device_get(losses)]为了检查验证集上的路由均衡情况,evaluate_moe 记录验证交叉熵、排序后的各专家词元份额以及被丢弃指派的比例,而 measure 将配置容量因子下的验证损失与无截断缓冲区(\(S = n k\),零丢弃)进行对比:
def evaluate_moe(model, data):
"""Validation loss; each expert layer's shares of the validation
tokens, busiest expert first; and the fraction of assignments dropped."""
layers = moe_layers(model)
for l in layers:
l.reset_stats()
loss = math.log(d2l.lm_perplexity(model, data.val_dataloader()))
shares = [sorted((l.load / l.load.sum()).tolist(), reverse=True)
for l in layers]
dropped = sum(float(l.dropped) for l in layers) / sum(
float(l.load.sum()) for l in layers)
return loss, shares, dropped
def measure(model, data):
"""The validation loss, the same with buffers that drop nothing, the
busiest expert's load in units of the even share, and the fraction
dropped; and the shares."""
layers = moe_layers(model)
val, shares, dropped = evaluate_moe(model, data)
peak = max(l.num_experts * s[0] for l, s in zip(layers, shares))
capacity = [l.capacity_factor for l in layers]
for l in layers: # S = n k slots: room for every assignment
l.capacity_factor = l.num_experts
val_all = evaluate_moe(model, data)[0]
for l, c in zip(layers, capacity):
l.capacity_factor = c
return (val, val_all, peak, dropped), sharesdef evaluate_moe(model, data):
"""Validation loss; each expert layer's shares of the validation
tokens, busiest expert first; and the fraction of assignments dropped."""
layers = moe_layers(model)
for l in layers:
l.reset_stats()
loss = math.log(d2l.lm_perplexity(model, data.val_dataloader()))
shares = [sorted((l.load / l.load.sum()).tolist(), reverse=True)
for l in layers]
dropped = sum(float(l.dropped) for l in layers) / sum(
float(l.load.sum()) for l in layers)
return loss, shares, dropped
def measure(model, data):
"""The validation loss, the same with buffers that drop nothing, the
busiest expert's load in units of the even share, and the fraction
dropped; and the shares."""
layers = moe_layers(model)
val, shares, dropped = evaluate_moe(model, data)
peak = max(l.num_experts * s[0] for l, s in zip(layers, shares))
capacity = [l.capacity_factor for l in layers]
for l in layers: # S = n k slots: room for every assignment
l.capacity_factor = l.num_experts
val_all = evaluate_moe(model, data)[0]
for l, c in zip(layers, capacity):
l.capacity_factor = c
return (val, val_all, peak, dropped), shares接下来,我们加载 WikiText103 并定义宽度为 \(d = 128\) 的 2 块字节级 GPT small_gpt(当 capacity_factor=None 时使用稠密 FFN,否则使用 8 专家 Top-1 MoELayer),同时定义用于冻结路由器对照组的 freeze_router:
data = d2l.WikiText103(batch_size=64, num_steps=128)
def small_gpt(vocab_size, capacity_factor=None):
"""Two blocks of width 128; with a capacity factor, each feed-forward
network becomes eight experts with one active per token."""
experts = lambda: MoELayer(128, 8, 1, capacity_factor=capacity_factor)
model = d2l.GPT(vocab_size, num_hiddens=128, num_heads=4, num_blks=2,
ffn_factory=None if capacity_factor is None else experts)
return model.to(d2l.try_gpu())
def freeze_router(model):
"""Keep every router at its initial weights: no gradient, no update."""
for l in moe_layers(model):
l.router.weight.requires_grad_(False)data = d2l.WikiText103(batch_size=64, num_steps=128)
def small_gpt(vocab_size, capacity_factor=None):
"""Two blocks of width 128; with a capacity factor, each feed-forward
network becomes eight experts with one active per token."""
experts = lambda rngs: MoELayer(128, 8, 1,
capacity_factor=capacity_factor, rngs=rngs)
return d2l.GPT(vocab_size, num_hiddens=128, num_heads=4, num_blks=2,
ffn_factory=None if capacity_factor is None else experts,
rngs=nnx.Rngs(d2l.get_key()))
def freeze_router(model):
"""Keep every router at its initial weights: a Variable that is not a
Param gets no gradient and no update."""
for l in moe_layers(model):
l.router.kernel = nnx.Variable(l.router.kernel[...])驱动函数 balancing_run 在选定均衡方案下以容量因子 \(\gamma = 1.25\) 训练全新的 small_gpt num_steps=800 步,并返回 measure 摘要:
def balancing_run(data, num_steps=800, frozen=False, aux_weight=0.0,
bias_rate=0.0):
"""Measure a fresh small MoE GPT after num_steps steps of training with
one balancing setting."""
model = small_gpt(len(data.vocab), capacity_factor=1.25)
if frozen:
freeze_router(model)
if num_steps:
optimizer = d2l.LMOptimizer(model, lr=2e-3, num_steps=num_steps,
warmup=100)
train_moe_lm(model, data, optimizer, num_steps, aux_weight,
bias_rate)
return measure(model, data)def balancing_run(data, num_steps=800, frozen=False, aux_weight=0.0,
bias_rate=0.0):
"""Measure a fresh small MoE GPT after num_steps steps of training with
one balancing setting."""
model = small_gpt(len(data.vocab), capacity_factor=1.25)
if frozen:
freeze_router(model)
if num_steps:
optimizer = d2l.LMOptimizer(model, lr=2e-3, num_steps=num_steps,
warmup=100)
train_moe_lm(model, data, optimizer, num_steps, aux_weight,
bias_rate)
return measure(model, data)对五种均衡方案各跑两个独立随机种子,制表呈现它们的验证损失(含缓冲区丢弃与不含丢弃)、峰值专家负载与丢弃率:
arms = {'initialization': dict(num_steps=0), 'no balancing': {},
'frozen router': dict(frozen=True),
'auxiliary loss': dict(aux_weight=0.01),
'bias controller': dict(bias_rate=0.01)}
print(f'spaces: {(data.val == ord(" ")).mean():.1%} of the validation bytes')
print(f'{"two runs each":>15} {"loss":^9} {"no drops":^9} '
f'{"busiest":^9} {"dropped":^7}')
shares = {} # The first run's shares
for name, kwargs in arms.items():
(a, shares[name]), (b, _) = [balancing_run(data, **kwargs)
for _ in range(2)]
print(f'{name:>15} {a[0]:.2f} {b[0]:.2f} {a[1]:.2f} {b[1]:.2f} '
f'{a[2]:3.1f}x {b[2]:3.1f}x {a[3]:3.0%} {b[3]:3.0%}')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%
arms = {'initialization': dict(num_steps=0), 'no balancing': {},
'frozen router': dict(frozen=True),
'auxiliary loss': dict(aux_weight=0.01),
'bias controller': dict(bias_rate=0.01)}
print(f'spaces: {(data.val == ord(" ")).mean():.1%} of the validation bytes')
print(f'{"two runs each":>15} {"loss":^9} {"no drops":^9} '
f'{"busiest":^9} {"dropped":^7}')
shares = {} # The first run's shares
for name, kwargs in arms.items():
(a, shares[name]), (b, _) = [balancing_run(data, **kwargs)
for _ in range(2)]
print(f'{name:>15} {a[0]:.2f} {b[0]:.2f} {a[1]:.2f} {b[1]:.2f} '
f'{a[2]:3.1f}x {b[2]:3.1f}x {a[3]:3.0%} {b[3]:3.0%}')spaces: 18.9% of the validation bytes
two runs each loss no drops busiest dropped
initialization 5.49 5.53 5.49 5.53 3.4x 3.1x 22% 29%
no balancing 1.71 1.76 1.66 1.69 2.4x 2.7x 24% 29%
frozen router 1.74 1.78 1.68 1.72 1.8x 2.7x 17% 23%
auxiliary loss 1.57 1.56 1.57 1.56 1.1x 1.2x 0% 0%
bias controller 1.60 1.56 1.59 1.55 1.8x 1.5x 3% 2%
将两个 MoE 层平均后的排序专家词元份额与均匀 \(1/8 = 12.5\%\) 参考线一同绘制,直观展示两种均衡机制如何防止路由坍缩:
ranks = list(range(1, 9))
mean_shares = [[sum(rank) / len(rank) for rank in zip(*s)]
for s in shares.values()] # Mean over the layers
d2l.plot(ranks, mean_shares + [[1 / 8] * 8], 'expert, busiest first',
'share of tokens', legend=list(shares) + ['even share'],
fmts=('C7x:', 'C0o-', 'C4v:', 'C1s--', 'C2^-.', 'k-'),
legend_loc='outside')ranks = list(range(1, 9))
mean_shares = [[sum(rank) / len(rank) for rank in zip(*s)]
for s in shares.values()] # Mean over the layers
d2l.plot(ranks, mean_shares + [[1 / 8] * 8], 'expert, busiest first',
'share of tokens', legend=list(shares) + ['even share'],
fmts=('C7x:', 'C0o-', 'C4v:', 'C1s--', 'C2^-.', 'k-'),
legend_loc='outside')不加均衡(no balancing)时,最忙的 3 个专家抢占了约 \(70\%\) 的路由词元,而最闲的专家几乎颗粒无收;在容量因子 \(\gamma = 1.25\) 下,四分之一到三分之一的指派遭到丢弃。冻结路由器(frozen router)最终偏斜略轻,但全新模型(initialization)本身就几乎和无均衡模型一样失衡,说明在这一规模下大部分偏斜来自输入分布而非专家学习与路由器更新之间的反馈;每行两次运行不足以区分二者(见 3)。相比之下,Switch 辅助损失与无损失偏置控制器都能将每个专家稳定在理想的 \(1/E = 12.5\%\) 份额附近(最忙专家不超过其两倍,在 \(\gamma = 1.25\) 下丢弃率至多几个百分点)。
11.7.4 混合专家语言模型
11.7.4.1 匹配激活参数下的 MoE GPT 对比稠密 GPT
在 WikiText-103 上训练 6,000 步,将负载均衡的 8 专家 Top-1 MoE GPT(\(N_{\textrm{active}} = 0.43\textrm{M}\),\(N_{\textrm{total}} = 2.26\textrm{M}\))与激活参数量及单词元浮点运算量完全相同的稠密 GPT(\(N_{\textrm{active}} = N_{\textrm{total}} = 0.43\textrm{M}\))对比,即可展示稀疏条件容量的 IsoFLOP 优势:
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
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
用 Switch 辅助损失(\(\alpha = 0.01\))对两个模型各运行两次独立的 \(6{,}000\) 步训练,并每 \(250\) 步评估一次验证损失,追踪稀疏模型何时反超稠密基线:
num_steps, every = 6000, 250
curves = {name: [] for name in capacity} # Validation loss every 250 steps
for run in range(2):
for name, c in capacity.items(): # Dense first, then MoE
model = small_gpt(len(data.vocab), capacity_factor=c)
optimizer = d2l.LMOptimizer(model, lr=2e-3, num_steps=num_steps,
warmup=100)
curve = []
for _ in range(num_steps // every): # Dense: no aux loss to add
train_moe_lm(model, data, optimizer, every, aux_weight=0.01)
curve.append(
math.log(d2l.lm_perplexity(model, data.val_dataloader())))
curves[name].append(curve)
dense, moe = curves['dense'][-1], curves['MoE'][-1]
ahead = next((every * (i + 1) for i, (m, d) in enumerate(zip(moe, dense))
if m < d), None)
print(f'run {run + 1}: dense {dense[-1]:.3f}, MoE {moe[-1]:.3f}; '
+ (f'MoE ahead from step {ahead}, ' if ahead else 'MoE never ahead, ')
+ f'{evaluate_moe(model, data)[2]:.1%} dropped at the end')
d2l.plot(list(range(every, num_steps + 1, every)),
[curves['dense'][0], curves['MoE'][0]], 'step',
'validation loss (nats)', legend=['dense', 'MoE'], fmts=('-', '--'))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
num_steps, every = 6000, 250
curves = {name: [] for name in capacity} # Validation loss every 250 steps
for run in range(2):
for name, c in capacity.items(): # Dense first, then MoE
model = small_gpt(len(data.vocab), capacity_factor=c)
optimizer = d2l.LMOptimizer(model, lr=2e-3, num_steps=num_steps,
warmup=100)
curve = []
for _ in range(num_steps // every): # Dense: no aux loss to add
train_moe_lm(model, data, optimizer, every, aux_weight=0.01)
curve.append(
math.log(d2l.lm_perplexity(model, data.val_dataloader())))
curves[name].append(curve)
dense, moe = curves['dense'][-1], curves['MoE'][-1]
ahead = next((every * (i + 1) for i, (m, d) in enumerate(zip(moe, dense))
if m < d), None)
print(f'run {run + 1}: dense {dense[-1]:.3f}, MoE {moe[-1]:.3f}; '
+ (f'MoE ahead from step {ahead}, ' if ahead else 'MoE never ahead, ')
+ f'{evaluate_moe(model, data)[2]:.1%} dropped at the end')
d2l.plot(list(range(every, num_steps + 1, every)),
[curves['dense'][0], curves['MoE'][0]], 'step',
'validation loss (nats)', legend=['dense', 'MoE'], fmts=('-', '--'))run 1: dense 1.331, MoE 1.268; MoE ahead from step 1250, 0.0% dropped at the end
run 2: dense 1.322, MoE 1.266; MoE ahead from step 1500, 0.0% dropped at the end
MoE 模型起步落后于稠密模型,但在前 2,000 步内即完成反超,最终在相同的单词元浮点运算开销下验证交叉熵低约 0.05 奈特。
11.7.4.2 已发布模型中的细粒度与共享专家
近期前沿 MoE 家族(表 11.7.1)从两方面改进了 Mixtral 8x7B 粗粒度的 8 专家 Top-2 配方(图 11.7.3):
- 细粒度专家切分:将 \(E\) 个全宽专家各自切分为 \(m\) 个宽度为 \(w / m\) 的专家,并将每个词元路由至 \(m E\) 个专家中的 \(m k\) 个;这保持存储与激活参数量不变,同时极大扩展了不同的激活专家组合数——例如在 \(m = 4\) 时从 \(\binom{16}{2} = 120\) 跃升至 \(\binom{64}{8} \approx 4.4 \times 10^9\)。已发布模型走得更远,采用 \(128\)–\(256\) 个专家并激活其中 \(4\)–\(8\) 个,同时也降低了激活比例。
- 共享专家 (Dai 等 2024年):专设 \(E_{\textrm{shared}} \ge 1\) 个窄专家在每个词元上无需路由即始终执行,让共享专家吸收通用的语法与格式变换,使路由专家能够专业化而避免冗余。
| 模型 | 每层专家数(\(E\)) | 激活数 \(k\) | 专家宽度 / \(d\) | 共享专家 | 存储 / 激活参数 |
|---|---|---|---|---|---|
| Mixtral 8x7B (Jiang 等 2024年) | 8 | 2 | 3.5 | 无 | 46.7B / 12.9B = 3.6 |
| DeepSeek-V3 (DeepSeek-AI 等 2024年) | 256 | 8 | 0.29 | 1 | 671B / 37B = 18 |
| Qwen3-235B (Yang 等 2025年) | 128 | 8 | 0.38 | 无 | 235B / 22B = 11 |
| gpt-oss-120b (OpenAI 2025年) | 128 | 4 | 1.0 | 无 | 117B / 5.1B = 23 |
11.7.5 小结
混合专家(MoE)层(式 11.7.1)用 \(E\) 个路由专家 FFN 替换稠密 FFN,每个词元仅激活得分最高的 \(k \ll E\) 个专家,从而将存储参数量 \(N_{\textrm{total}}\)(内存容量)与激活参数量 \(N_{\textrm{active}}\)(单词元浮点运算量)解耦。没有负载均衡时,专家利用率会严重偏斜:大部分偏斜在初始化时即已存在,而路由器与专家之间的正反馈可能将其放大为路由坍缩;Switch 辅助损失 \(\mathcal{L}_{\textrm{aux}} = E \sum_e f_e \bar{p}_e\)(式 11.7.2)与无损失动态路由器偏置 \(b_e \leftarrow b_e + \eta_b \textrm{sign}(1/E - f_e)\)(式 11.7.3)都能将专家负载维持在 \(1/E\) 附近。在匹配激活参数量与训练浮点运算量下,负载均衡的 MoE 语言模型能达到低于稠密 GPT 的验证交叉熵。近期开源权重 MoE 架构(表 11.7.1)进一步将专家切分为细粒度专家库(\(E \in [128, 256], k \in [4, 8]\))以扩展组合专业化,并常配以始终激活的共享专家(图 11.7.3)。
11.7.6 练习
\(k = 1\) 与 \(k > 1\) 重归一化下的路由器梯度。许多 MoE 层会按选中概率之和重新归一化:\(g_e(\mathbf{x}) = p_e(\mathbf{x}) / \sum_{j \in T(\mathbf{x})} p_j(\mathbf{x})\)。
- 证明:若在 \(k = 1\) 时同样施加这一重归一化,则 \(g_{e^*}(\mathbf{x}) = p_e(\mathbf{x}) / p_e(\mathbf{x}) \equiv 1\) 为常数,从而 \(\partial \textrm{MoE}(\mathbf{x}) / \partial \mathbf{W}_r = \mathbf{0}\),路由器永远收不到任务损失梯度。
- 在代码中验证我们的
MoELayer通过直接以原始概率加权每个选中专家(即与 Switch Transformer (Fedus 等 2022年) 一样令 \(g_{e^*}(\mathbf{x}) = p_{e^*}(\mathbf{x})\))避免了这一问题。
Switch 辅助损失的最小值与梯度。考虑 \(\mathcal{L}_{\textrm{aux}} = E \sum_{e=1}^E f_e \bar{p}_e\)(式 11.7.2),其中 \(f_e\) 视为截断梯度常数且 \(\sum_e \bar{p}_e = 1\)。
- 计算关于词元 \(t\) 的路由器对数几率 \(s_{t,e} = (\mathbf{x}_t \mathbf{W}_r)_e\) 的偏导数 \(\partial \mathcal{L}_{\textrm{aux}} / \partial s_{t,e}\),并证明其为零当且仅当所有经验负载相等(\(f_1 = \dots = f_E = 1/E\))。
- 利用柯西-施瓦茨不等式证明:当 \(\bar{p}_e = f_e\) 时,\(\mathcal{L}_{\textrm{aux}} \ge 1\),等号成立当且仅当 \(f_e = 1/E\);并求在完全坍缩至单一专家(\(f_1 = \bar{p}_1 = 1\))时它的最大值 \(E\)。
分离正反馈与输入分布偏斜。在
balancing_run中比较frozen router与no balancing在第 \(100, 200, 400, 800\) 步的表现。从全新模型的最忙专家份额(在我们的字节级模型中已约占三分之一)出发,在足够多的随机种子下,可训练路由器的最忙专家份额是否比冻结路由器偏离得更远?如果将所有专家输出投影W_2初始化为零、使所有专家在早期步骤产生相同输出,又会发生什么?无损失偏置控制器的步长动力学。以
bias_rate\(\eta_b \in \{10^{-4}, 10^{-3}, 10^{-2}, 10^{-1}\}\) 运行balancing_run,并绘制最忙专家份额与验证损失随训练步数的变化。为什么过大的控制器步长(\(\eta_b = 10^{-1}\))会导致专家负载在步与步之间剧烈振荡?极小数据区间下 MoE 的过拟合。重复 6,000 步的
dense对比MoE实验(11.7.4.1 节),但将data.train限制为仅前 \(65{,}536\) 字节(\(64\textrm{ KB}\)),使模型反复遍历同一段文本数百次。绘制dense与MoE的训练损失和验证损失:尽管两者每词元浮点运算量完全相同,为什么 \(2.26\textrm{M}\) 参数的 MoE 记住小语料的速度快得多,而且比 \(0.43\textrm{M}\) 参数的稠密模型更早开始过拟合?固定预算下的共享专家与细粒度切分。实现一个
SharedMoELayer,运行 1 个宽度为 \(w\) 的始终激活共享专家以及 \(E\) 个宽度为 \(w\) 的路由专家中的 Top-\(k\),并在small_gpt中匹配存储与激活专家宽度(每块存储 \(16 \times 170\)、激活 \(2 \times 170\))的前提下比较三种 FFN 配置:(a)粗粒度 \(E = 8, k = 1, w = 340\),(b)中粒度 \(E = 16, k = 2, w = 170\),以及(c)细粒度 + 共享 \(E_{\textrm{shared}} = 1, E = 15, k = 1, w = 170\)。比较它们在 800 步后的验证损失。