1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| def self.gate(self, hidden_states: torch.Tensor): """ x -> linear(dim, num_experts) -> topk(k) -> (num_tokens, topk) """ batch_size, seq_len, hidden_dim = hidden_states.shape hidden_states = hidden_states.view(-1, hidden_dim) logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32), None) scores = logits.softmax(dim=-1, dtype=torch.float32)
topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False) topk_weight = topk_weight * self.routed_scaling_factor return topk_idx, topk_weight
def moe(self, hidden_states: torch.Tensor, topk_ids: torch.Tensor, topk_weight: torch.Tensor) -> torch.Tensor: """ Args: hidden_states shape = (num_tokens, dim) topk_ids shape = (num_tokens, topk) topk_weight shape = (num_tokens, topk)
Returns: hidden_states """ cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))) cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(dim=0) indices = topk_ids.view(-1).argsort() sorted_tokens = hidden_states[indices // topk_ids.shape[1]]
outputs = [] start_idx = 0 for i, num_tokens in enumerate(tokens_per_expert): if num_tokens == 0: continue end_idx = start_idx + num_tokens expert = self.experts[i + self.ep_rank * self.experts_per_rank] tokens_for_this_expert = sorted_tokens[start_idx:end_idx] expert_out = expert(tokens_for_this_expert) outputs.append(expert_out) start_idx = end_idx
outs = torch.cat(outputs, dim=0) if outputs else sorted_tokens.new_empty(0)
new_x = torch.empty_like(outs) new_x[indices] = outs hidden_states = ( new_x.view(*topk_ids.shape, -1) .type(topk_weight.dtype) .mul_(topk_weight.unsqueeze(dim=-1)) .sum(dim=1) .type(new_x.dtype) ) return hidden_states
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: """ hidden_states shape (bsz, seqlen, dim) """ residuals = hidden_states orig_shape = hidden_states.shape topk_indices, topk_weights = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) hidden_states = self.moe(hidden_states, topk_indices, topk_weights).view(*orig_shape) hidden_states = hidden_states + self.shared_experts(residuals) return hidden_states
|