experts.py 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. '''
  2. Copyright 2020 The Microsoft DeepSpeed Team
  3. '''
  4. import torch
  5. import copy
  6. class Experts(torch.nn.Module):
  7. def __init__(self, expert, num_local_experts=1):
  8. super(Experts, self).__init__()
  9. self.deepspeed_experts = torch.nn.ModuleList(
  10. [copy.deepcopy(expert) for i in range(num_local_experts)])
  11. self.num_local_experts = num_local_experts
  12. # TODO: revisit allreduce for moe.gate...
  13. for expert in self.deepspeed_experts:
  14. # TODO: Create param groups to handle expert + data case (e.g. param.group = moe_group)
  15. for name, param in expert.named_parameters():
  16. param.allreduce = False
  17. def forward(self, inputs):
  18. chunks = inputs.chunk(self.num_local_experts, dim=1)
  19. expert_outputs = []
  20. for chunk, expert in zip(chunks, self.deepspeed_experts):
  21. out = expert(chunk)
  22. if type(out) is tuple:
  23. out = out[0] # Ignore the bias term for now
  24. expert_outputs += [out]
  25. expert_output = torch.cat(expert_outputs, dim=1)
  26. return expert_output