main
py 322 lines 11.4 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 """Inference-only Qwen3_5 MTP model."""
4
5 from collections.abc import Iterable
6
7 import torch
8 from torch import nn
9
10 from vllm.compilation.decorators import support_torch_compile
11 from vllm.config import VllmConfig
12 from vllm.distributed import get_pp_group, tensor_model_parallel_all_gather
13 from vllm.logger import init_logger
14 from vllm.model_executor.layers.fused_moe.utils import (
15 is_model_fused_shared_expert_compatible,
16 )
17 from vllm.model_executor.layers.linear import ColumnParallelLinear
18 from vllm.model_executor.layers.logits_processor import LogitsProcessor
19 from vllm.model_executor.layers.vocab_parallel_embedding import (
20 ParallelLMHead,
21 VocabParallelEmbedding,
22 )
23 from vllm.model_executor.models.interfaces import LocalArgmaxMixin
24 from vllm.model_executor.models.qwen3_5 import (
25 Qwen3_5DecoderLayer,
26 Qwen3_5Model,
27 Qwen3_5RMSNorm,
28 )
29 from vllm.model_executor.models.qwen3_next import (
30 Qwen3NextSparseMoeBlock,
31 QwenNextMixtureOfExperts,
32 )
33 from vllm.model_executor.models.utils import sequence_parallel_chunk
34 from vllm.sequence import IntermediateTensors
35 from vllm.transformers_utils.configs.qwen3_5 import Qwen3_5TextConfig
36 from vllm.transformers_utils.configs.qwen3_5_moe import Qwen3_5MoeTextConfig
37
38 from .interfaces import (
39 MultiModalEmbeddings,
40 SupportsMultiModal,
41 SupportsPP,
42 _require_is_multimodal,
43 )
44 from .utils import (
45 AutoWeightsLoader,
46 PPMissingLayer,
47 _merge_multimodal_embeddings,
48 make_empty_intermediate_tensors_factory,
49 maybe_fuse_shared_experts,
50 maybe_prefix,
51 )
52
53 logger = init_logger(__name__)
54
55
56 @support_torch_compile(
57 dynamic_arg_dims={
58 "input_ids": 0,
59 # positions is of shape (3, seq_len) if mrope is enabled for qwen2-vl,
60 # otherwise (seq_len, ).
61 "positions": -1,
62 "intermediate_tensors": 0,
63 "inputs_embeds": 0,
64 "hidden_states": 0,
65 }
66 )
67 class Qwen3_5MultiTokenPredictor(nn.Module):
68 hf_to_vllm_mapper = Qwen3_5Model.hf_to_vllm_mapper
69
70 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
71 super().__init__()
72
73 model_config = vllm_config.model_config
74 quant_config = vllm_config.quant_config
75
76 config: Qwen3_5TextConfig | Qwen3_5MoeTextConfig = model_config.hf_text_config
77
78 self.config = config
79
80 self.vocab_size = config.vocab_size
81
82 self.mtp_start_layer_idx = config.num_hidden_layers
83 self.num_mtp_layers = getattr(config, "mtp_num_hidden_layers", 1)
84
85 self.embed_tokens = VocabParallelEmbedding(
86 self.vocab_size,
87 config.hidden_size,
88 )
89
90 # Workaround: mtp.fc is stored as BF16 in NVFP4 checkpoints but is
91 # missing from hf_quant_config.json exclude_modules. Force unquantized.
92 # Ref: https://github.com/vllm-project/vllm/pull/38650
93 # Ref: https://github.com/NVIDIA/Model-Optimizer/pull/1124
94 fc_quant = (
95 None
96 if (quant_config and quant_config.get_name() == "modelopt_fp4")
97 else quant_config
98 )
99 self.fc = ColumnParallelLinear(
100 self.config.hidden_size * 2,
101 self.config.hidden_size,
102 gather_output=True,
103 bias=False,
104 return_bias=False,
105 quant_config=fc_quant,
106 prefix=f"{prefix}.fc",
107 )
108
109 # GPTQ: quantized checkpoints may exclude MTP from quantization via
110 # quantization_config.dynamic with "-:pattern" entries. When detected,
111 # disable quantization for MTP layers so they use unquantized params.
112 original_quant = vllm_config.quant_config
113 if quant_config and quant_config.get_name() not in ("modelopt_fp4",):
114 hf_qc = getattr(model_config.hf_config, "quantization_config", None)
115 if isinstance(hf_qc, dict):
116 dynamic = hf_qc.get("dynamic", {})
117 if any(k.startswith("-:") and "mtp" in k for k in dynamic):
118 vllm_config.quant_config = None
119 self.layers = torch.nn.ModuleList(
120 Qwen3_5DecoderLayer(
121 vllm_config,
122 layer_type="full_attention",
123 prefix=f"{prefix}.layers.{idx}",
124 )
125 for idx in range(self.num_mtp_layers)
126 )
127 vllm_config.quant_config = original_quant
128 self.is_fused_shared_expert_enabled = is_model_fused_shared_expert_compatible(
129 self.layers,
130 Qwen3NextSparseMoeBlock,
131 "mlp",
132 )
133 self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
134 ["hidden_states", "residual"], config.hidden_size
135 )
136 self.norm = Qwen3_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
137 self.pre_fc_norm_hidden = Qwen3_5RMSNorm(
138 config.hidden_size, eps=config.rms_norm_eps
139 )
140 self.pre_fc_norm_embedding = Qwen3_5RMSNorm(
141 config.hidden_size, eps=config.rms_norm_eps
142 )
143
144 def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
145 return self.embed_tokens(input_ids)
146
147 def forward(
148 self,
149 input_ids: torch.Tensor,
150 positions: torch.Tensor,
151 hidden_states: torch.Tensor,
152 intermediate_tensors: IntermediateTensors | None = None,
153 inputs_embeds: torch.Tensor | None = None,
154 spec_step_idx: int = 0,
155 ) -> torch.Tensor:
156 # Branch on the inputs, not the rank: the drafter is built entirely on
157 # the last PP stage, where `is_first_rank` is False.
158 if intermediate_tensors is None:
159 if inputs_embeds is None:
160 inputs_embeds = self.embed_input_ids(input_ids)
161 assert hidden_states.shape[-1] == inputs_embeds.shape[-1]
162 inputs_embeds = self.pre_fc_norm_embedding(inputs_embeds)
163 hidden_states = self.pre_fc_norm_hidden(hidden_states)
164 hidden_states = torch.cat([inputs_embeds, hidden_states], dim=-1)
165 hidden_states = self.fc(hidden_states)
166 residual = None
167 else:
168 hidden_states = intermediate_tensors["hidden_states"]
169 residual = intermediate_tensors["residual"]
170
171 current_step_idx = spec_step_idx % self.num_mtp_layers
172 mtp_layer = self.layers[current_step_idx]
173 if mtp_layer.use_attn_reduce_scatter_for_moe:
174 assert hidden_states.shape[0] == positions.shape[-1]
175 hidden_states = sequence_parallel_chunk(hidden_states)
176 assert residual is None
177 hidden_states, residual = mtp_layer(
178 positions=positions,
179 hidden_states=hidden_states,
180 residual=residual,
181 )
182
183 if not get_pp_group().is_last_rank:
184 return IntermediateTensors(
185 {"hidden_states": hidden_states, "residual": residual}
186 )
187
188 hidden_states, _ = self.norm(hidden_states, residual)
189 if mtp_layer.use_attn_reduce_scatter_for_moe:
190 hidden_states = tensor_model_parallel_all_gather(hidden_states, 0)
191 hidden_states = hidden_states[: positions.shape[-1]]
192 return hidden_states
193
194 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
195 weights = maybe_fuse_shared_experts(
196 weights,
197 enabled=self.is_fused_shared_expert_enabled,
198 n_routed_experts=getattr(self.config, "num_experts", 0),
199 n_shared_experts=1,
200 ckpt_prefix="mlp.shared_expert",
201 )
202 loader = AutoWeightsLoader(self)
203 return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)
204
205
206 @support_torch_compile(
207 dynamic_arg_dims={
208 "input_ids": 0,
209 # positions is of shape (3, seq_len) if mrope is enabled for qwen2-vl,
210 # otherwise (seq_len, ).
211 "positions": -1,
212 "intermediate_tensors": 0,
213 "inputs_embeds": 0,
214 "hidden_states": 0,
215 }
216 )
217 class Qwen3_5MTP(LocalArgmaxMixin, nn.Module, SupportsMultiModal, SupportsPP):
218 packed_modules_mapping = {
219 "qkv_proj": [
220 "q_proj",
221 "k_proj",
222 "v_proj",
223 ],
224 "gate_up_proj": ["gate_proj", "up_proj"],
225 }
226
227 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
228 config = vllm_config.model_config.hf_text_config
229 self.vllm_config = vllm_config
230 self.quant_config = vllm_config.quant_config
231
232 super().__init__()
233 self.config = config
234 self.model = Qwen3_5MultiTokenPredictor(
235 vllm_config=vllm_config, prefix=maybe_prefix(prefix, "mtp")
236 )
237
238 if get_pp_group().is_last_rank:
239 self.lm_head = ParallelLMHead(
240 config.vocab_size,
241 config.hidden_size,
242 quant_config=self.quant_config,
243 prefix=maybe_prefix(prefix, "lm_head"),
244 )
245 if config.tie_word_embeddings:
246 self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens)
247 else:
248 self.lm_head = PPMissingLayer()
249
250 self.logits_processor = LogitsProcessor(config.vocab_size)
251
252 self.make_empty_intermediate_tensors = (
253 self.model.make_empty_intermediate_tensors
254 )
255
256 def embed_input_ids(
257 self,
258 input_ids: torch.Tensor,
259 multimodal_embeddings: MultiModalEmbeddings | None = None,
260 *,
261 is_multimodal: torch.Tensor | None = None,
262 ) -> torch.Tensor:
263 inputs_embeds = self._embed_text_input_ids(
264 input_ids,
265 self.model.embed_input_ids,
266 is_multimodal=is_multimodal,
267 )
268
269 if multimodal_embeddings is None or len(multimodal_embeddings) == 0:
270 return inputs_embeds
271
272 is_multimodal = _require_is_multimodal(is_multimodal)
273
274 inputs_embeds = _merge_multimodal_embeddings(
275 inputs_embeds=inputs_embeds,
276 multimodal_embeddings=multimodal_embeddings,
277 is_multimodal=is_multimodal,
278 )
279
280 return inputs_embeds
281
282 def forward( # type: ignore[override]
283 self,
284 input_ids: torch.Tensor,
285 positions: torch.Tensor,
286 hidden_states: torch.Tensor,
287 intermediate_tensors: IntermediateTensors | None = None,
288 inputs_embeds: torch.Tensor | None = None,
289 **kwargs: object,
290 ):
291 hidden_states = self.model(
292 input_ids, positions, hidden_states, intermediate_tensors, inputs_embeds
293 )
294 return hidden_states
295
296 def compute_logits(
297 self,
298 hidden_states: torch.Tensor,
299 spec_step_idx: int = 0,
300 ) -> torch.Tensor | None:
301 return self.logits_processor(self.lm_head, hidden_states)
302
303 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
304 def remap_weight_names(weights):
305 for name, weight in weights:
306 if name.startswith("mtp."):
307 name = name.replace("mtp.", "model.")
308 elif any(key in name for key in ["embed_tokens", "lm_head"]):
309 if "embed_tokens" in name:
310 name = name.replace("language_model.", "")
311 else:
312 continue
313 yield name, weight
314
315 loader = AutoWeightsLoader(self)
316 return loader.load_weights(remap_weight_names(weights))
317
318
319 class Qwen3_5MoeMTP(Qwen3_5MTP, QwenNextMixtureOfExperts):
320 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
321 super().__init__(vllm_config=vllm_config, prefix=prefix)
322 self.set_moe_parameters()