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\) を 2 倍にすると、訓練コスト(トークンあたり \(6 N\) FLOPs)も推論の計算量(トークンあたり \(2 N\) FLOPs)も 2 倍になる。モデルの保持パラメータ容量 \(N_{\textrm{total}}\) を拡大しつつ、トークンごとに実行されるアクティブパラメータ数 \(N_{\textrm{active}}\) を増やさずに済ませることはできるだろうか。
11.1 節 で見たように、フィードフォワードネットワークは密なブロックのパラメータ数の 3 分の 2(\(8 d^2\)、ブロック全体では \(12 d^2\))を占め、各トークンベクトル \(\mathbf{x} \in \mathbb{R}^d\) に対して独立に位置ごと(position-wise)に作用する。スパース混合エキスパート(sparse mixture-of-experts、MoE)層 (Jacobs ほか 1991年; Shazeer ほか 2017年; Lepikhin ほか 2021年; Fedus ほか 2022年) は、この独立性を活用する(図 11.7.1)。すなわち、ブロック内の単一の FFN を並列な \(E\) 個の FFN エキスパート群 \(\{\textrm{FFN}_1, \dots, \textrm{FFN}_E\}\) に置き換え、軽量な線形ルータ \(\mathbf{W}_r \in \mathbb{R}^{d \times E}\) を用いて各トークン \(\mathbf{x}\) を上位 \(k\) 個のエキスパートのみにディスパッチする(\(1 \le k \ll E\))。
11.7.1 条件付き計算:保持パラメータとアクティブパラメータ
\(L\) 層の MoE Transformer において、各ブロックがアテンションのパラメータ \(P_{\textrm{attn}}\)、ルーティングされる \(E\) 個の SwiGLU エキスパート(中間幅 \(w\)、エキスパートあたり \(P_{\textrm{exp}} = 3 d w\) 個のパラメータ)、および \(E_{\textrm{shared}}\) 個の常時アクティブな共有エキスパート(shared expert)を持つとする (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}}\) がそれぞれ異なるシステム資源を規定している点に注目しよう。
- トークンあたり FLOPs(訓練とプレフィル)は \(N_{\textrm{active}}\) に比例してスケールする(\(C_{\textrm{train}} \approx 6 N_{\textrm{active}} D\))。
- VRAM 容量は \(N_{\textrm{total}}\) に比例してスケールする。全 \(E\) 個のエキスパートをデバイスメモリ上に常駐させる必要があるためである。
- バッチデコードの帯域幅:バッチサイズ \(B = 1\) では、1 つのトークンが HBM からストリーミングするのは \(k\) 個のエキスパートのみである(\(N_{\textrm{active}}\) 個分の重みバイト数)。しかし、\(B\) トークンのバッチ全体で見ると、異なるトークンが異なるエキスパートを活性化させる。\(B \gg E / k\) になると、ほぼ全 \(E\) 個のエキスパートがバッチ内の少なくとも 1 つのトークンによって参照されるため、各デコードステップでは HBM からほぼ \(N_{\textrm{total}}\) 個分の重みバイト数をストリーミングする一方で、実行する演算は \(2 B N_{\textrm{active}}\) FLOPs にとどまる。
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}\) を計算し、集合 \(T(\mathbf{x}) \subset \{1, \dots, E\}\) としてスコア上位 \(k\) 個のエキスパートを選択する。続いて、その生の確率をそのまま重み \(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 固定容量エキスパートバッファへのトークンのディスパッチ
コンパイル実行や分散訓練では、各エキスパート \(e \in \{1, \dots, E\}\) はあらかじめ容量 \(S = \lceil \gamma \cdot n k / E \rceil\) スロットの固定バッファを、\(n\) トークンのバッチに対して確保する。ここで、\(n k / E\) は完全に均等化されたときのエキスパートあたりの負荷であり、\(\gamma \ge 1\) は容量係数(capacity factor)である(\(\gamma = E\) とすれば \(S = n k\) となり、ドロップは無効化される)。\(S\) 個を超えるトークン・エキスパート割り当てがエキスパート \(e\) に集中した場合、超過分の割り当てはドロップされる(式 11.7.1 への寄与が 0 になり、該当トークンは外側のブロックの残差スキップ接続をそのまま通過する)。図 11.7.2 は、6 個のトークンがこのディスパッチ処理を通過する様子を追ったものである。
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(())2 つの小さなユーティリティ関数 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 フックを受け取るため、密な FFN を 8 エキスパート・Top-2 の MoELayer に置き換えるにはラムダ式を 1 つ渡すだけでよい。
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 負荷の偏りと正のフィードバック
初期化の時点でさえ、ランダムなルータの重みによって、一部のエキスパートには他よりも多くのトークンが送られる。負荷分散(load balancing)の仕組みなしに訓練を進めると、正のフィードバックループ(positive-feedback loop)がこの非対称性を増幅し、ルーティング崩壊(routing collapse)を引き起こす (Shazeer ほか 2017年)。すなわち、ステップ 1 でより多くのトークンを受け取ったエキスパートほど大きな勾配更新を受け、ステップ 2 で言語モデリング損失をより速く減少させ、ステップ 3 で \(\nabla_{\mathbf{W}_r}\mathcal{L}\) から報酬を受けてルータのロジットがさらに高くなる。このまま放置すると、ごく少数のエキスパートが上位 \(k\) 個のスロットの大半を独占し、残りのエキスパートにはほとんどトークンが回らず何も学習できない状態に陥りうる。
11.7.3.2 2 つの解決策:補助負荷分散損失と損失不要バイアスコントローラ
Switch 補助負荷分散損失 (Fedus ほか 2022年):\(f_e = \frac{1}{n k} \sum_{t=1}^n \mathbb{I}[e \in T(\mathbf{x}_t)]\) をエキスパート \(e\) にディスパッチされたルーティングスロットの経験的な割合(\(n\) トークンのバッチ内)とし、\(\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}\]
この項は、高い確率 \(\bar{p}_e\) が負荷の集中したエキスパート(\(f_e\) が大きいもの)に与えられることにペナルティを課し、最小値 \(\mathcal{L}_{\textrm{aux}} = 1\) をとるのは \(f_e = 1/E\) がすべての \(e\) について成り立つときである。
損失不要の動的ルータバイアス制御(loss-free dynamic router bias control、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 負荷分散手法の比較
メソッド balance(rate) を MoELayer に追加し、2 ブロックのバイトレベル GPT(\(E = 8, k = 1\) とし、各エキスパートを全幅の FFN とすることで 1 個のアクティブなエキスパートが 1 個の密な FFN と等価になる設定)を用いて、WikiText-103 上で 800 ステップにわたり 5 つの設定を比較する。(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\)、ドロップ数 0)での値と比較する。
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 を読み込み、small_gpt を定義する。これは 2 ブロック・バイトレベルの GPT(幅 \(d = 128\))であり、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)5 つの負荷分散アームのそれぞれについて独立な 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.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\) のもとで全割り当ての 4 分の 1 から 3 分の 1 がドロップされる。ルータを凍結した場合(frozen router)は偏りがやや緩和されるものの、初期化直後の未訓練モデル(initialization)の時点ですでに負荷分散なしの場合と同程度の偏りがあるため、この規模では偏りの大部分はエキスパートの学習とルータの更新の間のフィードバックではなく入力分布に起因している。1 行あたり 2 回の実行ではこの 2 つの要因を切り分けることはできない(演習問題 3)。Switch 補助損失と損失不要のバイアスコントローラはいずれも、すべてのエキスパートを理想的な占有率 \(1/E = 12.5\%\) の近くに保っている(最も負荷の高いエキスパートでもその 2 倍未満に収まり、\(\gamma = 1.25\) でのドロップ率は高々数パーセントにとどまる)。
11.7.4 混合エキスパート言語モデル
11.7.4.1 アクティブパラメータ数を揃えた MoE GPT と密な GPT の比較
負荷分散された 8 エキスパート・Top-1 の MoE GPT(\(N_{\textrm{active}} = 0.43\textrm{M}\)、\(N_{\textrm{total}} = 2.26\textrm{M}\))を、アクティブパラメータ数とトークンあたり FLOPs が完全に同一の密な GPT(\(N_{\textrm{active}} = N_{\textrm{total}} = 0.43\textrm{M}\))と WikiText-103 上の 6,000 訓練ステップにわたって比較すると、スパースな条件付き容量がもたらす 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
両モデルを独立に 2 回ずつ \(6{,}000\) ステップにわたり Switch 補助損失(\(\alpha = 0.01\))のもとで訓練し、\(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 ステップ以内に追い抜き、同じトークンあたり FLOP コストでありながら検証交差エントロピーが約 0.05 nat 低い状態で訓練を終える。
11.7.4.2 公開モデルにおける細粒度エキスパートと共有エキスパート
近年の最先端 MoE モデル群(表 11.7.1)は、Mixtral 8x7B の粗粒度な 8 エキスパート・Top-2 のレシピを次の 2 つの方向で洗練させている(図 11.7.3)。
- 細粒度エキスパート分割(fine-grained expert segmentation):\(E\) 個の全幅エキスパートのそれぞれを \(m\) 個のエキスパート(幅 \(w / m\))に分割し、各トークンを \(m k\) 個へと(全 \(m E\) 個の中から)ルーティングすると、保持パラメータ数とアクティブパラメータ数の両方を変えないまま、異なるアクティブなエキスパートの組み合わせ数を、たとえば \(\binom{16}{2} = 120\) 通りから \(\binom{64}{8} \approx 4.4 \times 10^9\) 通りへと拡大できる(\(m = 4\) の場合)。公開モデルではさらに踏み込み、\(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)は、密な FFN をルーティングされる \(E\) 個のエキスパート FFN に置き換え、トークンごとに上位 \(k \ll E\) 個のエキスパートのみを活性化させることで、保持パラメータ数 \(N_{\textrm{total}}\)(メモリ容量)をアクティブパラメータ数 \(N_{\textrm{active}}\)(トークンあたり FLOPs)から切り離す。負荷分散を行わないとエキスパートの稼働率は大きく偏る。この偏りのかなりの部分は初期化時点ですでに存在しており、ルータとエキスパート間の正のフィードバックによってルーティング崩壊へと増幅されうるが、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\) 付近に保つ。アクティブパラメータ数と訓練 FLOPs を揃えた比較では、負荷分散された 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は、選択された各エキスパートを生の確率で重み付けすることで(\(g_{e^*}(\mathbf{x}) = p_{e^*}(\mathbf{x})\) とする Switch Transformer (Fedus ほか 2022年) と同様に)この問題を回避していることをコードで確認せよ。
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\) とする。
- 偏微分 \(\partial \mathcal{L}_{\textrm{aux}} / \partial s_{t,e}\)(トークン \(t\) のルータロジット \(s_{t,e} = (\mathbf{x}_t \mathbf{W}_r)_e\) に関する微分)を計算し、これが 0 になるのはすべての経験的負荷が等しいとき、かつそのときに限ること(\(f_1 = \dots = f_E = 1/E\))を示せ。
- コーシー・シュワルツの不等式を用いて、\(\bar{p}_e = f_e\) のときに \(\mathcal{L}_{\textrm{aux}} \ge 1\) が成り立ち、等号成立は \(f_e = 1/E\) のとき、かつそのときに限ることを証明せよ。また、その最大値 \(E\)(単一エキスパートへの完全な崩壊 \(f_1 = \bar{p}_1 = 1\) のとき)を求めよ。
正のフィードバックと入力分布の偏りの切り分け。
balancing_runにおいて、frozen routerアームとno balancingをステップ \(100, 200, 400, 800\) で比較せよ。初期状態のモデルにおける最上位エキスパートの占有率(本節のバイトレベルモデルではすでに約 3 分の 1 に達している)を起点としたとき、判別に十分な数のシードにわたって評価すると、訓練可能なルータの最上位エキスパート占有率は凍結ルータよりもそこから大きく離れるか。また、すべてのエキスパートの出力射影W_2を 0 で初期化し、初期ステップですべてのエキスパートが同一の出力を生成するようにすると何が起きるか。損失不要バイアスコントローラのステップサイズに関するダイナミクス。
balancing_runをbias_rate\(\eta_b \in \{10^{-4}, 10^{-3}, 10^{-2}, 10^{-1}\}\) で実行し、訓練ステップにわたる最上位エキスパートの占有率と検証損失をプロットせよ。コントローラのステップサイズが大きすぎる場合(\(\eta_b = 10^{-1}\))、なぜエキスパートの負荷がステップごとに振動するのか。極小データ領域における MoE の過学習。6,000 ステップの
dense対MoEの比較(11.7.4.1 節)を、ただしdata.trainを先頭の \(65{,}536\) バイト(\(64\textrm{ KB}\))のみに制限し、モデルが同じテキストを何百回も反復するようにして再実行せよ。denseとMoEの両方について訓練損失と検証損失をプロットせよ。両者がトークンあたりで全く同じ FLOPs を使用しているにもかかわらず、なぜ \(2.26\textrm{M}\) パラメータの MoE は小さなコーパスをはるかに速く暗記し、\(0.43\textrm{M}\) パラメータの密なモデルよりも早く過学習し始めるのか。固定予算下での共有エキスパートと細粒度化。常時アクティブな 1 個の共有エキスパート(幅 \(w\))に加えて Top-\(k\) 個(ルーティングされる \(E\) 個の幅 \(w\) のエキスパートから選択)を実行する
SharedMoELayerを実装し、保持およびアクティブなエキスパート幅を揃えた条件(ブロックあたり保持 \(16 \times 170\)、アクティブ \(2 \times 170\))のもとで、small_gpt内の 3 つの 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 ステップ後の検証損失を比較せよ。