Schwertlilien
As a recoder: notes and ideas.

2026-4-17-DeepseekMoE

DeepSeek MoE 专家梯度下降

PyTorch 会自动跟踪计算图中所有参与计算的张量的梯度。对于未被选中的专家,它们在本次前向传播中没有参与任何计算,因此它们的梯度自然为 0,优化器不会更新它们的参数。

Gate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class MoEGate(nn.Module):
def forward(self, hidden_states):
bsz,seq_len,h=hidden_states.shape
hidden_states=hidden_states.view(-1,h) # [B*L, H]

logits=F.linear(hidden_states,self.weights,None)
scores=logits.softmax(-1) # [B*L, N_experts]
# 选择 top-k 专家(默认 top-2)
topk_weight, topk_idx=torch.topk(scores,k=self.top_k,dim=-1,sorted=False)

if self.top_k>1 and selg.norm_topk_preb:
topk_weight=topk_weight/topk_weight.sum(dim=-1,keepdim=True)

aux_loss=self._compute_aux_loss(scores,topk_idx,bsz,seq_len) if self.training else None
return topk_idx,topk_weight,aux_loss # [B*L, K], [B*L, K], scalar

DeepseekMoE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class DeepseekMoE(nn.Module):
def forward(self, hidden_states):
identity = hidden_states
orig_shape = hidden_states.shape # [B, L, H]

# 步骤1:获取门控结果
topk_idx, topk_weight, aux_loss = self.gate(hidden_states)
hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) # [B*L, H]
flat_topk_idx = topk_idx.view(-1) # [B*L*K]

if self.training:
# 步骤2:关键操作!将每个 token 重复 K 次(K=num_experts_per_tok)
# 这样每个 token 都有 K 个副本,分别对应它选中的 K 个专家
hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0) # [B*L*K, H]

# 步骤3:创建空输出张量
y = torch.empty_like(hidden_states) # [B*L*K, H]

# 步骤4:遍历每个专家,只处理被它选中的 token 副本
for i, expert in enumerate(self.experts):
# 掩码:找出所有被分配给专家 i 的 token 副本
mask = (flat_topk_idx == i)
# 只对这些 token 副本进行专家计算
y[mask] = expert(hidden_states[mask])

# 步骤5:将 K 个专家的输出按权重加权求和
# 先 reshape 回 [B*L, K, H],然后在 K 维度加权求和
y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1) # [B*L, H]
y = y.view(*orig_shape) # [B, L, H]

# 步骤6:注入辅助损失到计算图中
y = AddAuxiliaryLoss.apply(y, aux_loss)
else:
# 推理模式使用更高效的实现(无梯度)
y = self.moe_infer(hidden_states, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)

# 加上共享专家的输出(如果有)
if self.config.n_shared_experts is not None:
y = y + self.shared_experts(identity)

return y
搜索
匹配结果数:
未搜索到匹配的文章。