|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import torch |
| 18 | +from transformers.models import Qwen3MoeConfig |
| 19 | +from transformers.models.qwen3_moe.modeling_qwen3_moe import ( |
| 20 | + Qwen3MoeSparseMoeBlock as OriginalQwen3MoeSparseMoeBlock, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +class Qwen3MoeSparseMoeBlock(torch.nn.Module): |
| 25 | + def __init__( |
| 26 | + self, config: Qwen3MoeConfig, original: OriginalQwen3MoeSparseMoeBlock |
| 27 | + ): |
| 28 | + super().__init__() |
| 29 | + self.num_experts = config.num_experts |
| 30 | + self.top_k = config.top_k |
| 31 | + self.norm_topk_prob = config.norm_topk_prob |
| 32 | + |
| 33 | + # gating |
| 34 | + self.gate = original.gate |
| 35 | + self.experts = original.experts |
| 36 | + |
| 37 | + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 38 | + batch_size, sequence_length, hidden_dim = hidden_states.shape |
| 39 | + hidden_states = hidden_states.view(-1, hidden_dim) |
| 40 | + # router_logits: (batch * sequence_length, n_experts) |
| 41 | + router_logits = self.gate(hidden_states) |
| 42 | + |
| 43 | + routing_weights = torch.nn.functional.softmax( |
| 44 | + router_logits, dim=1, dtype=torch.float |
| 45 | + ) |
| 46 | + routing_weights, selected_experts = torch.topk( |
| 47 | + routing_weights, self.top_k, dim=-1 |
| 48 | + ) |
| 49 | + if self.norm_topk_prob: # only diff with mixtral sparse moe block! |
| 50 | + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) |
| 51 | + # we cast back to the input dtype |
| 52 | + routing_weights = routing_weights.to(hidden_states.dtype) |
| 53 | + final_hidden_states = torch.zeros( |
| 54 | + (batch_size * sequence_length, hidden_dim), |
| 55 | + dtype=hidden_states.dtype, |
| 56 | + device=hidden_states.device, |
| 57 | + ) |
| 58 | + |
| 59 | + # One hot encode the selected experts to create an expert mask |
| 60 | + # this will be used to easily index which expert is going to be sollicitated |
| 61 | + expert_mask = torch.nn.functional.one_hot( |
| 62 | + selected_experts, num_classes=self.num_experts |
| 63 | + ).permute(2, 1, 0) |
| 64 | + |
| 65 | + for expert_idx in range(len(self.experts)): |
| 66 | + expert_layer = self.experts[expert_idx] |
| 67 | + idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0)) |
| 68 | + # Index the correct hidden states and compute the expert hidden state for |
| 69 | + # the current expert. We need to make sure to multiply the output hidden |
| 70 | + # states by `routing_weights` on the corresponding tokens (top-1 and top-2) |
| 71 | + current_state = hidden_states[None, top_x].reshape(-1, hidden_dim) |
| 72 | + expert_output = expert_layer(current_state) |
| 73 | + current_hidden_states = expert_output * routing_weights[top_x, idx, None] |
| 74 | + # However `index_add_` only support torch tensors for indexing so we'll use |
| 75 | + # the `top_x` tensor here. |
| 76 | + final_hidden_states.index_add_( |
| 77 | + 0, top_x, current_hidden_states.to(hidden_states.dtype) |
| 78 | + ) |
| 79 | + |
| 80 | + final_hidden_states = final_hidden_states.reshape( |
| 81 | + batch_size, sequence_length, hidden_dim |
| 82 | + ) |
| 83 | + return final_hidden_states, router_logits |
| 84 | + |
| 85 | + |
| 86 | +def replace(config: Qwen3MoeConfig, module: OriginalQwen3MoeSparseMoeBlock): |
| 87 | + return Qwen3MoeSparseMoeBlock(config=config, original=module) |
0 commit comments