longcat_flash.py 27.9 KB
Newer Older
XuruiYang's avatar
XuruiYang committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Apache License, Version 2.0:
# 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.
#
# MIT License:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Inference-only Flash model compatible with HuggingFace weights."""
35

XuruiYang's avatar
XuruiYang committed
36
37
import typing
from collections.abc import Callable, Iterable
38
from itertools import islice
XuruiYang's avatar
XuruiYang committed
39
40
41
42
43
44
45
46
47
48

import torch
from torch import nn
from transformers import PretrainedConfig

from vllm.compilation.decorators import support_torch_compile
from vllm.config import CacheConfig, VllmConfig
from vllm.distributed import get_pp_group
from vllm.logger import init_logger
from vllm.model_executor.layers.activation import SiluAndMul
49
50
51
52
from vllm.model_executor.layers.fused_moe import (
    FusedMoE,
    fused_moe_make_expert_params_mapping,
)
XuruiYang's avatar
XuruiYang committed
53
from vllm.model_executor.layers.layernorm import RMSNorm
54
55
56
57
58
from vllm.model_executor.layers.linear import (
    MergedColumnParallelLinear,
    ReplicatedLinear,
    RowParallelLinear,
)
XuruiYang's avatar
XuruiYang committed
59
60
from vllm.model_executor.layers.logits_processor import LogitsProcessor
from vllm.model_executor.layers.quantization import QuantizationConfig
61
from vllm.model_executor.layers.quantization.utils.int8_utils import block_dequant
XuruiYang's avatar
XuruiYang committed
62
from vllm.model_executor.layers.vocab_parallel_embedding import (
63
64
65
    ParallelLMHead,
    VocabParallelEmbedding,
)
XuruiYang's avatar
XuruiYang committed
66
67
68
69
70
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
from vllm.model_executor.models.deepseek_v2 import DeepseekV2MLAAttention
from vllm.sequence import IntermediateTensors

from .interfaces import SupportsLoRA, SupportsPP
71
72
73
74
75
76
77
from .utils import (
    PPMissingLayer,
    is_pp_missing_parameter,
    make_empty_intermediate_tensors_factory,
    make_layers,
    maybe_prefix,
)
XuruiYang's avatar
XuruiYang committed
78
79
80
81
82
83

logger = init_logger(__name__)


class FlashConfig(PretrainedConfig):
    """Flash model configuration."""
84

XuruiYang's avatar
XuruiYang committed
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    model_type = "longcat_flash"
    keys_to_ignore_at_inference = ["past_key_values"]

    def __init__(
        self,
        vocab_size=131072,
        hidden_size=4096,
        intermediate_size=8192,
        num_layers=28,
        num_hidden_layers=None,
        num_attention_heads=96,
        num_key_value_heads=128,
        ep_size=1,
        kv_lora_rank=512,
        q_lora_rank=1536,
        qk_rope_head_dim=64,
        v_head_dim=128,
        qk_nope_head_dim=128,
        num_experts_per_tok=None,
        norm_topk_prob=False,
        max_position_embeddings=8192,
        initializer_range=0.02,
        rms_norm_eps=1e-05,
        use_cache=True,
        pad_token_id=None,
        bos_token_id=100000,
        eos_token_id=100001,
        pretraining_tp=1,
        tie_word_embeddings=False,
114
        rope_parameters=None,
XuruiYang's avatar
XuruiYang committed
115
116
117
118
        attention_bias=False,
        attention_dropout=0.0,
        mla_scale_q_lora=False,
        mla_scale_kv_lora=False,
119
        dtype="bfloat16",
XuruiYang's avatar
XuruiYang committed
120
121
122
123
        params_dtype="bfloat16",
        router_dtype="float32",
        router_bias=False,
        topk_method=None,
124
        routed_scaling_factor=1.0,
XuruiYang's avatar
XuruiYang committed
125
126
127
128
129
130
131
132
133
134
        zero_expert_num=0,
        zero_expert_type=None,
        nextn_use_scmoe=False,
        **kwargs,
    ):
        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            tie_word_embeddings=tie_word_embeddings,
135
            dtype=dtype,
