|
| 1 | +import torch |
| 2 | +import torch.nn.functional as F |
| 3 | + |
| 4 | + |
| 5 | +def fused_moe( |
| 6 | + hidden_states: torch.Tensor, |
| 7 | + w1: torch.Tensor, |
| 8 | + w2: torch.Tensor, |
| 9 | + gating_output: torch.Tensor, |
| 10 | + topk: int, |
| 11 | + renormalize: bool, |
| 12 | +) -> torch.Tensor: |
| 13 | + """ |
| 14 | + Args: |
| 15 | + hidden_states: [*, hidden_size] |
| 16 | + w1: [num_experts, intermediate_size * 2, hidden_size] |
| 17 | + w2: [num_experts, hidden_size, intermediate_size] |
| 18 | + gating_output: [*, num_experts] |
| 19 | + """ |
| 20 | + orig_shape = hidden_states.shape |
| 21 | + hidden_size = hidden_states.shape[-1] |
| 22 | + num_tokens = hidden_states.shape[:-1].numel() |
| 23 | + num_experts = w1.shape[0] |
| 24 | + intermediate_size = w2.shape[-1] |
| 25 | + dtype = hidden_states.dtype |
| 26 | + |
| 27 | + hidden_states = hidden_states.view(num_tokens, hidden_size) |
| 28 | + gating_output = gating_output.view(num_tokens, num_experts) |
| 29 | + topk_weights = gating_output.softmax(dim=-1, dtype=torch.float) |
| 30 | + topk_weights, selected_experts = topk_weights.topk(topk, dim=-1) |
| 31 | + if renormalize: |
| 32 | + topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True) |
| 33 | + topk_weights = topk_weights.to(dtype) |
| 34 | + |
| 35 | + final_hidden_states = None |
| 36 | + for expert_idx in range(num_experts): |
| 37 | + expert_w1 = w1[expert_idx] |
| 38 | + expert_w2 = w2[expert_idx] |
| 39 | + expert_mask = (selected_experts == expert_idx) |
| 40 | + expert_weights = (topk_weights * expert_mask).sum(dim=-1, keepdim=True) |
| 41 | + x = F.linear(hidden_states, expert_w1) |
| 42 | + gate = F.silu(x[:, :intermediate_size]) |
| 43 | + x = x[:, intermediate_size:] * gate |
| 44 | + x = F.linear(x, expert_w2) |
| 45 | + current_hidden_states = x * expert_weights |
| 46 | + if final_hidden_states is None: |
| 47 | + final_hidden_states = current_hidden_states |
| 48 | + else: |
| 49 | + final_hidden_states = final_hidden_states + current_hidden_states |
| 50 | + |
| 51 | + return final_hidden_states.view(orig_shape) # type: ignore |
0 commit comments