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)
밀집 트랜스포머(11.6절)에서는 모든 토큰이 모든 매개변수를 사용합니다. 모델 용량 \(N \approx 12 L d^2\) 을 두 배로 키우면 학습 비용(토큰당 \(6 N\) FLOPs)도 두 배가 되고 추론 연산량(토큰당 \(2 N\) FLOPs)도 두 배가 됩니다. 그렇다면 토큰당 실행되는 활성 매개변수 \(N_{\textrm{active}}\) 는 늘리지 않으면서 모델의 저장 매개변수 용량 \(N_{\textrm{total}}\) 만 키울 수 있을까요?
11.1절 에서 살펴보았듯 피드포워드 신경망은 밀집 블록 매개변수의 3분의 2(\(12 d^2\) 중 \(8 d^2\))를 차지하며 각 토큰 벡터 \(\mathbf{x} \in \mathbb{R}^d\) 에 독립적으로 위치별 작용을 합니다. 희소 전문가 혼합(Sparse Mixture-of-Experts, MoE) 층 (Jacobs 기타 1991년; Shazeer 기타 2017년; Lepikhin 기타 2021년; Fedus 기타 2022년) 은 바로 이 독립성을 활용합니다(그림 11.7.1). 블록의 단일 FFN을 \(E\) 개의 병렬 FFN 전문가(expert) 뱅크 \(\{\textrm{FFN}_1, \dots, \textrm{FFN}_E\}\) 로 대체하고, 가벼운 선형 라우터(router) \(\mathbf{W}_r \in \mathbb{R}^{d \times E}\) 를 사용해 각 토큰 \(\mathbf{x}\) 를 점수가 가장 높은 상위-\(k\) 개 전문가(\(1 \le k \ll E\))로만 보냅니다.
11.7.1 조건부 연산: 저장 매개변수 대 활성 매개변수
각 블록이 어텐션 매개변수 \(P_{\textrm{attn}}\), 중간 폭 \(w\) 인 라우팅 대상 SwiGLU 전문가 \(E\) 개(전문가당 매개변수 \(P_{\textrm{exp}} = 3 d w\)), 그리고 항상 활성화되는 공유 전문가 \(E_{\textrm{shared}}\) 개 (Dai 기타 2024년) 를 갖는 \(L\) 층 MoE 트랜스포머에서는 \(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 용량은 \(E\) 개 전문가가 모두 장치 메모리에 상주해야 하므로 \(N_{\textrm{total}}\)에 비례합니다.
- 배치 디코드 대역폭: 배치 크기 \(B = 1\) 에서는 토큰 하나가 \(k\) 개 전문가만 HBM에서 스트리밍합니다(\(N_{\textrm{active}}\) 가중치 바이트). 그러나 토큰 \(B\) 개짜리 배치에서는 토큰마다 서로 다른 전문가를 활성화하므로, 일단 \(B \gg E / k\) 가 되면 거의 모든 \(E\) 개 전문가가 배치 내 적어도 한 토큰에 의해 호출되어 매 디코드 스텝마다 \(2 B N_{\textrm{active}}\) FLOPs를 수행하면서 거의 \(N_{\textrm{total}}\) 가중치 바이트를 HBM에서 스트리밍하게 됩니다.
11.7.2 전문가 혼합 층
11.7.2.1 상위-\(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})\) 위에서 재정규화하면 상위-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\) 은 용량 계수(capacity factor)입니다(\(\gamma = E\) 로 두면 \(S = n k\) 가 되어 토큰 드롭이 비활성화됨). 전문가 \(e\) 로 향하는 토큰–전문가 배정이 \(S\) 개를 넘으면 초과 배정은 드롭(drop)됩니다(식 11.7.1 에 0을 기여하므로 해당 토큰들은 바깥 블록의 잔차 스킵 연결만 그대로 통과함). 그림 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 훅을 받으므로, 밀집 FFN을 8-전문가 상위-2 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
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 불균등한 부하와 양성 피드백
초기화 시점부터도 무작위 라우터 가중치는 특정 전문가들에게 더 많은 토큰을 보냅니다. 부하 분산 메커니즘 없이 학습하면 양성 피드백 루프가 이 비대칭을 라우팅 붕괴(routing collapse) (Shazeer 기타 2017년) 로 증폭시킵니다. 스텝 1에서 더 많은 토큰을 받은 전문가가 더 큰 그레이디언트 업데이트를 받아 스텝 2에서 언어 모델링 손실을 더 빠르게 낮추고, 스텝 3에서 \(\nabla_{\mathbf{W}_r}\mathcal{L}\) 로부터 더 높은 라우터 로짓으로 보상받기 때문입니다. 이를 방치하면 소수의 전문가가 상위-\(k\) 슬롯 대부분을 독점하고 나머지 전문가들은 학습할 토큰조차 거의 받지 못하는 상태로 끝날 수 있습니다.
11.7.3.2 두 가지 해법: 보조 부하 분산 손실 대 무손실 편향 제어기
Switch 보조 부하 분산 손실 (Fedus 기타 2022년): 토큰 \(n\) 개짜리 배치에서 전문가 \(e\) 에 배정된 라우팅 슬롯의 경험적 비율을 \(f_e = \frac{1}{n k} \sum_{t=1}^n \mathbb{I}[e \in T(\mathbf{x}_t)]\) 라 하고, 전문가 \(e\) 에 부여된 평균 라우터 확률을 \(\bar{p}_e = \frac{1}{n}\sum_{t=1}^n p_e(\mathbf{x}_t)\) 라 합시다. 학습 손실에 \(\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\) 를 유지하여 상위-\(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 위에서 800 스텝 동안 2-블록 바이트 수준 GPT(\(E = 8, k = 1\), 활성 전문가 1개가 밀집 FFN 1개와 같도록 각 전문가를 전체 폭 FFN으로 설정)에 대해 다섯 가지 구성을 비교합니다. (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을 불러오고 capacity_factor=None일 때는 밀집 FFN을, 그 외에는 8-전문가 상위-1 MoELayer를 사용하는 폭 \(d = 128\) 의 2-블록 바이트 수준 GPT 생성 함수 small_gpt와 동결 라우터 대조군을 위한 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\) 아래에서 전체 배정의 4분의 1 내지 3분의 1이 드롭됩니다. 라우터를 동결하면(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-전문가 상위-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}\))와 비교하면 희소 조건부 용량의 등연산량(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 스텝 안에 추월한 뒤, 동일한 토큰당 FLOP 비용에서 약 0.05 nats 더 낮은 검증 교차 엔트로피로 마무리합니다.
11.7.4.2 공개 모델들의 세분화 전문가와 공유 전문가
최근의 최전선 MoE 모델 계열들(표 11.7.1)은 Mixtral 8x7B의 굵직한 8-전문가 상위-2 레시피를 두 가지 방향으로 정교화합니다(그림 11.7.3).
- 세분화된 전문가 분할(fine-grained expert segmentation): 전체 폭 전문가 \(E\) 개 각각을 폭 \(w / m\) 인 전문가 \(m\) 개로 쪼개고 각 토큰을 총 \(m E\) 개 중 \(m k\) 개로 라우팅하면, 저장 및 활성 매개변수 수는 그대로 유지하면서 서로 다른 활성 전문가 조합의 수를 크게 넓힐 수 있습니다(예: \(m = 4\) 일 때 \(\binom{16}{2} = 120\) 개에서 \(\binom{64}{8} \approx 4.4 \times 10^9\) 개로 증가). 공개된 최신 모델들은 한 걸음 더 나아가 \(128\)–\(256\) 개 전문가 중 \(4\)–\(8\) 개만 활성화함으로써 활성 비율 자체도 낮춥니다.
- 공유 전문가(shared experts) (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는 Switch Transformer (Fedus 기타 2022년) 와 마찬가지로 선택된 각 전문가에 원래 확률 그대로 가중치를 부여하여(\(g_{e^*}(\mathbf{x}) = p_{e^*}(\mathbf{x})\)) 이 문제를 피함을 코드로 검증하십시오.
Switch 보조 손실의 최솟값과 그레이디언트. \(f_e\) 를 그레이디언트 차단 상수로 취급하고 \(\sum_e \bar{p}_e = 1\) 일 때 \(\mathcal{L}_{\textrm{aux}} = E \sum_{e=1}^E f_e \bar{p}_e\)(식 11.7.2)를 생각합시다.
- 토큰 \(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\)), 그리고 오직 그때만 이 값이 0이 됨을 보이십시오.
- \(\bar{p}_e = f_e\) 일 때 코시–슈바르츠 부등식을 이용해 \(\mathcal{L}_{\textrm{aux}} \ge 1\) 이며 등호 성립 필요충분조건이 \(f_e = 1/E\) 임을 증명하고, 단일 전문가로 완전히 붕괴했을 때(\(f_1 = \bar{p}_1 = 1\)) 최댓값 \(E\) 를 가짐을 구하십시오.
입력 분포 쏠림에서 양성 피드백 분리하기.
balancing_run에서 스텝 \(100, 200, 400, 800\) 에 걸쳐frozen router실험군을no balancing과 비교하십시오. 초기 모델의 최상위 전문가 점유율(바이트 수준 모델에서는 이미 약 3분의 1)에서 출발할 때, 구분할 수 있을 만큼 충분한 시드에서 학습 가능한 라우터의 최상위 전문가 점유율이 동결 라우터보다 더 멀리 벌어집니까? 또한 초반 스텝에서 모든 전문가가 동일한 출력을 내도록 모든 전문가의 출력 투영W_2를 0으로 초기화하면 어떤 현상이 일어납니까?무손실 편향 제어기의 스텝 크기 동역학.
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의 학습 손실 및 검증 손실을 함께 그리고, 두 모델이 토큰당 정확히 동일한 FLOPs를 쓰는데도 왜 \(2.26\textrm{M}\) 매개변수 MoE가 \(0.43\textrm{M}\) 매개변수 밀집 모델보다 작은 말뭉치를 훨씬 빨리 암기하고 더 일찍 과적합되기 시작하는지 설명하십시오.고정 예산에서의 공유 전문가와 세분성 비교. 항상 활성화되는 폭 \(w\) 의 공유 전문가 1개와 폭 \(w\) 의 라우팅 전문가 \(E\) 개 중 상위-\(k\) 개를 함께 실행하는
SharedMoELayer를 구현하고, 저장 및 활성 전문가 총 폭을 일치시킨 조건(블록당 저장 \(16 \times 170\), 활성 \(2 \times 170\))에서small_gpt내부의 세 가지 FFN 구성을 비교하십시오: (a) 굵직한(coarse) 전문가 \(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 스텝 후의 검증 손실을 비교하십시오.