mimo_mtp.py 10.8 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# Adapted from
# https://github.com/vllm-project/vllm/blob/v0.7.3/vllm/model_executor/models/deepseek_mtp.py
# Copyright 2025 Xiaomi Corporation.
# Copyright 2023 The vLLM team.
# Copyright 2024 DeepSeek-AI team.

# 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.
"""Inference-only MiMo-MTP model."""
22

23
from collections.abc import Iterable
24
25
26
27
28
29
30
31
32
33

import torch
import torch.nn as nn
from transformers import PretrainedConfig

from vllm.config import CacheConfig, ModelConfig, VllmConfig
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.vocab_parallel_embedding import (
34
35
36
    ParallelLMHead,
    VocabParallelEmbedding,
)
37
38
39
40
41
42
43
44
45
46
47
48
49
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.qwen2 import Qwen2DecoderLayer
from vllm.sequence import IntermediateTensors

from .utils import maybe_prefix


class MiMoMultiTokenPredictorLayer(nn.Module):
    def __init__(
        self,
        config: PretrainedConfig,
        prefix: str,
        model_config: ModelConfig,
50
51
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
52
53
54
    ) -> None:
        super().__init__()

55
56
57
58
59
60
61
62
63
64
65
66
        self.token_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.hidden_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.input_proj = nn.Linear(
            config.hidden_size * 2, config.hidden_size, bias=False
        )
        self.mtp_block = Qwen2DecoderLayer(
            config=config,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=prefix,
        )
        self.final_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

    def forward(
        self,
        inputs_embeds: torch.Tensor,
        positions: torch.Tensor,
        previous_hidden_states: torch.Tensor,
        spec_step_index: int = 0,
    ) -> torch.Tensor:
        assert inputs_embeds is not None
        # masking inputs at position 0, as not needed by MTP
        inputs_embeds[positions == 0] = 0
        inputs_embeds = self.token_layernorm(inputs_embeds)
        previous_hidden_states = self.hidden_layernorm(previous_hidden_states)

        hidden_states = self.input_proj(
82
83
            torch.cat([previous_hidden_states, inputs_embeds], dim=-1)
        )
84

85
86
87
        hidden_states, residual = self.mtp_block(
            positions=positions, hidden_states=hidden_states, residual=None
        )
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
        hidden_states = residual + hidden_states
        return self.final_layernorm(hidden_states)


class MiMoMultiTokenPredictor(nn.Module):
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()

        config = vllm_config.model_config.hf_config
        self.mtp_start_layer_idx = config.num_hidden_layers
        self.num_mtp_layers = config.num_nextn_predict_layers

        self.embed_tokens = VocabParallelEmbedding(
            config.vocab_size,
            config.hidden_size,
        )

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        self.mtp_layers = torch.nn.ModuleDict(
            {
                str(idx): MiMoMultiTokenPredictorLayer(
                    config,
                    f"{prefix}.layers.{idx}",
                    model_config=vllm_config.model_config,
                    cache_config=vllm_config.cache_config,
                    quant_config=vllm_config.quant_config,
                )
                for idx in range(
                    self.mtp_start_layer_idx,
                    self.mtp_start_layer_idx + self.num_mtp_layers,
                )
            }
        )
120
121
122

        self.logits_processor = LogitsProcessor(config.vocab_size)

123
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
124
125
        return self.embed_tokens(input_ids)

126
127
128
129
130
    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        previous_hidden_states: torch.Tensor,
131
        inputs_embeds: torch.Tensor | None = None,
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        spec_step_idx: int = 0,
    ) -> torch.Tensor:
        if inputs_embeds is None:
            inputs_embeds = self.embed_tokens(input_ids)
        return self.mtp_layers[str(self.mtp_start_layer_idx + spec_step_idx)](
            inputs_embeds,
            positions,
            previous_hidden_states,
            spec_step_idx,
        )

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        lm_head: ParallelLMHead,
        spec_step_idx: int = 0,
    ) -> torch.Tensor:
        self.mtp_layers[str(self.mtp_start_layer_idx + spec_step_idx)]
150
        logits = self.logits_processor(lm_head, hidden_states)
