全文约0.6K字
阅读量:0
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) logits=F.linear(hidden_states,self.weights,None) scores=logits.softmax(-1) 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
|
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 topk_idx, topk_weight, aux_loss = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) flat_topk_idx = topk_idx.view(-1) if self.training: hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0) y = torch.empty_like(hidden_states) for i, expert in enumerate(self.experts): mask = (flat_topk_idx == i) y[mask] = expert(hidden_states[mask]) y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1) y = y.view(*orig_shape) 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
|