MoE混合专家模型详解:从Switch Transformer到DeepSeek-MoE
MoE架构的本质思想 混合专家模型(Mixture of Experts, MoE)的核心思想非常直观:不要让每个Token都经过所有参数的计算,而是为每个Token选择最合适的"专家"子网络来处理。这类似于医院分诊——患者不会被所有医生同时看诊,而是根据症状被分配给对应科室的专家。 MoE vs Dense模型对比 特性 Dense模型 MoE模型 参数利用率 100%(每个Token激活所有参数) 5-20%(仅激活部分专家) 总参数量 固定 可扩展至更大规模 训练成本 与参数量成正比 与激活参数量成正比 推理成本 与参数量成正比 与激活参数量成正比 模型容量 受限于计算预算 可用更大容量模型 MoE架构演进史 第一代:经典MoE(2017-2020) 最早的MoE思想可追溯到1991年Jacobs等人提出的自适应混合模型。在现代深度学习中,Google的GShard(2020)首次将MoE引入Transformer架构: # GShard MoE 的核心逻辑(简化版) import torch import torch.nn as nn import torch.nn.functional as F class MoELayer(nn.Module): def __init__(self, d_model, num_experts, top_k=2): super().__init__() self.num_experts = num_experts self.top_k = top_k # 门控网络 self.gate = nn.Linear(d_model, num_experts) # 专家网络(每个专家是一个FFN) self.experts = nn.ModuleList([ nn.Sequential( nn.Linear(d_model, d_model * 4), nn.GELU(), nn.Linear(d_model * 4, d_model) ) for _ in range(num_experts) ]) def forward(self, x): # x shape: (batch_size, seq_len, d_model) gate_logits = self.gate(x) # (batch, seq, num_experts) # 选择Top-K专家 gate_scores = F.softmax(gate_logits, dim=-1) topk_scores, topk_indices = torch.topk(gate_scores, self.top_k, dim=-1) # 归一化专家权重 topk_scores = topk_scores / topk_scores.sum(dim=-1, keepdim=True) # 计算加权输出 output = torch.zeros_like(x) for i in range(self.top_k): expert_idx = topk_indices[..., i] # (batch, seq) weight = topk_scores[..., i:i+1] # (batch, seq, 1) for e in range(self.num_experts): mask = (expert_idx == e) if mask.any(): expert_input = x[mask] expert_output = self.experts[e](expert_input) output[mask] += expert_output * weight[mask] return output 第二代:Switch Transformer(2021) Google在2021年提出的Switch Transformer将Top-2简化为Top-1路由,大幅降低了通信开销: ...