XuruiYang's avatar
XuruiYang committed
136
137
138
139
140
141
142
143
144
145
            params_dtype=params_dtype,
            router_dtype=router_dtype,
            topk_method=topk_method,
            router_bias=router_bias,
            nextn_use_scmoe=nextn_use_scmoe,
            **kwargs,
        )
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
146
147
148
        self.num_hidden_layers = (
            num_hidden_layers if num_hidden_layers is not None else num_layers
        )
XuruiYang's avatar
XuruiYang committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        self.num_attention_heads = num_attention_heads
        self.ep_size = ep_size
        self.kv_lora_rank = kv_lora_rank
        self.q_lora_rank = q_lora_rank
        self.qk_rope_head_dim = qk_rope_head_dim
        self.v_head_dim = v_head_dim
        self.qk_nope_head_dim = qk_nope_head_dim
        self.num_experts_per_tok = num_experts_per_tok
        self.norm_topk_prob = norm_topk_prob
        # for backward compatibility
        if num_key_value_heads is None:
            num_key_value_heads = num_attention_heads

        self.num_key_value_heads = num_key_value_heads
        self.initializer_range = initializer_range
        self.rms_norm_eps = rms_norm_eps
        self.pretraining_tp = pretraining_tp
        self.use_cache = use_cache
167
168
169
170
171
172
173
        # Try to set `rope_scaling` if available, otherwise use `rope_parameters`
        rope_scaling = kwargs.pop("rope_scaling", None)
        rope_parameters = rope_scaling or rope_parameters or {"rope_type": "default"}
        rope_theta = kwargs.pop("rope_theta", 1000000.0)
        if "rope_theta" not in rope_parameters:
            rope_parameters["rope_theta"] = rope_theta
        self.rope_parameters = rope_parameters
XuruiYang's avatar
XuruiYang committed
174
175
176
177
178
179
180
181
        self.attention_bias = attention_bias
        self.attention_dropout = attention_dropout
        self.mla_scale_q_lora = mla_scale_q_lora
        self.mla_scale_kv_lora = mla_scale_kv_lora
        self.zero_expert_num = zero_expert_num
        self.zero_expert_type = zero_expert_type
        self.routed_scaling_factor = routed_scaling_factor
        self.hidden_act = "silu"
182
183
184
        self.intermediate_size = (
            self.ffn_hidden_size
            if hasattr(self, "ffn_hidden_size")
185
            else intermediate_size
186
        )
XuruiYang's avatar
XuruiYang committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        if hasattr(self, "moe_intermediate_size"):
            self.moe_intermediate_size = self.moe_intermediate_size
        elif hasattr(self, "expert_ffn_hidden_size"):
            self.moe_intermediate_size = self.expert_ffn_hidden_size
        else:
            self.moe_intermediate_size = self.intermediate_size


