main
py 273 lines 10.4 KB
Raw
1 #
2 # Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
3 # Copyright 2023 The vLLM team.
4 #
5 # This file is a part of the vllm-ascend project.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18
19 # Adapted from
20 # https://github.com/vllm-project/vllm/blob/v0.7.3/vllm/model_executor/models/deepseek_mtp.py
21 from collections.abc import Iterable
22
23 import torch
24 import torch.nn as nn
25
26 from vllm.compilation.decorators import support_torch_compile
27 from vllm.config import VllmConfig
28
29 # SPDX-License-Identifier: Apache-2.0
30 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
31 from vllm.model_executor.layers.fused_moe import (
32 fused_moe_make_expert_params_mapping,
33 )
34 from vllm.model_executor.layers.layernorm import RMSNorm
35 from vllm.model_executor.layers.logits_processor import LogitsProcessor
36 from vllm.model_executor.layers.vocab_parallel_embedding import (
37 VocabParallelEmbedding,
38 )
39 from vllm.model_executor.model_loader.weight_utils import default_weight_loader
40 from vllm.model_executor.models.deepseek_mtp import (
41 DeepSeekMultiTokenPredictor,
42 DeepSeekMultiTokenPredictorLayer,
43 SharedHead,
44 )
45 from vllm.model_executor.models.utils import maybe_prefix
46 from vllm.sequence import IntermediateTensors
47
48 from .openpangu import OpenPanguDecoderLayer
49
50
51 class OpenPanguMultiTokenPredictorLayer(DeepSeekMultiTokenPredictorLayer):
52 def __init__(self, vllm_config: VllmConfig, prefix: str) -> None:
53 nn.Module.__init__(self)
54
55 speculative_config = vllm_config.speculative_config
56 assert speculative_config is not None
57 config = speculative_config.draft_model_config.hf_config
58 self.config = config
59 quant_config = vllm_config.quant_config
60
61 self.enorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
62 self.hnorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
63 self.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
64 self.shared_head = SharedHead(
65 config=config,
66 quant_config=quant_config,
67 prefix=maybe_prefix(prefix, "shared_head"),
68 )
69 self.mtp_block = OpenPanguDecoderLayer(config, prefix, vllm_config)
70
71
72 class OpenPanguMultiTokenPredictor(DeepSeekMultiTokenPredictor):
73 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
74 nn.Module.__init__(self)
75 config = vllm_config.model_config.hf_config
76 self.mtp_start_layer_idx = config.num_hidden_layers
77 self.num_mtp_layers = config.num_nextn_predict_layers
78 # to map the exact layer index from weights
79 self.layers = torch.nn.ModuleDict(
80 {
81 str(idx): OpenPanguMultiTokenPredictorLayer(
82 vllm_config, f"{prefix}.layers.{idx}"
83 )
84 for idx in range(
85 self.mtp_start_layer_idx,
86 self.mtp_start_layer_idx + self.num_mtp_layers,
87 )
88 }
89 )
90 self.embed_tokens = VocabParallelEmbedding(
91 config.vocab_size,
92 config.hidden_size,
93 )
94 self.logits_processor = LogitsProcessor(config.vocab_size)
95
96
97 @support_torch_compile
98 class OpenPanguMTP(nn.Module):
99 def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
100 super().__init__()
101 self.config = vllm_config.model_config.hf_config
102 self.model = OpenPanguMultiTokenPredictor(
103 vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
104 )
105
106 def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
107 return self.model.embed_input_ids(input_ids)
108
109 def forward(
110 self,
111 input_ids: torch.Tensor | None,
112 positions: torch.Tensor,
113 hidden_states: torch.Tensor,
114 intermediate_tensors: IntermediateTensors | None = None,
115 inputs_embeds: torch.Tensor | None = None,
116 spec_step_idx: int = 0,
117 ) -> torch.Tensor:
118 hidden_states = self.model(
119 input_ids,
120 positions,
121 hidden_states,
122 inputs_embeds,
123 spec_step_idx,
124 )
125 return hidden_states
126
127 def compute_logits(
128 self,
129 hidden_states: torch.Tensor,
130 spec_step_idx: int = 0,
131 ) -> torch.Tensor | None:
132 return self.model.compute_logits(hidden_states, spec_step_idx)
133
134 def get_spec_layer(self, name):
135 if (
136 "layers" in name
137 and hasattr(self.config, "num_nextn_predict_layers")
138 and self.config.num_nextn_predict_layers > 0
139 ):
140 layer_idx = int(name.split("layers.")[-1].split(".")[0])
141 mtp_idx = layer_idx - self.config.num_hidden_layers
142 if mtp_idx >= 0 and mtp_idx < self.config.num_nextn_predict_layers:
143 return layer_idx
144 return None
145
146 def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
147 stacked_params_mapping = [
148 ("gate_up_proj", "gate_proj", 0),
149 ("gate_up_proj", "up_proj", 1),
150 ("fused_qkv_a_proj", "q_a_proj", 0),
151 ("fused_qkv_a_proj", "kv_a_proj_with_mqa", 1),
152 ]
153
154 expert_params_mapping = fused_moe_make_expert_params_mapping(
155 self,
156 ckpt_gate_proj_name="gate_proj",
157 ckpt_down_proj_name="down_proj",
158 ckpt_up_proj_name="up_proj",
159 num_experts=self.config.n_routed_experts,
160 )
161
162 params_dict = dict(self.named_parameters())
163 loaded_params: set[str] = set()
164 for name, loaded_weight in weights:
165 if "rotary_emb.inv_freq" in name:
166 continue
167 spec_layer = self.get_spec_layer(name)
168 if spec_layer is None:
169 continue
170
171 name = self._rewrite_spec_layer_name(spec_layer, name)
172 for param_name, weight_name, shard_id in stacked_params_mapping:
173 # Skip non-stacked layers and experts (experts handled below).
174 if weight_name not in name:
175 continue
176 # We have mlp.experts[0].gate_proj in the checkpoint.
177 # Since we handle the experts below in expert_params_mapping,
178 # we need to skip here BEFORE we update the name, otherwise
179 # name will be updated to mlp.experts[0].gate_up_proj, which
180 # will then be updated below in expert_params_mapping
181 # for mlp.experts[0].gate_gate_up_proj, which breaks load.
182 if ("mlp.experts." in name) and name not in params_dict:
183 continue
184 name_mapped = name.replace(weight_name, param_name)
185
186 # QKV fusion is optional, fall back to normal
187 # weight loading if it's not enabled
188 if (
189 param_name == "fused_qkv_a_proj"
190 ) and name_mapped not in params_dict:
191 continue
192 else:
193 name = name_mapped
194
195 # Skip loading extra bias for GPTQ models.
196 if name.endswith(".bias") and name not in params_dict:
197 continue
198
199 param = params_dict[name]
200 weight_loader = param.weight_loader
201 weight_loader(param, loaded_weight, shard_id)
202 break
203 else:
204 for mapping in expert_params_mapping:
205 (
206 expert_param_name,
207 expert_weight_name,
208 expert_id,
209 expert_shard_id,
210 ) = mapping
211 if expert_weight_name not in name:
212 continue
213 name = name.replace(expert_weight_name, expert_param_name)
214
215 param = params_dict[name]
216 weight_loader = param.weight_loader
217 weight_loader(
218 param,
219 loaded_weight,
220 name,
221 shard_id=expert_shard_id,
222 expert_id=expert_id,
223 )
224 break
225 else:
226 # Skip loading extra bias for GPTQ models.
227 if name.endswith(".bias") and name not in params_dict:
228 continue
229
230 if (
231 spec_layer != self.model.mtp_start_layer_idx
232 and ".layers" not in name
233 ):
234 continue
235
236 param = params_dict[name]
237 weight_loader = getattr(
238 param, "weight_loader", default_weight_loader
239 )
240 weight_loader(param, loaded_weight)
241 loaded_params.add(name)
242 return loaded_params
243
244 def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
245 """Rewrite the weight name to match the format of the original model.
246 Add .mtp_block for modules in transformer layer block for spec layer
247 and rename shared layer weights to be top level.
248 """
249 spec_layer_weight_names = [
250 "embed_tokens",
251 "enorm",
252 "hnorm",
253 "eh_proj",
254 "shared_head",
255 ]
256 shared_weight_names = ["embed_tokens"]
257 spec_layer_weight = False
258 shared_weight = False
259 for weight_name in spec_layer_weight_names:
260 if weight_name in name:
261 spec_layer_weight = True
262 if weight_name in shared_weight_names:
263 shared_weight = True
264 break
265 if not spec_layer_weight:
266 # treat rest weights as weights for transformer layer block
267 name = name.replace(
268 f"model.layers.{spec_layer}.", f"model.layers.{spec_layer}.mtp_block."
269 )
270 elif shared_weight:
271 # treat shared weights as top level weights
272 name = name.replace(f"model.layers.{spec_layer}.", "model.")
273 return name