|
| 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 Qwen3NextConfig |
| 19 | +from transformers.models.qwen3_next.modeling_qwen3_next import ( |
| 20 | + Qwen3NextSparseMoeBlock as OriginalQwen3NextMoeSparseMoeBlock, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +class Qwen3NextSparseMoeBlock(torch.nn.Module): |
| 25 | + def __init__( |
| 26 | + self, |
| 27 | + config: Qwen3NextConfig, |
| 28 | + original: OriginalQwen3NextMoeSparseMoeBlock, |
| 29 | + calibrate_all_experts: bool, |
| 30 | + ): |
| 31 | + super().__init__() |
| 32 | + self.num_experts = config.num_experts |
| 33 | + self.top_k = config.top_k |
| 34 | + self.norm_topk_prob = config.norm_topk_prob |
| 35 | + |
| 36 | + # gating |
| 37 | + self.calibrate_all_experts = calibrate_all_experts |
| 38 | + self.gate = original.gate |
| 39 | + self.experts = original.experts |
| 40 | + |
| 41 | + self.shared_expert = original.shared_expert |
| 42 | + self.shared_expert_gate = original.shared_expert_gate |
| 43 | + |
| 44 | + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 45 | + batch_size, sequence_length, hidden_dim = hidden_states.shape |
| 46 | + hidden_states = hidden_states.view(-1, hidden_dim) |
| 47 | + # router_logits: (batch * sequence_length, n_experts) |
| 48 | + router_logits = self.gate(hidden_states) |
| 49 | + |
| 50 | + routing_weights = torch.nn.functional.softmax( |
| 51 | + router_logits, dim=1, dtype=torch.float |
| 52 | + ) |
| 53 | + routing_weights, selected_experts = torch.topk( |
| 54 | + routing_weights, self.top_k, dim=-1 |
| 55 | + ) |
| 56 | + if self.norm_topk_prob: |
| 57 | + routing_weights /= routing_weights.sum(dim=-1, keepdim=True) |
| 58 | + # we cast back to the input dtype |
| 59 | + routing_weights = routing_weights.to(hidden_states.dtype) |
| 60 | + |
| 61 | + final_hidden_states = torch.zeros( |
| 62 | + (batch_size * sequence_length, hidden_dim), |
| 63 | + dtype=hidden_states.dtype, |
| 64 | + device=hidden_states.device, |
| 65 | + ) |
| 66 | + |
| 67 | + # One hot encode the selected experts to create an expert mask |
| 68 | + # this will be used to easily index which expert is going to be |
| 69 | + # sollicitated |
| 70 | + expert_mask = torch.nn.functional.one_hot( |
| 71 | + selected_experts, num_classes=self.num_experts |
| 72 | + ).permute(2, 1, 0) |
| 73 | + |
| 74 | + # Loop over all available experts in the model and perform the |
| 75 | + # computation on each expert |
| 76 | + # expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero() |
| 77 | + |
| 78 | + for expert_idx, expert_layer in enumerate(self.experts): |
| 79 | + idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0)) |
| 80 | + |
| 81 | + if self.calibrate_all_experts: |
| 82 | + expert_out = expert_layer(hidden_states)[top_x] |
| 83 | + else: |
| 84 | + expert_out = expert_layer(hidden_states[top_x]) |
| 85 | + |
| 86 | + # Index the correct hidden states and compute the expert hidden |
| 87 | + # state for the current expert. We need to make sure to multiply |
| 88 | + # the output hidden states by `routing_weights` on the |
| 89 | + # corresponding tokens (top-1 and top-2) |
| 90 | + if len(top_x) > 0: |
| 91 | + current_hidden_states = expert_out * routing_weights[top_x, idx, None] |
| 92 | + final_hidden_states.index_add_( |
| 93 | + 0, |
| 94 | + top_x, |
| 95 | + current_hidden_states.to(hidden_states.dtype), |
| 96 | + ) |
| 97 | + |
| 98 | + shared_expert_output = self.shared_expert(hidden_states) |
| 99 | + shared_expert_output = ( |
| 100 | + torch.nn.functional.sigmoid(self.shared_expert_gate(hidden_states)) |
| 101 | + * shared_expert_output |
| 102 | + ) |
| 103 | + |
| 104 | + final_hidden_states = final_hidden_states + shared_expert_output |
| 105 | + final_hidden_states = final_hidden_states.reshape( |
| 106 | + batch_size, sequence_length, hidden_dim |
| 107 | + ) |
| 108 | + return final_hidden_states, router_logits |
| 109 | + |
| 110 | + |
| 111 | +def replace( |
| 112 | + config: Qwen3NextConfig, |
| 113 | + module: OriginalQwen3NextMoeSparseMoeBlock, |
| 114 | + calibrate_all_experts: bool, |
| 115 | +): |
| 116 | + return Qwen3NextSparseMoeBlock( |
| 117 | + config=config, original=module, calibrate_all_experts=calibrate_all_experts |
| 118 | + ) |
0 commit comments