class FlashMLP(nn.Module):
    """Flash MLP layer."""

    def __init__(
        self,
        hidden_size: int,
        intermediate_size: int,
        hidden_act: str,
203
        quant_config: QuantizationConfig | None = None,
XuruiYang's avatar
XuruiYang committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        reduce_results: bool = True,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.gate_up_proj = MergedColumnParallelLinear(
            hidden_size,
            [intermediate_size] * 2,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.gate_up_proj",
        )
        self.down_proj = RowParallelLinear(
            intermediate_size,
            hidden_size,
            bias=False,
            quant_config=quant_config,
            reduce_results=reduce_results,
            prefix=f"{prefix}.down_proj",
        )
        if hidden_act != "silu":
224
225
226
            raise ValueError(
                f"Unsupported activation: {hidden_act}. Only silu is supported for now."
            )
XuruiYang's avatar
XuruiYang committed
227
228
229
230
231
232
233
234
235
236
237
238
239
        self.act_fn = SiluAndMul()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        if x.numel() == 0:
            return x

        gate_up, _ = self.gate_up_proj(x)
        x = self.act_fn(gate_up)
        x, _ = self.down_proj(x)
        return x


class LongcatRouter(nn.Module):
240
241
    def __init__(
        self,
242
243
        config: FlashConfig,
        zero_expert_num: int,
Jiayi Yan's avatar
Jiayi Yan committed
244
        router_params_dtype: torch.dtype,
245
246
        prefix: str = "",
    ):
XuruiYang's avatar
XuruiYang committed
247
        super().__init__()
248
249
250
251
252
        self.n_routed_experts = (
            config.n_routed_experts
            if hasattr(config, "n_routed_experts")
            else config.num_experts[0]
        )
XuruiYang's avatar
XuruiYang committed
253
254
255
256
257
        self.n_routed_experts = self.n_routed_experts + zero_expert_num
        self.classifier = ReplicatedLinear(
            config.hidden_size,
            self.n_routed_experts,
            bias=config.router_bias,
Jiayi Yan's avatar
Jiayi Yan committed
258
            params_dtype=router_params_dtype,
XuruiYang's avatar
XuruiYang committed
259
260
261
262
            quant_config=None,
            prefix=f"{prefix}.classifier",
        )
        self.e_score_correction_bias = nn.Parameter(
Jiayi Yan's avatar
Jiayi Yan committed
263
            torch.zeros((self.n_routed_experts), dtype=router_params_dtype)
264
        )
XuruiYang's avatar
XuruiYang committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278

    def forward(self, hidden_states):
        logits, _ = self.classifier(hidden_states)
        return logits


class LongcatMoe(nn.Module):
    def __init__(
        self,
        config: FlashConfig,
        num_experts: int,
        top_k: int,
        hidden_size: int,
        intermediate_size: int,
279
280
        params_dtype: torch.dtype | None = None,
        quant_config: QuantizationConfig | None = None,
XuruiYang's avatar
XuruiYang committed
281
282
283
284
285
286
        prefix: str = "",
        enable_eplb: bool = False,
    ):
        super().__init__()
        self.hidden_size = hidden_size
        # Gate always runs at half / full precision for now.
Jiayi Yan's avatar
Jiayi Yan committed
287
        self.router_params_dtype = params_dtype
XuruiYang's avatar
XuruiYang committed
288
        if config.router_dtype == "float32":
Jiayi Yan's avatar
Jiayi Yan committed
289
            self.router_params_dtype = torch.float32
XuruiYang's avatar
XuruiYang committed
290
291
292

        self.router = LongcatRouter(
            config=config,
293
            zero_expert_num=config.zero_expert_num,
Jiayi Yan's avatar
Jiayi Yan committed
294
            router_params_dtype=self.router_params_dtype,
295
296
            prefix=f"{prefix}.gate",
        )
XuruiYang's avatar
XuruiYang committed
297

298
        assert config.zero_expert_type is not None
299
        self.experts = FusedMoE(
300
            zero_expert_type=config.zero_expert_type,
301
            e_score_correction_bias=self.router.e_score_correction_bias,
XuruiYang's avatar
XuruiYang committed
302
303
304
305
306
307
308
309
            num_experts=num_experts,
            top_k=top_k,
            hidden_size=hidden_size,
            intermediate_size=intermediate_size,
            params_dtype=params_dtype,
            renormalize=False,
            quant_config=quant_config,
            prefix=f"{prefix}.experts",
310
            enable_eplb=enable_eplb,
XuruiYang's avatar
XuruiYang committed
311
            routed_scaling_factor=config.routed_scaling_factor,
Jiayi Yan's avatar
Jiayi Yan committed
312
            router_logits_dtype=self.router_params_dtype,
XuruiYang's avatar
XuruiYang committed
313
314
315
316
317
318
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        num_tokens, hidden_dim = hidden_states.shape
        hidden_states = hidden_states.view(-1, hidden_dim)

319
320
321
322
323
324
325
326
327
328
329
330
331
        # Align to FusedMoE padded hidden size to avoid dim mismatch
        padded_hidden = self.experts.hidden_size
        if hidden_dim < padded_hidden:
            hidden_states_padded = torch.nn.functional.pad(
                hidden_states,
                (0, padded_hidden - hidden_dim),
                mode="constant",
                value=0.0,
            )
        else:
            hidden_states_padded = hidden_states

        router_logits_full = self.router(
Jiayi Yan's avatar
Jiayi Yan committed
332
            hidden_states_padded.to(self.router_params_dtype)
333
334
        )

335
        # FusedMoE handles routing memoization and zero expert computation
336
337
        # internally. Pass full router_logits (including zero experts) so that
        # zero experts can be properly identified in routing.
338
        final_hidden_states = self.experts(
339
340
            hidden_states=hidden_states_padded,
            router_logits=router_logits_full,  # Full logits (includes zero experts)
341
        )
XuruiYang's avatar
XuruiYang committed
342

343
344
345
346
        # Crop back to original hidden dimension if padded earlier
        if padded_hidden != hidden_dim:
            final_hidden_states = final_hidden_states[..., :hidden_dim]

XuruiYang's avatar
XuruiYang committed
347
348
349
350
351
352
353
354
        return final_hidden_states.view(num_tokens, hidden_dim)


class FlashDecoderLayer(nn.Module):
    """Flash decoder layer with dual attention and MLP structure."""

    def __init__(
        self,
355
        vllm_config: VllmConfig,
XuruiYang's avatar
XuruiYang committed
356
        config: FlashConfig,
357
358
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
XuruiYang's avatar
XuruiYang committed
359
360
361
362
        prefix: str = "",
        enable_eplb: bool = False,
    ) -> None:
        super().__init__()
363
        self.layer_idx = int(prefix.split(sep=".")[-1])
XuruiYang's avatar
XuruiYang committed
364
        self.hidden_size = config.hidden_size
365
        max_position_embeddings = getattr(config, "max_position_embeddings", 8192)
XuruiYang's avatar
XuruiYang committed
366
367

        # Dual attention structure
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
        self.self_attn = nn.ModuleList(
            [
                DeepseekV2MLAAttention(
                    vllm_config=vllm_config,
                    config=config,
                    hidden_size=self.hidden_size,
                    num_heads=config.num_attention_heads,
                    qk_nope_head_dim=config.qk_nope_head_dim,
                    qk_rope_head_dim=config.qk_rope_head_dim,
                    v_head_dim=config.v_head_dim,
                    q_lora_rank=(
                        config.q_lora_rank if hasattr(config, "q_lora_rank") else None
                    ),
                    kv_lora_rank=config.kv_lora_rank,
                    max_position_embeddings=max_position_embeddings,
                    cache_config=cache_config,
                    quant_config=None
                    if "self_attn" in getattr(config, "disable_quant_module", [])
                    else quant_config,
                    prefix=f"{prefix}.self_attn.{i}",
                )
                for i in range(2)
            ]
        )
        self.input_layernorm = nn.ModuleList(
            [RMSNorm(config.hidden_size, eps=config.rms_norm_eps) for i in range(2)]
        )
        self.post_attention_layernorm = nn.ModuleList(
            [RMSNorm(config.hidden_size, eps=config.rms_norm_eps) for i in range(2)]
        )
XuruiYang's avatar
XuruiYang committed
398
399

        # Dual MLP structure
400
401
402
403
404
405
406
407
408
409
410
411
412
413
        self.mlps = nn.ModuleList(
            [
                FlashMLP(
                    hidden_size=self.hidden_size,
                    intermediate_size=config.intermediate_size,
                    hidden_act=config.hidden_act,
                    quant_config=None
                    if "mlps" in getattr(config, "disable_quant_module", [])
                    else quant_config,
                    prefix=f"{prefix}.mlps.{i}",
                )
                for i in range(2)
            ]
        )
XuruiYang's avatar
XuruiYang committed
414
415
416

        self.mlp = LongcatMoe(
            config=config,
417
418
419
            num_experts=config.n_routed_experts
            if hasattr(config, "n_routed_experts")
            else config.num_experts[self.layer_idx],
XuruiYang's avatar
XuruiYang committed
420
            top_k=config.moe_topk
421
422
            if hasattr(config, "moe_topk")
            else config.num_experts_per_tok,
XuruiYang's avatar
XuruiYang committed
423
424
425
426
427
428
429
430
431
432
            hidden_size=config.hidden_size,
            intermediate_size=config.moe_intermediate_size,
            quant_config=quant_config,
            prefix=(f"{prefix}.mlp"),
        )

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
433
        residual: torch.Tensor | None,
XuruiYang's avatar
XuruiYang committed
434
435
436
437
438
    ) -> tuple[torch.Tensor, torch.Tensor]:
        if residual is None:
            residual = hidden_states
            hidden_states = self.input_layernorm[0](hidden_states)
        else:
439
            hidden_states, residual = self.input_layernorm[0](hidden_states, residual)
XuruiYang's avatar
XuruiYang committed
440
441
442
443

        hidden_states = self.self_attn[0](
            positions=positions,
            hidden_states=hidden_states,
444
            llama_4_scaling=None,
XuruiYang's avatar
XuruiYang committed
445
446
447
        )

        hidden_states, residual = self.post_attention_layernorm[0](
448
449
            hidden_states, residual
        )
XuruiYang's avatar
XuruiYang committed
450
451
452
453
454
455
456
457

        # moe
        hidden_states_copy = hidden_states.clone()
        moe_hidden_states = self.mlp(hidden_states_copy)

        # first mlp
        hidden_states = self.mlps[0](hidden_states)

458
        hidden_states, residual = self.input_layernorm[1](hidden_states, residual)
XuruiYang's avatar
XuruiYang committed
459
460
461
462
463

        # second_attn
        hidden_states = self.self_attn[1](
            positions=positions,
            hidden_states=hidden_states,
464
            llama_4_scaling=None,
XuruiYang's avatar
XuruiYang committed
465
466
        )
        hidden_states, residual = self.post_attention_layernorm[1](
467
468
            hidden_states, residual
        )
XuruiYang's avatar
XuruiYang committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501

        # second_mlp
        hidden_states = self.mlps[1](hidden_states)

        hidden_states = hidden_states + moe_hidden_states

        return hidden_states, residual


@support_torch_compile
class FlashModel(nn.Module):
    """Flash model."""

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config
        self.config = config

        self.vocab_size = config.vocab_size

        if get_pp_group().is_first_rank:
            self.embed_tokens = VocabParallelEmbedding(
                config.vocab_size,
                config.hidden_size,
                prefix=maybe_prefix(prefix, "embed_tokens"),
            )
        else:
            self.embed_tokens = PPMissingLayer()
        self.start_layer, self.end_layer, self.layers = make_layers(
            config.num_hidden_layers,
            lambda prefix: FlashDecoderLayer(
502
                vllm_config,
XuruiYang's avatar
XuruiYang committed
503
504
505
506
507
                config,
                cache_config=cache_config,
                quant_config=quant_config,
                prefix=prefix,
            ),
508
509
            prefix=f"{prefix}.layers",
        )
XuruiYang's avatar
XuruiYang committed
510
511
512
513
        if get_pp_group().is_last_rank:
            self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        else:
            self.norm = PPMissingLayer()
514
515
516
        self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory(
            ["hidden_states", "residual"], config.hidden_size
        )
XuruiYang's avatar
XuruiYang committed
517

518
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
XuruiYang's avatar
XuruiYang committed
519
520
521
522
        return self.embed_tokens(input_ids)

    def forward(
        self,
523
        input_ids: torch.Tensor | None,
XuruiYang's avatar
XuruiYang committed
524
        positions: torch.Tensor,
525
526
527
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor | IntermediateTensors:
XuruiYang's avatar
XuruiYang committed
528
529
530
531
        if get_pp_group().is_first_rank:
            if inputs_embeds is not None:
                hidden_states = inputs_embeds
            else:
532
                hidden_states = self.embed_input_ids(input_ids)
XuruiYang's avatar
XuruiYang committed
533
534
535
536
537
538
            residual = None
        else:
            assert intermediate_tensors is not None
            hidden_states = intermediate_tensors["hidden_states"]
            residual = intermediate_tensors["residual"]

539
        for layer in islice(self.layers, self.start_layer, self.end_layer):
XuruiYang's avatar
XuruiYang committed
540
541
542
543
544
545
546
            hidden_states, residual = layer(
                positions,
                hidden_states,
                residual,
            )

        if not get_pp_group().is_last_rank:
547
548
549
            return IntermediateTensors(
                {"hidden_states": hidden_states, "residual": residual}
            )
XuruiYang's avatar
XuruiYang committed
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575

        hidden_states, _ = self.norm(hidden_states, residual)
        return hidden_states


class LongcatFlashForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
    """Flash model for causal language modeling."""

    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        config = FlashConfig(**vllm_config.model_config.hf_config.__dict__)
        quant_config = vllm_config.quant_config

        self.config = config
576
577
578
579
580
        config.intermediate_size = (
            config.ffn_hidden_size
            if hasattr(config, "ffn_hidden_size")
            else config.intermediate_size
        )
581

XuruiYang's avatar
XuruiYang committed
582
583
        self.quant_config = quant_config

584
585
586
        self.model = FlashModel(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
        )
XuruiYang's avatar
XuruiYang committed
587
588

        if get_pp_group().is_last_rank:
589
590
591
592
593
594
            self.lm_head = ParallelLMHead(
                config.vocab_size,
                config.hidden_size,
                quant_config=quant_config,
                prefix=maybe_prefix(prefix, "lm_head"),
            )
XuruiYang's avatar
XuruiYang committed
595
596
597
598
599
        else:
            self.lm_head = PPMissingLayer()

        self.logits_processor = LogitsProcessor(config.vocab_size)
        self.make_empty_intermediate_tensors = (
600
601
            self.model.make_empty_intermediate_tensors
        )
XuruiYang's avatar
XuruiYang committed
602

603
604
    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.embed_input_ids(input_ids)
XuruiYang's avatar
XuruiYang committed
605
606
607

    def forward(
        self,
608
        input_ids: torch.Tensor | None,
XuruiYang's avatar
XuruiYang committed
609
        positions: torch.Tensor,
610
611
612
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor | IntermediateTensors:
613
614
615
        hidden_states = self.model(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )
XuruiYang's avatar
XuruiYang committed
616
617
618
619
620
        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
621
    ) -> torch.Tensor | None:
XuruiYang's avatar
XuruiYang committed
622
623
624
625
626
627
        logits = self.logits_processor(self.lm_head, hidden_states)
        return logits

    def get_expert_mapping(self) -> list[tuple[str, str, int, str]]:
        # Params for weights, fp8 weight scales, fp8 activation scales
        # (param_name, weight_name, expert_id, shard_id)
628
        return fused_moe_make_expert_params_mapping(
629
            self,
XuruiYang's avatar
XuruiYang committed
630
631
632
            ckpt_gate_proj_name="gate_proj",
            ckpt_down_proj_name="down_proj",
            ckpt_up_proj_name="up_proj",
633
634
635
            num_experts=self.config.n_routed_experts
            if hasattr(self.config, "n_routed_experts")
            else self.config.num_experts[0],
XuruiYang's avatar
XuruiYang committed
636
637
        )

638
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
XuruiYang's avatar
XuruiYang committed
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
        stacked_params_mapping = [
            ("fused_qkv_a_proj", "q_a_proj", 0),
            ("fused_qkv_a_proj", "kv_a_proj_with_mqa", 1),
            (".gate_up_proj", ".gate_proj", 0),
            (".gate_up_proj", ".up_proj", 1),
        ]

        expert_params_mapping = self.get_expert_mapping()
        loaded_params: set[str] = set()

        params_dict = dict(self.named_parameters())
        for name, loaded_weight in weights:
            if "rotary_emb.inv_freq" in name:
                continue
            for param_name, weight_name, shard_id in stacked_params_mapping:
                if weight_name not in name:
                    continue
                if "mlp" in name and "mlps" not in name:
                    continue
                name = name.replace(weight_name, param_name)
                # Skip loading extra bias for GPTQ models.
660
661
662
                if (
                    name.endswith(".bias") or name.endswith("_bias")
                ) and name not in params_dict:
XuruiYang's avatar
XuruiYang committed
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
                    continue
                # Skip mtp
                if ".mtp." in name:
                    continue
                if is_pp_missing_parameter(name, self):
                    continue
                param = params_dict[name]
                weight_loader = param.weight_loader
                weight_loader(param, loaded_weight, shard_id)
                break
            else:
                is_expert_weight = False
                for mapping in expert_params_mapping:
                    param_name, weight_name, expert_id, shard_id = mapping
                    if weight_name not in name:
                        continue
                    is_expert_weight = True
                    name_mapped = name.replace(weight_name, param_name)
                    # Skip mtp
                    if ".mtp." in name_mapped:
                        continue
684
685
686
                    if (
                        name_mapped.endswith(".bias") or name_mapped.endswith("_bias")
                    ) and name not in params_dict:
XuruiYang's avatar
XuruiYang committed
687
688
689
690
691
                        continue
                    if is_pp_missing_parameter(name, self):
                        continue
                    param = params_dict[name_mapped]
                    weight_loader = param.weight_loader
692
693
694
695
696
697
698
699
700
701
702
                    weight_loader = typing.cast(
                        Callable[..., bool], param.weight_loader
                    )
                    success = weight_loader(
                        param,
                        loaded_weight,
                        name_mapped,
                        shard_id=shard_id,
                        expert_id=expert_id,
                        return_success=True,
                    )
XuruiYang's avatar
XuruiYang committed
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
                    if success:
                        name = name_mapped
                        break
                else:
                    if is_expert_weight:
                        # We've checked that this is an expert weight
                        # However it's not mapped locally to this rank
                        # So we simply skip it
                        continue
                    # Skip loading extra bias for GPTQ models.
                    if name.endswith(".bias") and name not in params_dict:
                        continue
                    # Skip loading kv_scale from ckpts towards new design.
                    if name.endswith(".kv_scale") and name not in params_dict:
                        continue
                    # Skip mtp
                    if ".mtp." in name:
                        continue
                    if name is None:
                        continue
                    if is_pp_missing_parameter(name, self):
                        continue
                    param = params_dict[name]
726
727
728
                    weight_loader = getattr(
                        param, "weight_loader", default_weight_loader
                    )
XuruiYang's avatar
XuruiYang committed
729
730
731
732
733
734
735
                    weight_loader(param, loaded_weight)
            loaded_params.add(name)
        for layer_id in range(self.config.num_hidden_layers):
            for i in range(2):
                if isinstance(self.model.layers[layer_id], PPMissingLayer):
                    continue
                self_attn = self.model.layers[layer_id].self_attn[i]
736
737
738
739
740
741
                if hasattr(
                    self.quant_config, "weight_block_size"
                ) and self_attn.kv_b_proj.weight.dtype in (
                    torch.float8_e4m3fn,
                    torch.float8_e4m3fnuz,
                ):
XuruiYang's avatar
XuruiYang committed
742
743
744
745
                    weight_block_size = self.quant_config.weight_block_size
                    if weight_block_size is not None:
                        assert hasattr(self_attn.kv_b_proj, "weight_scale_inv")
                        dtype = torch.get_default_dtype()
746
747
748
749
750
                        w = block_dequant(
                            self_attn.kv_b_proj.weight,
                            self_attn.kv_b_proj.weight_scale_inv,
                            weight_block_size,
                        ).to(dtype)
XuruiYang's avatar
XuruiYang committed
751
752
753
754
                else:
                    w = self_attn.kv_b_proj.weight

                w_kc, w_vc = w.unflatten(
755
756
757
                    0, (-1, self_attn.qk_nope_head_dim + self_attn.v_head_dim)
                ).split([self_attn.qk_nope_head_dim, self_attn.v_head_dim], dim=1)
                self_attn.w_kc = w_kc.transpose(1, 2).contiguous().transpose(1, 2)
XuruiYang's avatar
XuruiYang committed
758
759
760
                self_attn.w_vc = w_vc.contiguous().transpose(1, 2)
                if self.config.mla_scale_q_lora:
                    self_attn.q_a_layernorm.weight.data *= (
761
762
                        self.config.hidden_size / self.config.q_lora_rank
                    ) ** 0.5
XuruiYang's avatar
XuruiYang committed
763
764
                if self.config.mla_scale_kv_lora:
                    self_attn.kv_a_layernorm.weight.data *= (
765
766
                        self.config.hidden_size / self.config.kv_lora_rank
                    ) ** 0.5
XuruiYang's avatar
XuruiYang committed
767
        return loaded_params