################################################################################ # Copyright(c)2020-2025 Shanghai Biren Technology Co., Ltd. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ################################################################################ from collections.abc import Iterable from typing import Optional, Union import torch import torch_br from fastcore.basics import patch_to import vllm from vllm.distributed import get_pp_group, tensor_model_parallel_all_reduce from vllm.forward_context import ForwardContext, get_forward_context from vllm.logger import init_logger from vllm.model_executor.layers.fused_moe import FusedMoE from vllm.model_executor.layers.rotary_embedding import MRotaryEmbedding from vllm.model_executor.model_loader.weight_utils import default_weight_loader from vllm.model_executor.models.qwen3_moe import Qwen3MoeModel from vllm.model_executor.models.utils import is_pp_missing_parameter from vllm.sequence import IntermediateTensors from vllm_br.v1.attention.backends.attention_v1 import ( SUPAFlashAttentionMetadata) logger = init_logger(__name__) @patch_to(vllm.model_executor.models.qwen3_moe.Qwen3MoeSparseMoeBlock) def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: # NOTE: hidden_states can have either 1D or 2D shape. orig_shape = hidden_states.shape if len(hidden_states.shape) == 3: hidden_states = hidden_states.squeeze(0) final_hidden_states = self.experts(hidden_states=hidden_states, router_logits=(self.gate.weight, None, None)) if hasattr(final_hidden_states, 'all_reduced'): # NOTE: this flag indicates that the final_hidden_states has been reduced in fused_moe delattr(final_hidden_states, 'all_reduced') elif self.tp_size > 1: final_hidden_states = tensor_model_parallel_all_reduce( final_hidden_states) return final_hidden_states.view(orig_shape) @patch_to(vllm.model_executor.models.qwen3_moe.Qwen3MoeAttention) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, ) -> torch.Tensor: forward_context: ForwardContext = get_forward_context() attn_metadata: SUPAFlashAttentionMetadata = forward_context.attn_metadata if attn_metadata is None: ## for dummy run return hidden_states seq_len = hidden_states.shape[-2] decode_seql = 512 if isinstance(attn_metadata, dict): attn_metadata = attn_metadata[self.attn.layer_name] kv_cache = self.attn.kv_cache[forward_context.virtual_engine] if kv_cache is not None: if seq_len <= decode_seql: if hasattr(self.qkv_proj, "qweight"): qkv_weight = self.qkv_proj.qweight.data qkv_scales = self.qkv_proj.scales.data elif hasattr(self.qkv_proj, "weight_packed"): qkv_weight = self.qkv_proj.weight_packed.data qkv_scales = self.qkv_proj.weight_scale.data else: qkv_weight = self.qkv_proj.weight qkv_scales = None if isinstance(self.rotary_emb, MRotaryEmbedding): assert len( self.rotary_emb.mrope_section ) == 3 and self.rotary_emb.mrope_section[ 1] == self.rotary_emb.mrope_section[ 2], "current only support mrope_section width and height are equal!" q, k, v = torch_br.br_qwen3_vl_prefix_attn_infer( hidden_states, qkv_weight, [self.q_size, self.kv_size, self.kv_size], self.head_dim, self.q_norm.variance_epsilon, self.q_norm.weight, self.k_norm.weight, self.rotary_emb.cos_sin_cache, kv_cache, positions, attn_metadata.slot_mapping, self.rotary_emb.mrope_section[1], bias=self.qkv_proj.bias, scales=qkv_scales) else: q, k, v = torch_br.br_qwen3_prefix_attn_infer( hidden_states, qkv_weight, [self.q_size, self.kv_size, self.kv_size], self.head_dim, self.q_norm.variance_epsilon, self.q_norm.weight, self.k_norm.weight, self.rotary_emb.sin_cache, self.rotary_emb.cos_cache, kv_cache, positions, attn_metadata.slot_mapping, bias=self.qkv_proj.bias, scales=qkv_scales) else: qkv, _ = self.qkv_proj(hidden_states) if isinstance(self.rotary_emb, MRotaryEmbedding): assert len( self.rotary_emb.mrope_section ) == 3 and self.rotary_emb.mrope_section[ 1] == self.rotary_emb.mrope_section[ 2], "current only support mrope_section width and height are equal!" q, k, v = torch_br.br_fused_rms_mrope_kvstore_infer( qkv, [self.q_size, self.kv_size, self.kv_size], self.head_dim, self.q_norm.variance_epsilon, self.q_norm.weight, self.k_norm.weight, self.rotary_emb.cos_sin_cache, kv_cache, positions, attn_metadata.slot_mapping, attn_metadata.block_table, attn_metadata.query_start_loc, attn_metadata.context_lens, self.rotary_emb.mrope_section[1]) else: q, k, v = torch_br.br_fused_rms_rope_kvstore_infer( qkv, [self.q_size, self.kv_size, self.kv_size], self.head_dim, self.q_norm.variance_epsilon, self.q_norm.weight, self.k_norm.weight, self.rotary_emb.sin_cache, self.rotary_emb.cos_cache, kv_cache, positions, attn_metadata.slot_mapping, attn_metadata.block_table, attn_metadata.query_start_loc, attn_metadata.context_lens) if hasattr(attn_metadata, 'do_cache'): attn_metadata.do_cache = False attn_output = self.attn(q, k, v) output, _ = self.o_proj(attn_output) return output else: return hidden_states def model_forward( self, input_ids: torch.Tensor, positions: torch.Tensor, intermediate_tensors: Optional[IntermediateTensors] = None, inputs_embeds: Optional[torch.Tensor] = None, ) -> Union[torch.Tensor, IntermediateTensors]: if get_pp_group().is_first_rank: if inputs_embeds is not None: hidden_states = inputs_embeds else: hidden_states = self.get_input_embeddings(input_ids) residual = None else: assert intermediate_tensors is not None hidden_states = intermediate_tensors["hidden_states"] residual = intermediate_tensors["residual"] if len(hidden_states.shape) == 2: hidden_states = hidden_states.unsqueeze(0) for i in range(self.start_layer, self.end_layer): layer = self.layers[i] hidden_states, residual = layer(positions, hidden_states, residual) if not get_pp_group().is_last_rank: return IntermediateTensors({ "hidden_states": hidden_states.squeeze(0) if hidden_states is not None else None, "residual": residual.squeeze(0) if residual is not None else None }) hidden_states, _ = self.norm(hidden_states, residual) # NOTE: convert back to 2D hidden_states = hidden_states.squeeze() if hidden_states.dim() == 1: hidden_states = hidden_states.unsqueeze(0) return hidden_states Qwen3MoeModel.forward = model_forward def Qwen3MoeModel_load_weights( self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: stacked_params_mapping = [ # (param_name, shard_name, shard_id) ("qkv_proj", "q_proj", "q"), ("qkv_proj", "k_proj", "k"), ("qkv_proj", "v_proj", "v"), ("gate_up_proj", "gate_proj", 0), ("gate_up_proj", "up_proj", 1), ] # Params for weights, fp8 weight scales, fp8 activation scales # (param_name, weight_name, expert_id, shard_id) expert_params_mapping = FusedMoE.make_expert_params_mapping( ckpt_gate_proj_name="gate_proj", ckpt_down_proj_name="down_proj", ckpt_up_proj_name="up_proj", num_experts=self.config.num_experts) params_dict = dict(self.named_parameters()) loaded_params: set[str] = set() for name, loaded_weight in weights: for (param_name, weight_name, shard_id) in stacked_params_mapping: # Skip non-stacked layers and experts (experts handled below). if weight_name not in name: continue # We have mlp.experts[0].gate_proj in the checkpoint. # Since we handle the experts below in expert_params_mapping, # we need to skip here BEFORE we update the name, otherwise # name will be updated to mlp.experts[0].gate_up_proj, which # will then be updated below in expert_params_mapping # for mlp.experts[0].gate_gate_up_proj, which breaks load. if "mlp.experts" in name: continue name = name.replace(weight_name, param_name) # Skip loading extra bias for GPTQ models. if ((name.endswith(".bias") or name.endswith("_bias")) and name not in params_dict): continue # Skip layers on other devices. if is_pp_missing_parameter(name, self): continue if name not in params_dict: continue param = params_dict[name] weight_loader = param.weight_loader weight_loader(param, loaded_weight, shard_id) break else: for mapping in expert_params_mapping: param_name, weight_name, expert_id, shard_id = mapping if weight_name not in name: continue name = name.replace(weight_name, param_name) # Skip layers on other devices. if is_pp_missing_parameter(name, self): continue # Skip loading extra bias for GPTQ models. if ((name.endswith(".bias") or name.endswith("_bias")) and name not in params_dict): continue param = params_dict[name] weight_loader = param.weight_loader weight_loader(param, loaded_weight, name, shard_id=shard_id, expert_id=expert_id) break else: # Skip loading extra bias for GPTQ models. if ((name.endswith(".bias") or name.endswith("_bias")) and name not in params_dict): continue # Skip layers on other devices. if is_pp_missing_parameter(name, self): continue # Remapping the name of FP8 kv-scale. if name.endswith("kv_scale"): remapped_kv_scale_name = name.replace( ".kv_scale", ".attn.kv_scale") if remapped_kv_scale_name not in params_dict: logger.warning_once( "Found kv scale in the checkpoint (e.g. %s), but not found the expected name in the model (e.g. %s). kv-scale is not loaded.", # noqa: E501 name, remapped_kv_scale_name, ) continue else: name = remapped_kv_scale_name param = params_dict[name] weight_loader = getattr(param, "weight_loader", default_weight_loader) weight_loader(param, loaded_weight) if name.find("norm.weight") != -1: param.data = param.data.to(torch.float32) loaded_params.add(name) return loaded_params Qwen3MoeModel.load_weights = Qwen3MoeModel_load_weights