experts.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  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, expert_group_name=None):
  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. param.group_name = expert_group_name
  18. def forward(self, inputs):
  19. chunks = inputs.chunk(self.num_local_experts, dim=1)
  20. expert_outputs = []
  21. for chunk, expert in zip(chunks, self.deepspeed_experts):
  22. out = expert(chunk)
  23. if type(out) is tuple:
  24. out = out[0] # Ignore the bias term for now
  25. expert_outputs += [out]
  26. expert_output = torch.cat(expert_outputs, dim=1)
  27. return expert_output