151
152
153
154
155
156
157
        return logits


class MiMoMTP(nn.Module):
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        self.config = vllm_config.model_config.hf_config
158
159
160
161
162
163
164
165
        self.model = MiMoMultiTokenPredictor(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
        )
        self.lm_head = ParallelLMHead(
            self.config.vocab_size,
            self.config.hidden_size,
            prefix=maybe_prefix(prefix, "lm_head"),
        )
166

167
168
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.embed_input_ids(input_ids)
169

170
171
172
173
    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
174
        hidden_states: torch.Tensor,
175
176
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
177
178
179
        spec_step_idx: int = 0,
    ) -> torch.Tensor:
        assert spec_step_idx == 0, "mimo_mtp only support predict one token now"
180
181
182
        hidden_states = self.model(
            input_ids, positions, hidden_states, inputs_embeds, spec_step_idx
        )
183
184
185
186
187
188
        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        spec_step_idx: int = 0,
189
    ) -> torch.Tensor | None:
190
        return self.model.compute_logits(hidden_states, self.lm_head, spec_step_idx)
191

192
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
193
194
195
196
197
198
199
200
201
        stacked_params_mapping = [
            ("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_dict = dict(self.named_parameters())
202
        loaded_params: set[str] = set()
203
204
205
206
207
        for name, loaded_weight in weights:
            if "rotary_emb.inv_freq" in name:
                continue
            name = self.map_model_name_to_mtp_param_name(name)

208
            for param_name, weight_name, shard_id in stacked_params_mapping:
209
210
211
212
213
214
215
216
217
218
219
                # Skip non-stacked layers and experts (experts handled below).
                if weight_name not in name:
                    continue
                if "mtp_layers" not in name:
                    break
                # 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.
220
                if ("mlp.experts." in name) and name not in params_dict:
221
222
223
224
225
226
227
228
229
230
231
232
233
234
                    continue
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue

                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                break
            else:
                # Skip loading extra bias for GPTQ models.
                if name.endswith(".bias") and name not in params_dict:
                    continue
235
236
237
                if "mtp_layers" not in name and (
                    "embed_tokens" not in name and "lm_head" not in name
                ):
238
239
                    continue
                param = params_dict[name]
240
                weight_loader = getattr(param, "weight_loader", default_weight_loader)
241
242
243
244
245
                weight_loader(param, loaded_weight)
            loaded_params.add(name)
        return loaded_params

    def map_model_name_to_mtp_param_name(self, name: str) -> str:
246
        import regex as re
247
248
249
250
251
252
253
254
255

        # append mtp_start_layer_idx
        pattern = r"(model\.mtp_layers\.)(\d+)(\.)"
        match = re.match(pattern, name)
        if match:
            original_num = int(match.group(2))
            new_num = original_num + self.config.num_hidden_layers
            name = name.replace(match.group(), f"{match.group(1)}{new_num}.")
        # check for early turn
256
        name_without_prefix = [
257
258
259
260
            "token_layernorm",
            "hidden_layernorm",
            "input_proj",
            "final_layernorm",
261
262
263
264
        ]
        for sub_name in name_without_prefix:
            if sub_name in name:
                return name
265
266
267
268
269
        # add mtp_block
        pattern = r"(model\.mtp_layers\.\d+\.)"
        match = re.match(pattern, name)
        if match:
            name = name.replace(match.group(), match.group() + "mtp_block.")
270
271
272
273
274
275
276
277
        return name

    def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
        """
        Rewrite the weight name to match the format of the original model.
        Add .mtp_block for modules in transformer layer block for spec layer
        """
        spec_layer_weight_names = [
278
279
280
281
282
            "embed_tokens",
            "enorm",
            "hnorm",
            "eh_proj",
            "shared_head",
283
284
285
286
287
288
289
290
        ]
        spec_layer_weight = False
        for weight_name in spec_layer_weight_names:
            if weight_name in name:
                spec_layer_weight = True
                break
        if not spec_layer_weight:
            # treat rest weights as weights for transformer layer block
291
292
293
            name = name.replace(
                f"model.layers.{spec_layer}.", f"model.layers.{spec_layer}.mtp_block."
            )
294
        return name