
混合专家模型深入剖析:从 GShard 到 DeepSeek V4
MoE 核心原理 混合专家(Mixture of Experts, MoE)的核心思想:用路由器选择性地激活部分参数,实现参数总量大但计算量小。 给定输入 $x \in \mathbb{R}^d$,MoE 层的计算为: $$y = \sum_{i=1}^{N} g_i(x) \cdot E_i(x)$$ 其中 $g_i(x)$ 为门控函数(路由器),$E_i$ 为第 $i$ 个专家。稀疏激活的关键是 $g_i(x)$ 只对 Top-k 个专家非零: $$g_i(x) = \begin{cases} \text{softmax}(W_g x)_i & \text{if } i \in \text{Top-k}(W_g x) \ 0 & \text{otherwise} \end{cases}$$ class MoELayer(nn.Module): def __init__(self, d_model, num_experts=8, top_k=2): super().__init__() self.gate = nn.Linear(d_model, num_experts, bias=False) self.experts = nn.ModuleList([ FeedForward(d_model) for _ in range(num_experts) ]) self.top_k = top_k self.num_experts = num_experts def forward(self, x): # x: (B, L, d) logits = self.gate(x) # (B, L, num_experts) topk_logits, topk_idx = logits.topk(self.top_k, dim=-1) topk_weights = F.softmax(topk_logits, dim=-1) output = torch.zeros_like(x) for i in range(self.top_k): expert_idx = topk_idx[..., i] # (B, L) weight = topk_weights[..., i:i+1] # (B, L, 1) for j in range(self.num_experts): mask = (expert_idx == j) if mask.any(): expert_input = x[mask] expert_output = self.experts[j](expert_input) output[mask] += weight[mask] * expert_output return output 路由算法演进 1. Top-k 路由(标准方案) 最常用的路由策略。每个 token 选择得分最高的 k 个专家。问题:容易出现"赢者通吃"——少数专家被过度使用。 ...








