IT评测·应用市场-qidao123.com

标题: 大模型条记:pytorch实现MOE [打印本页]

作者: 鼠扑    时间: 2025-2-13 17:37
标题: 大模型条记:pytorch实现MOE
0 导入库

  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
复制代码
1  专家模型

  1. #一个简单的专家模型,可以是任何神经网络架构
  2. class Expert(nn.Module):
  3.     def __init__(self, input_size, output_size):
  4.         super(Expert, self).__init__()
  5.         self.fc = nn.Linear(input_size, output_size)
  6.    
  7.     def forward(self, x):
  8.         return self.fc(x)
复制代码
2 MOE

  1. class MoE(nn.Module):
  2.     def __init__(self, num_experts, input_size, output_size,topk):
  3.         super(MoE, self).__init__()
  4.         self.num_experts = num_experts
  5.         self.topk=topk
  6.         self.experts = nn.ModuleList([Expert(input_size, output_size) for _ in range(num_experts)])
  7.         #创建多个专家
  8.         self.gating_network = nn.Linear(input_size, num_experts)  
  9.         #门控网络
  10.     def forward(self, x):
  11.         #假设x的维度是(batch,input_size)
  12.                   
  13.         gating_scores = self.gating_network(x)
  14.         # 门控网络决定权重 (选择每一个专家的概率)
  15.         #输出维度是(batch_size, num_experts)
  16.         topk_gate_scores,topk_gate_index=gating_scores.topk(topk,-1)
  17.         #选取topk个专家
  18.         #(batch_size,topk)
  19.         gating_scores_filtered=torch.full_like(gating_scores,fill_value=float("-inf"))
  20.         gating_scores_filtered=gating_scores_filtered.scatter(-1,topk_gate_index,topk_gate_scores)
  21.         gating_scores_filtered=F.softmax(gating_scores_filtered,dim=-1)
  22.         ##创建一个全为负无穷的张量 zeros,并将 topk_gate_scores 的值插入到这个张量的对应位置
  23.         #(batch_size,num_experts)
  24.                     
  25.         expert_outputs = torch.stack([expert(x) for expert in self.experts], dim=1)  
  26.         # 专家网络输出
  27.         #每个expert的输出维度是 (batch_size, output_size)
  28.         #stack沿着第二个维度堆叠,之后expert_outputs的维度是(batch_size,num_experts,output_size)
  29.                   
  30.         moe_output = torch.bmm(gating_scores_filtered.unsqueeze(1), expert_outputs).squeeze(1)
  31.         # 加权组合专家输出
  32.         #gating_scores.unsqueeze(1)——>(batch_size, 1,num_experts)
  33.         #torch.bmm(gating_scores.unsqueeze(1), expert_outputs)——>(batch_size,1,output_size)
  34.         #moe_output——>(batch_size,output_size)
  35.         return moe_output
复制代码

3  输入举例

  1. input_size = 10  
  2. # 输入特征是大小为10的向量
  3. output_size = 5  
  4. # 输出大小为5的向量
  5. num_experts = 3  
  6. # 3个专家
  7. moe_model = MoE(num_experts, input_size, output_size)
  8. # 初始化MOE模型
  9. input_vector = torch.randn(1, input_size)
  10. # 创建一个输入向量
  11. output_vector = moe_model(input_vector)
  12. # 前向传递
  13. print(output_vector.shape,output_vector)
  14. # 打印输出
  15. '''
  16. torch.Size([1, 5]) tensor([[ 2.7343e-04,  4.0966e-01, -3.6634e-01, -8.9064e-01,  4.0759e-01]],
  17.        grad_fn=<SqueezeBackward1>)
  18. '''
复制代码



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4