plamo2.py 45.3 KB
Newer Older
Shinichi Hemmi's avatar
Shinichi Hemmi committed
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
Shinichi Hemmi's avatar
Shinichi Hemmi committed
3
"""Inference-only PLaMo2 model."""
4
from collections.abc import Iterable
5
from itertools import islice
6
7
8
9
from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from vllm.attention.backends.abstract import AttentionBackend
Shinichi Hemmi's avatar
Shinichi Hemmi committed
10
11
12

import torch
from torch import nn
13
from transformers import PretrainedConfig
Shinichi Hemmi's avatar
Shinichi Hemmi committed
14

15
from vllm import envs
Shinichi Hemmi's avatar
Shinichi Hemmi committed
16
17
from vllm.attention.backends.abstract import AttentionMetadata
from vllm.attention.layer import Attention
18
from vllm.compilation.decorators import support_torch_compile
19
from vllm.config import VllmConfig, get_current_vllm_config
20
21
from vllm.distributed import divide, get_tensor_model_parallel_world_size
from vllm.distributed.parallel_state import get_pp_group
22
23
from vllm.forward_context import ForwardContext, get_forward_context
from vllm.model_executor.custom_op import CustomOp
24
from vllm.model_executor.layers.activation import SiluAndMul
Shinichi Hemmi's avatar
Shinichi Hemmi committed
25
26
27
28
29
30
from vllm.model_executor.layers.layernorm import RMSNorm
from vllm.model_executor.layers.linear import (ColumnParallelLinear,
                                               MergedColumnParallelLinear,
                                               QKVParallelLinear,
                                               RowParallelLinear)
from vllm.model_executor.layers.logits_processor import LogitsProcessor
31
from vllm.model_executor.layers.mamba.abstract import MambaBase
32
from vllm.model_executor.layers.mamba.mamba2_metadata import (
33
34
35
    Mamba2Metadata, prepare_mamba2_metadata, update_metadata)
from vllm.model_executor.layers.mamba.mamba_utils import (
    MambaStateDtypeCalculator, MambaStateShapeCalculator)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
36
37
38
from vllm.model_executor.layers.mamba.ops.causal_conv1d import (
    causal_conv1d_fn, causal_conv1d_update)
from vllm.model_executor.layers.mamba.ops.mamba_ssm import (
39
40
41
    selective_state_update)
from vllm.model_executor.layers.mamba.ops.ssd_combined import (
    mamba_chunk_scan_combined)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
42
43
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.model_executor.layers.rotary_embedding import get_rope
44
from vllm.model_executor.layers.sampler import SamplerOutput, get_sampler
Shinichi Hemmi's avatar
Shinichi Hemmi committed
45
46
47
48
49
from vllm.model_executor.layers.vocab_parallel_embedding import (
    DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
from vllm.model_executor.model_loader.weight_utils import (
    composed_weight_loader, default_weight_loader, sharded_weight_loader)
from vllm.model_executor.models.interfaces import (HasInnerState, IsHybrid,
50
                                                   SupportsPP)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
51
52
from vllm.model_executor.models.mamba_cache import (MambaCacheManager,
                                                    MambaCacheParams)
53
54
55
from vllm.model_executor.models.utils import (
    is_pp_missing_parameter, make_empty_intermediate_tensors_factory,
    make_layers, maybe_prefix)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
56
57
from vllm.model_executor.sampling_metadata import SamplingMetadata
from vllm.model_executor.utils import set_weight_attrs
58
from vllm.platforms import current_platform
Shinichi Hemmi's avatar
Shinichi Hemmi committed
59
from vllm.sequence import IntermediateTensors
60
61
from vllm.utils import LayerBlockType, direct_register_custom_op
from vllm.v1.attention.backends.mamba2_attn import Mamba2AttentionMetadata
Shinichi Hemmi's avatar
Shinichi Hemmi committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94


# Only used for type hinting.
class Plamo2Config(PretrainedConfig):  # type: ignore
    model_type: str = "plamo2"

    hidden_size: int
    num_hidden_layers: int
    rms_norm_eps: float
    # Attention
    num_attention_heads: int
    hidden_size_per_head: int
    num_key_value_heads: int
    # Mamba
    mamba_d_state: int
    mamba_d_conv: int
    mamba_num_heads: int
    mamba_step: int
    # MLP
    intermediate_size: int
    # Tokenizer
    vocab_size: int


def is_mamba(config: Plamo2Config, i: int) -> bool:
    assert config.mamba_step > 1

    if config.num_hidden_layers <= (config.mamba_step // 2):
        # use attention in last layer
        return i != config.num_hidden_layers - 1
    return (i % config.mamba_step) != (config.mamba_step // 2)


95
96
97
# Adapted from:
# vllm.model_executor.layers.mamba.mamba_mixer2.MambaMixer2
# transformers.models.mamba.modeling_mamba.MambaMixer
98
99
@CustomOp.register(name="plamo2_mamba_mixer")
class Plamo2MambaMixer(MambaBase, CustomOp):
Shinichi Hemmi's avatar
Shinichi Hemmi committed
100
101

    def __init__(self,
102
103
                 vllm_config: VllmConfig,
                 *,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
104
105
106
                 prefix: str = "",
                 **kwargs) -> None:
        super().__init__()
107
        self.config = vllm_config.model_config.hf_config
108
109
        self.cache_config = vllm_config.cache_config
        self.model_config = vllm_config.model_config
110
111
112
113
114
115
116
117
118
        self.quant_config = vllm_config.quant_config
        self.hidden_size = self.config.hidden_size
        self.ssm_state_size = self.config.mamba_d_state
        self.conv_kernel_size = self.config.mamba_d_conv
        self.intermediate_size = (self.config.mamba_num_heads *
                                  self.config.hidden_size_per_head)
        self.tp_size = get_tensor_model_parallel_world_size()
        self.head_dim = self.config.hidden_size_per_head
        self.num_heads = self.config.mamba_num_heads
Shinichi Hemmi's avatar
Shinichi Hemmi committed
119
120
121
122
        self.time_step_rank = max(64, self.hidden_size // 16)
        self.conv1d = ColumnParallelLinear(
            input_size=self.conv_kernel_size,
            output_size=self.intermediate_size,
123
124
125
            bias=False,
            prefix=f"{prefix}.conv1d",
            return_bias=False,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
126
127
128
129
130
131
132
133
134
135
        )
        # unsqueeze to fit conv1d weights shape into the linear weights shape.
        # Can't do this in `weight_loader` since it already exists in
        # `ColumnParallelLinear` and `set_weight_attrs`
        # doesn't allow to override it
        self.conv1d.weight.data = self.conv1d.weight.data.unsqueeze(1)

        self.in_proj = MergedColumnParallelLinear(
            self.hidden_size,
            [self.intermediate_size] * 2,
136
137
            bias=False,
            quant_config=self.quant_config,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
138
            prefix=f"{prefix}.in_proj",
139
            return_bias=False,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
140
141
142
143
144
145
        )
        # selective projection used to make dt, B and C input dependent
        self.bcdt_proj = RowParallelLinear(
            self.intermediate_size,
            self.time_step_rank + self.ssm_state_size * 2,
            bias=False,
146
            quant_config=self.quant_config,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
147
            prefix=f"{prefix}.bcdt_proj",
148
            return_bias=False,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
149
150
151
152
153
154
155
156
        )
        # time step projection (discretization) -
        # In the forward we need to apply dt_proj without the bias,
        # as the bias is added in the selective scan kernel.
        self.dt_proj = ColumnParallelLinear(
            self.time_step_rank,
            self.num_heads,
            bias=False,
157
            quant_config=self.quant_config,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
158
            prefix=f"{prefix}.dt_proj",
159
            return_bias=False,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
160
161
162
163
        )

        self.A = nn.Parameter(
            torch.empty(
164
                divide(self.num_heads, self.tp_size),
Shinichi Hemmi's avatar
Shinichi Hemmi committed
165
166
                dtype=torch.float32,
            ))
167
168
169
        self.D = nn.Parameter(torch.ones(divide(self.num_heads, self.tp_size)))
        self.dt_bias = nn.Parameter(
            torch.ones(divide(self.num_heads, self.tp_size)))
Shinichi Hemmi's avatar
Shinichi Hemmi committed
170
171
172
173
174

        set_weight_attrs(self.D, {"weight_loader": sharded_weight_loader(0)})
        a_weight_loader = composed_weight_loader(
            sharded_weight_loader(0), lambda x: -torch.exp(x.float()))
        set_weight_attrs(self.A, {"weight_loader": a_weight_loader})
175
176
        set_weight_attrs(self.dt_bias,
                         {"weight_loader": sharded_weight_loader(0)})
Shinichi Hemmi's avatar
Shinichi Hemmi committed
177
178
179
180

        self.out_proj = RowParallelLinear(
            self.intermediate_size,
            self.hidden_size,
181
            bias=False,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
182
            input_is_parallel=True,
183
            quant_config=self.quant_config,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
184
            prefix=f"{prefix}.out_proj",
185
            return_bias=False,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
186
187
188
189
        )
        # The activation function is fixed to SiLU.
        self.activation = "silu"

190
191
192
193
194
195
196
        self.dt_norm = RMSNorm(self.time_step_rank,
                               eps=self.config.rms_norm_eps)
        self.B_norm = RMSNorm(self.ssm_state_size,
                              eps=self.config.rms_norm_eps)
        self.C_norm = RMSNorm(self.ssm_state_size,
                              eps=self.config.rms_norm_eps)

197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
        self.chunk_size = self.config.mamba_chunk_size

        if envs.VLLM_USE_V1:
            compilation_config = get_current_vllm_config().compilation_config
            if prefix in compilation_config.static_forward_context:
                raise ValueError(f"Duplicate layer name: {prefix}")
            compilation_config.static_forward_context[prefix] = self
            # The outer list is for v0 PP virtual engine. Though this code path
            # only runs for v1, we have to do this to unify with the interface
            # of Attention + v0 PP.
            # The inner tuple is (conv_state, ssm_state)
            self.kv_cache = [(torch.tensor([]), torch.tensor([]))]
            assert self.chunk_size != -1, "chunk_size must be set for v1"

        self.prefix = prefix

213
214
215
216
217
218
219
220
221
222
223
224
225
226
    def _project_ssm_parameters(self, hidden_states):
        ssm_parameters = self.bcdt_proj(hidden_states)
        B, C, time_step = torch.split(
            ssm_parameters,
            [self.ssm_state_size, self.ssm_state_size, self.time_step_rank],
            dim=-1,
        )

        # vllm._custom_ops.rms_norm requires contiguous input tensors.
        time_step = self.dt_norm(time_step.contiguous())
        B = self.B_norm(B.contiguous())
        C = self.C_norm(C.contiguous())
        dt = self.dt_proj(time_step)
        return B, C, dt
Shinichi Hemmi's avatar
Shinichi Hemmi committed
227

228
229
230
231
232
233
234
235
236
237
    def forward_native(
        self,
        hidden_states: torch.Tensor,
        output: torch.Tensor,
        mamba_cache_params: MambaCacheParams,
        mamba2_metadata: Mamba2Metadata,
        **kwargs,
    ):
        pass

Shinichi Hemmi's avatar
Shinichi Hemmi committed
238
239
240
    def forward(
        self,
        hidden_states: torch.Tensor,
241
        output: torch.Tensor,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
242
        mamba_cache_params: MambaCacheParams,
243
        mamba2_metadata: Mamba2Metadata,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
244
        **kwargs,
245
246
247
248
249
250
251
252
253
254
    ):
        if not envs.VLLM_USE_V1:
            CustomOp.forward(self, hidden_states, output, mamba_cache_params,
                             mamba2_metadata)
        else:
            torch.ops.vllm.plamo2_mamba_mixer(
                hidden_states,
                output,
                self.prefix,
            )
Shinichi Hemmi's avatar
Shinichi Hemmi committed
255

256
257
258
259
260
261
262
263
264
265
    def forward_cuda(
        self,
        hidden_states: torch.Tensor,
        output: torch.Tensor,
        mamba_cache_params: MambaCacheParams,
        mamba2_metadata: Mamba2Metadata,
        **kwargs,
    ):

        forward_context = get_forward_context()
266
267
268
269
        # mamba2_metadata contains metadata necessary for the mamba2 triton
        # kernels to operate in continuous batching and in chunked prefill
        # modes; they are computed at top-level model forward since they
        # stay the same and reused for all mamba layers in the same iteration
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
        attn_metadata: AttentionMetadata = forward_context.attn_metadata
        if envs.VLLM_USE_V1:
            if attn_metadata is not None:
                assert isinstance(attn_metadata, dict)
                attn_metadata = attn_metadata[self.prefix]
                mamba2_metadata = attn_metadata
                assert isinstance(attn_metadata, Mamba2AttentionMetadata)
                self_kv_cache = self.kv_cache[forward_context.virtual_engine]
                # conv_state = (..., dim, width-1) yet contiguous along 'dim'
                conv_state = self_kv_cache[0].transpose(-1, -2)
                ssm_state = self_kv_cache[1]
                state_indices_tensor = attn_metadata.state_indices_tensor
                has_initial_states_p = attn_metadata.has_initial_states_p
                prep_initial_states = attn_metadata.prep_initial_states
                chunk_size = attn_metadata.chunk_size
                seq_idx_p = attn_metadata.seq_idx_p
                chunk_indices_p = attn_metadata.chunk_indices_p
                chunk_offsets_p = attn_metadata.chunk_offsets_p
        else:
            conv_state = mamba_cache_params.conv_state
            ssm_state = mamba_cache_params.ssm_state
            state_indices_tensor = mamba_cache_params.state_indices_tensor
            has_initial_states_p = mamba2_metadata.has_initial_states
            prep_initial_states = mamba2_metadata.prep_initial_states
            chunk_size = mamba2_metadata.chunk_size
            seq_idx_p = mamba2_metadata.seq_idx
            chunk_indices_p = mamba2_metadata.chunk_indices
            chunk_offsets_p = mamba2_metadata.chunk_offsets
298

Shinichi Hemmi's avatar
Shinichi Hemmi committed
299
        # 1. Gated MLP's linear projection
300
301
        projected_states = self.in_proj(hidden_states)
        gate, hidden_states = projected_states.chunk(2, dim=-1)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
302
303
304
305
306

        # 2. Convolution sequence transformation
        conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0),
                                               self.conv1d.weight.size(2))

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
        if envs.VLLM_USE_V1 and attn_metadata is None:
            # V1 profile run
            hidden_states = (hidden_states.transpose(0, 1).clone().transpose(
                0, 1)).contiguous()
            output[:] = self.out_proj(hidden_states)
            return

        num_prefills = attn_metadata.num_prefills  # request count
        num_decodes = attn_metadata.num_decode_tokens  # token count (=request)
        num_prefill_tokens = attn_metadata.num_prefill_tokens  # token count
        has_prefill = num_prefills > 0
        has_decode = num_decodes > 0
        num_actual_tokens = num_prefill_tokens + num_decodes

        # NOTE: V0 put prefill before decode, v1 puts decode before prefill
322
323
        # Separate prefill and decode by splitting varlen input
        # Split along token dimension
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
        if envs.VLLM_USE_V1:
            hidden_states_d, hidden_states_p = torch.split(
                hidden_states[:num_actual_tokens],
                [num_decodes, num_prefill_tokens],
                dim=0,
            )
            gate_d, gate_p = torch.split(gate[:num_actual_tokens],
                                         [num_decodes, num_prefill_tokens],
                                         dim=0)
            # Split along batch dimension
            state_indices_tensor_d, state_indices_tensor_p = torch.split(
                state_indices_tensor,
                [num_decodes, num_prefills],
                dim=0,
            )
            query_start_loc_p = (
                attn_metadata.query_start_loc[-num_prefills - 1:] -
                num_decodes if has_prefill else None)
        else:
            hidden_states_p, hidden_states_d = torch.split(
                hidden_states,
                [num_prefill_tokens, num_decodes],
                dim=0,
            )
            gate_p, gate_d = torch.split(gate,
                                         [num_prefill_tokens, num_decodes],
                                         dim=0)
            # Split along batch dimension
            state_indices_tensor_p, state_indices_tensor_d = torch.split(
                state_indices_tensor,
                [num_prefills, num_decodes],
                dim=0,
            )
            query_start_loc_p = (attn_metadata.query_start_loc[:num_prefills +
                                                               1]
                                 if has_prefill else None)
360

361
362
363
364
365
366
367
368
369
370
        # Preallocate output tensor to avoid memcpy cost for merging prefill
        # and decode outputs
        preallocated_ssm_out = torch.empty(
            [
                num_prefill_tokens + num_decodes,
                (self.num_heads // self.tp_size) * self.head_dim
            ],
            dtype=hidden_states.dtype,
            device=hidden_states.device,
        )
371
372
373
374
375
376
377
378
379
380
381
382
        if envs.VLLM_USE_V1:
            preallocated_ssm_out_d, preallocated_ssm_out_p = torch.split(
                preallocated_ssm_out,
                [num_decodes, num_prefill_tokens],
                dim=0,
            )
        else:
            preallocated_ssm_out_p, preallocated_ssm_out_d = torch.split(
                preallocated_ssm_out,
                [num_prefill_tokens, num_decodes],
                dim=0,
            )
383
384
385
386
387

        # Process prefill requests
        if has_prefill:
            # 2. Convolution sequence transformation
            # - "cache_indices" updates the conv_state cache in positions
388
389
390
391
392
393
            #   pointed to by "state_indices_tensor"
            x = hidden_states_p.transpose(
                0, 1)  # this is the form that causal-conv see
            if mamba2_metadata.cu_seqlen is None:
                mamba2_metadata = update_metadata(x, query_start_loc_p,
                                                  mamba2_metadata)
394
            hidden_states_p = causal_conv1d_fn(
395
                x,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
396
397
398
                conv_weights,
                self.conv1d.bias,
                activation=self.activation,
399
400
                conv_states=conv_state,
                has_initial_state=has_initial_states_p,
401
                cache_indices=state_indices_tensor_p,
402
                metadata=mamba2_metadata,
403
404
405
406
407
408
409
410
411
412
413
414
                query_start_loc=query_start_loc_p)
            hidden_states_p = hidden_states_p.transpose(0, 1)
            hidden_states_p = hidden_states_p[:num_prefill_tokens]
            # In some instances, the following `bcdt_proj` op
            # requires contiguous inputs
            # (e.g. if the Marlin kernel is used).
            hidden_states_p = hidden_states_p.contiguous()

            B, C, dt = self._project_ssm_parameters(hidden_states_p)

            # 3. State Space Model sequence transformation
            initial_states = None
415
            if has_initial_states_p is not None and prep_initial_states:
416
                # making a copy of the states
417
418
419
420
421
422
423
424
                if envs.VLLM_USE_V1:
                    initial_states = torch.where(
                        has_initial_states_p[:, None, None, None],
                        ssm_state[state_indices_tensor_p], 0)
                else:
                    initial_states = torch.where(
                        has_initial_states_p[:num_prefills, None, None, None],
                        ssm_state[state_indices_tensor_p], 0)
425
            varlen_state = mamba_chunk_scan_combined(
426
427
428
429
430
431
432
                hidden_states_p.view(1, num_prefill_tokens,
                                     self.num_heads // self.tp_size,
                                     self.head_dim),
                dt.unsqueeze(0),
                self.A,
                B.view(1, num_prefill_tokens, 1, -1),
                C.view(1, num_prefill_tokens, 1, -1),
433
                chunk_size=chunk_size,
434
435
436
437
                D=self.D,
                z=gate_p.view(1, num_prefill_tokens,
                              self.num_heads // self.tp_size, self.head_dim),
                dt_bias=self.dt_bias,
438
439
440
441
                seq_idx=seq_idx_p,
                chunk_indices=chunk_indices_p,
                chunk_offsets=chunk_offsets_p,
                cu_seqlens=query_start_loc_p,
442
443
444
445
446
                initial_states=initial_states,
                return_varlen_states=True,
                return_final_states=False,
                dt_softplus=True,
                dt_limit=(0.0, float("inf")),
447
448
                out=preallocated_ssm_out_p.view(1, num_prefill_tokens, -1,
                                                self.head_dim),
449
                state_dtype=ssm_state.dtype,
450
451
452
453
            )

            # update ssm states
            # - varlen state is a (batch, nheads, headdim, dstate) tensor
454
            ssm_state[state_indices_tensor_p] = varlen_state
455
456
457
458
459
460

        # Process decode requests
        if has_decode:
            # 2. Convolution sequence transformation
            hidden_states_d = causal_conv1d_update(
                hidden_states_d,
461
                conv_state,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
462
463
464
                conv_weights,
                self.conv1d.bias,
                self.activation,
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
                conv_state_indices=state_indices_tensor_d)

            B, C, dt = self._project_ssm_parameters(hidden_states_d)

            # 3. State Space Model sequence transformation
            A = self.A[:, None, ...][:, :,
                                     None].expand(-1, self.head_dim,
                                                  self.config.mamba_d_state)
            dt = dt[:, :, None].expand(-1, -1, self.head_dim)
            dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
            D = self.D[:, None, ...].expand(-1, self.head_dim)
            B = B.unsqueeze(1)
            C = C.unsqueeze(1)
            hidden_states_d = hidden_states_d.view(
                -1, self.num_heads // self.tp_size, self.head_dim)

            # - the hidden is reshaped into (bs, num_heads, head_dim)
            # - mamba_cache_params.ssm_state's slots will be selected
            #   using state_indices_tensor_d
484
485

            # NOTE: final output is an in-place update of out tensor
486
            selective_state_update(
487
                ssm_state,
488
489
490
                hidden_states_d,
                dt,
                A,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
491
492
                B,
                C,
493
494
495
                D,
                z=gate_d.reshape(num_decodes, -1, self.head_dim),
                dt_bias=dt_bias,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
496
                dt_softplus=True,
497
                state_batch_indices=state_indices_tensor_d,
498
499
                out=preallocated_ssm_out_d.view(num_decodes, -1,
                                                self.head_dim),
500
            )
Shinichi Hemmi's avatar
Shinichi Hemmi committed
501
502

        # 4. Final linear projection
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        output[:num_actual_tokens] = self.out_proj(preallocated_ssm_out)

    def get_state_dtype(self) -> tuple[torch.dtype, torch.dtype]:
        assert self.model_config is not None
        assert self.cache_config is not None
        return MambaStateDtypeCalculator.mamba2_state_dtype(
            self.model_config.dtype,
            self.cache_config.mamba_cache_dtype,
            self.cache_config.mamba_ssm_cache_dtype,
        )

    def get_state_shape(self) -> tuple[tuple[int, ...], tuple[int, ...]]:
        return MambaStateShapeCalculator.mamba2_state_shape(
            intermediate_size=self.intermediate_size,
            tp_world_size=get_tensor_model_parallel_world_size(),
            n_groups=0,
            num_heads=self.num_heads,
            head_dim=self.head_dim,
            state_size=self.ssm_state_size,
            conv_kernel=self.conv_kernel_size,
        )

    @property
    def mamba_type(self) -> str:
        return "mamba2"

    def get_attn_backend(self) -> type["AttentionBackend"]:
        from vllm.v1.attention.backends.mamba2_attn import (
            Mamba2AttentionBackend)
        return Mamba2AttentionBackend


def plamo2_mamba_mixer(
    hidden_states: torch.Tensor,
    output: torch.Tensor,
    layer_name: str,
) -> None:
    forward_context: ForwardContext = get_forward_context()
    self = forward_context.no_compile_layers[layer_name]
    self.forward_cuda(hidden_states=hidden_states,
                      output=output,
                      mamba_cache_params=None,
                      mamba2_metadata=None)


def plamo2_mamba_mixer_fake(
    hidden_states: torch.Tensor,
    output: torch.Tensor,
    layer_name: str,
) -> None:
    return


direct_register_custom_op(
    op_name="plamo2_mamba_mixer",
    op_func=plamo2_mamba_mixer,
    mutates_args=["output"],
    fake_impl=plamo2_mamba_mixer_fake,
    dispatch_key=current_platform.dispatch_key,
)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
563
564
565
566
567
568
569
570
571
572
573
574
575
576


class DenseMLP(nn.Module):

    def __init__(
        self,
        config: Plamo2Config,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ) -> None:
        super().__init__()
        self.hidden_size = config.hidden_size
        self.intermediate_size = config.intermediate_size
        self.gate_up_proj = MergedColumnParallelLinear(
577
578
            self.hidden_size,
            [self.intermediate_size] * 2,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
579
580
            bias=False,
            prefix=f"{prefix}.gate_up_proj",
581
582
583
584
            quant_config=quant_config,
            return_bias=False,
        )
        self.act = SiluAndMul()
Shinichi Hemmi's avatar
Shinichi Hemmi committed
585
586
587
588
        self.down_proj = RowParallelLinear(self.intermediate_size,
                                           self.hidden_size,
                                           bias=False,
                                           prefix=f"{prefix}.down_proj",
589
590
                                           quant_config=quant_config,
                                           return_bias=False)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
591
592

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
593
594
595
        h = self.gate_up_proj(hidden_states)
        h = self.act(h)
        return self.down_proj(h)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
596
597
598
599
600


class Plamo2AttentionMixer(nn.Module):

    def __init__(self,
601
602
                 *,
                 vllm_config: VllmConfig,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
603
604
605
                 prefix: str = "",
                 **kwargs) -> None:
        super().__init__()
606
607
608
        config = vllm_config.model_config.hf_config
        cache_config = vllm_config.cache_config
        quant_config = vllm_config.quant_config
Shinichi Hemmi's avatar
Shinichi Hemmi committed
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
        self.hidden_size = config.hidden_size
        tp_size = get_tensor_model_parallel_world_size()
        self.total_num_heads = config.num_attention_heads
        assert self.total_num_heads % tp_size == 0
        self.num_heads = self.total_num_heads // tp_size
        self.total_num_kv_heads = config.num_key_value_heads
        if self.total_num_kv_heads >= tp_size:
            # Number of KV heads is greater than TP size, so we partition
            # the KV heads across multiple tensor parallel GPUs.
            assert self.total_num_kv_heads % tp_size == 0
        else:
            # Number of KV heads is less than TP size, so we replicate
            # the KV heads across multiple tensor parallel GPUs.
            assert tp_size % self.total_num_kv_heads == 0
        self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
        self.head_dim = config.hidden_size_per_head
        self.q_size = self.num_heads * self.head_dim
        self.kv_size = self.num_kv_heads * self.head_dim
        self.scaling = self.head_dim**-0.5

        self.qkv_proj = QKVParallelLinear(
            config.hidden_size,
            self.head_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=False,
            quant_config=quant_config,
        )
        self.o_proj = RowParallelLinear(self.total_num_heads * self.head_dim,
                                        config.hidden_size,
                                        bias=False,
                                        quant_config=quant_config)

        self.rope_theta = config.rope_theta if hasattr(config,
                                                       "rope_theta") else 10000
        self.rope_scaling = config.rope_scaling if hasattr(
            config, "rope_scaling") else None
646
647
648
649
650
        max_position = config.max_position_embeddings
        if hasattr(vllm_config.model_config, "max_model_len") and isinstance(
                vllm_config.model_config.max_model_len, int):
            max_position = min(max_position,
                               vllm_config.model_config.max_model_len)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
651
652
653
654

        self.rotary_emb = get_rope(
            self.head_dim,
            rotary_dim=self.head_dim,
655
            max_position=max_position,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
656
657
658
            base=self.rope_theta,
            rope_scaling=self.rope_scaling,
        )
659
660
661
        self.q_norm = RMSNorm(config.hidden_size_per_head,
                              eps=config.rms_norm_eps)
        self.q_norm.weight = torch.nn.Parameter(
Shinichi Hemmi's avatar
Shinichi Hemmi committed
662
            torch.ones((self.num_heads, config.hidden_size_per_head)))
663
664
665
666
667
        set_weight_attrs(self.q_norm.weight,
                         {"weight_loader": sharded_weight_loader(0)})
        self.k_norm = RMSNorm(config.hidden_size_per_head,
                              eps=config.rms_norm_eps)
        self.k_norm.weight = torch.nn.Parameter(
Shinichi Hemmi's avatar
Shinichi Hemmi committed
668
            torch.ones((self.num_kv_heads, config.hidden_size_per_head)))
669
670
671
672
673
674
        # Tensor-parallelism shards the K norm weights to the tp ranks
        # in a head-wise manner. This approach does not work if there is only
        # a single KV head, as is the case for PLaMo 2-1B.
        if self.total_num_kv_heads != 1:
            set_weight_attrs(self.k_norm.weight,
                             {"weight_loader": sharded_weight_loader(0)})
Shinichi Hemmi's avatar
Shinichi Hemmi committed
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692

        self.attn = Attention(
            self.num_heads,
            self.head_dim,
            self.scaling,
            num_kv_heads=self.num_kv_heads,
            cache_config=cache_config,
            prefix=f"{prefix}.attn",
        )

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        **kwargs,
    ) -> torch.Tensor:
        qkv, _ = self.qkv_proj(hidden_states)
        q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
693
694
695
696
697
698
699
700

        q_shape = q.shape
        q = q.reshape(q_shape[:-1] + self.q_norm.weight.shape)
        q = self.q_norm.forward_native(q).reshape(q_shape)
        k_shape = k.shape
        k = k.reshape(k_shape[:-1] + self.k_norm.weight.shape)
        k = self.k_norm.forward_native(k).reshape(k_shape)

Shinichi Hemmi's avatar
Shinichi Hemmi committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
        q, k = self.rotary_emb(positions, q, k)
        attn_output = self.attn(q, k, v)
        output, _ = self.o_proj(attn_output)
        return output


class Plamo2DecoderLayer(nn.Module):

    def __init__(self,
                 vllm_config: VllmConfig,
                 layer_idx: int,
                 prefix: str = "",
                 **kwargs) -> None:
        super().__init__()
        config = vllm_config.model_config.hf_config
        quant_config = vllm_config.quant_config

        self.is_mamba = is_mamba(config, layer_idx)
        if self.is_mamba:
720
            self.mixer = Plamo2MambaMixer(vllm_config=vllm_config,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
721
722
                                          prefix=f"{prefix}.mixer")
        else:
723
            self.mixer = Plamo2AttentionMixer(vllm_config=vllm_config,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
                                              prefix=f"{prefix}.mixer")

        self.mlp = DenseMLP(config=config,
                            quant_config=quant_config,
                            prefix=f"{prefix}.mlp")
        self.pre_mixer_norm = RMSNorm(config.hidden_size,
                                      eps=config.rms_norm_eps)
        self.post_mixer_norm = RMSNorm(config.hidden_size,
                                       eps=config.rms_norm_eps)
        self.pre_mlp_norm = RMSNorm(config.hidden_size,
                                    eps=config.rms_norm_eps)
        self.post_mlp_norm = RMSNorm(config.hidden_size,
                                     eps=config.rms_norm_eps)

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        residual: Optional[torch.Tensor],
        mamba_cache_params: MambaCacheParams,
744
        mamba2_metadata: Mamba2Metadata,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
745
746
747
748
749
750
751
752
753
        **kwargs,
    ):
        if residual is None:
            residual = hidden_states
            hidden_states = self.pre_mixer_norm(hidden_states)
        else:
            hidden_states, residual = self.pre_mixer_norm(
                hidden_states, residual)

754
755
756
757
758
759
760
761
762
763
764
765
        if self.is_mamba:
            # Plamo2MambaMixer writes output to this tensor
            output = torch.empty_like(hidden_states)
            mixer_kwargs = {
                "output": output,
                "mamba_cache_params": mamba_cache_params,
                "mamba2_metadata": mamba2_metadata,
            }
        else:
            mixer_kwargs = {
                "positions": positions,
            }
766
767
        hidden_states = self.mixer(
            hidden_states=hidden_states,
768
            **mixer_kwargs,
769
        )
770
771
        if self.is_mamba:
            hidden_states = output
Shinichi Hemmi's avatar
Shinichi Hemmi committed
772
773
774
775
776
777
778
779
780
781
        hidden_states = self.post_mixer_norm(hidden_states)
        # Fully Connected
        hidden_states, residual = self.pre_mlp_norm(hidden_states, residual)
        hidden_states = self.mlp(hidden_states)
        hidden_states = self.post_mlp_norm(hidden_states)
        return hidden_states, residual


class Plamo2Decoder(torch.nn.Module):

782
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
Shinichi Hemmi's avatar
Shinichi Hemmi committed
783
        super().__init__()
784
785
786
787
788
789
790
791
792
        config = vllm_config.model_config.hf_config
        extra_kwargs = {"is_lora_enabled": bool(vllm_config.lora_config)}

        def get_layer(prefix: str):
            layer_idx = int(prefix.rsplit(".", 1)[1])
            return Plamo2DecoderLayer(vllm_config=vllm_config,
                                      layer_idx=layer_idx,
                                      prefix=prefix,
                                      **extra_kwargs)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
793

794
795
        self.start_layer, self.end_layer, self.layers = make_layers(
            config.num_hidden_layers, get_layer, prefix=f"{prefix}.layers")
Shinichi Hemmi's avatar
Shinichi Hemmi committed
796
797
798
799
800
801
802

    def forward(
        self,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        residual: Optional[torch.Tensor],
        mamba_cache_params: MambaCacheParams,
803
        mamba2_metadata: Mamba2Metadata,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
804
805
    ) -> torch.Tensor:
        mamba_cache_index = 0
806
        for layer in islice(self.layers, self.start_layer, self.end_layer):
Shinichi Hemmi's avatar
Shinichi Hemmi committed
807
            layer_mamba_cache_params = None
808
            if layer.is_mamba and mamba_cache_params is not None:
Shinichi Hemmi's avatar
Shinichi Hemmi committed
809
810
811
812
813
814
815
816
                layer_mamba_cache_params = mamba_cache_params.at_layer_idx(
                    mamba_cache_index)
                mamba_cache_index += 1

            hidden_states, residual = layer(
                positions=positions,
                hidden_states=hidden_states,
                residual=residual,
817
818
819
                mamba_cache_params=layer_mamba_cache_params,
                mamba2_metadata=mamba2_metadata,
            )
Shinichi Hemmi's avatar
Shinichi Hemmi committed
820
821
822
        return hidden_states, residual


823
824
@support_torch_compile
class Plamo2Model(torch.nn.Module):
Shinichi Hemmi's avatar
Shinichi Hemmi committed
825
826

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
827
        super().__init__()
Shinichi Hemmi's avatar
Shinichi Hemmi committed
828
829
830
831
832
833
834
835
836
837
838
839
840
841

        config = vllm_config.model_config.hf_config

        self.config = config
        self.padding_idx = config.pad_token_id
        self.vocab_size = config.vocab_size
        self.org_vocab_size = config.vocab_size

        self.embed_tokens = VocabParallelEmbedding(
            self.vocab_size,
            config.hidden_size,
            org_num_embeddings=config.vocab_size,
            prefix=f"{prefix}.embed_tokens",
        )
842
843
844
        self.make_empty_intermediate_tensors = (
            make_empty_intermediate_tensors_factory(
                ["hidden_states", "residual"], config.hidden_size))
845
846
        self.layers = Plamo2Decoder(vllm_config=vllm_config,
                                    prefix=f"{prefix}.layers")
Shinichi Hemmi's avatar
Shinichi Hemmi committed
847
848
        self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)

849
850
851
    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.embed_tokens(input_ids)

Shinichi Hemmi's avatar
Shinichi Hemmi committed
852
853
854
855
856
857
858
859
    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        mamba_cache_params: MambaCacheParams,
        intermediate_tensors: Optional[IntermediateTensors] = None,
        inputs_embeds: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
860
861
862
863
864
865
866
867
868
869
870
        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"]

871
872
873
874
875
876
877
878
879
880
        if not envs.VLLM_USE_V1:
            attn_metadata: AttentionMetadata = get_forward_context(
            ).attn_metadata
            mamba2_metadata = prepare_mamba2_metadata(
                chunk_size=self.config.mamba_chunk_size,
                attn_metadata=attn_metadata,
            )
        else:
            # v1 get mamba2_metadata from forward_context
            mamba2_metadata = None
Shinichi Hemmi's avatar
Shinichi Hemmi committed
881
882
883
884
885

        hidden_states, residual = self.layers(
            positions=positions,
            hidden_states=hidden_states,
            residual=residual,
886
887
888
889
890
891
892
893
            mamba_cache_params=mamba_cache_params,
            mamba2_metadata=mamba2_metadata,
        )
        if not get_pp_group().is_last_rank:
            return IntermediateTensors({
                "hidden_states": hidden_states,
                "residual": residual
            })
Shinichi Hemmi's avatar
Shinichi Hemmi committed
894
895
896
897
        hidden_states, _ = self.norm(hidden_states, residual)
        return hidden_states


898
class Plamo2ForCausalLM(torch.nn.Module, HasInnerState, SupportsPP, IsHybrid):
Shinichi Hemmi's avatar
Shinichi Hemmi committed
899
900
901
902
903
904
905
906
907
    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
    }

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
908
        super().__init__()
Shinichi Hemmi's avatar
Shinichi Hemmi committed
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
        config = vllm_config.model_config.hf_config
        scheduler_config = vllm_config.scheduler_config

        self.config = config
        self.vllm_config = vllm_config
        self.model_config = vllm_config.model_config
        self.scheduler_config = scheduler_config

        # ModelConfig.get_head_size assumes head_dim is set or calculated as
        # hidden_size // num_attention_heads. However, this is not always
        # the case for PLaMo2, as indicated by the FIXME comment.
        self.config.head_dim = self.config.hidden_size_per_head

        self.model = Plamo2Model(vllm_config=vllm_config,
                                 prefix=maybe_prefix(prefix, "model"))
        self.vocab_size = self.config.vocab_size
        self.unpadded_vocab_size = self.config.vocab_size
        num_embeddings = ((self.vocab_size + 15) // 16) * 16
        self.lm_head = ParallelLMHead(
            num_embeddings,
            self.config.hidden_size,
            org_num_embeddings=self.config.vocab_size,
            padding_size=DEFAULT_VOCAB_PADDING_SIZE,
            prefix=f"{prefix}.lm_head",
        )
        if self.config.tie_word_embeddings:
            self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens)

        # Used to track and store by the Mamba cache between steps.
        self.mamba_cache: Optional[MambaCacheManager] = None

        self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
                                                self.config.vocab_size)
942
943
944
        self.sampler = get_sampler()
        self.make_empty_intermediate_tensors = (
            self.model.make_empty_intermediate_tensors)
Shinichi Hemmi's avatar
Shinichi Hemmi committed
945

946
947
948
    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.get_input_embeddings(input_ids)

Shinichi Hemmi's avatar
Shinichi Hemmi committed
949
950
951
952
953
954
    def forward(self,
                input_ids: torch.Tensor,
                positions: torch.Tensor,
                intermediate_tensors: Optional[IntermediateTensors] = None,
                inputs_embeds: Optional[torch.Tensor] = None,
                **kwargs):
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
        if not envs.VLLM_USE_V1:
            if self.mamba_cache is None:
                num_mamba_layers = (
                    self.model_config.get_num_layers_by_block_type(
                        self.vllm_config.parallel_config,
                        LayerBlockType.mamba))

                mamba_state_shape = self.get_mamba_state_shape_from_config(
                    self.vllm_config, use_v1=False)
                mamba_state_dtype = \
                    self.get_mamba_state_dtype_from_config(
                    self.vllm_config)
                self.mamba_cache = MambaCacheManager(self.vllm_config,
                                                     num_mamba_layers,
                                                     *mamba_state_shape,
                                                     *mamba_state_dtype)

            mamba_cache_params = self.mamba_cache.current_run_tensors(**kwargs)
        else:
            # NOTE: mamba_cache_params is not needed for v1
            mamba_cache_params = None
Shinichi Hemmi's avatar
Shinichi Hemmi committed
976
977
978
979
980
981
982
983
984
985
986
987

        hidden_states = self.model(input_ids, positions, mamba_cache_params,
                                   intermediate_tensors, inputs_embeds)
        return hidden_states

    def copy_inputs_before_cuda_graphs(self, input_buffers, **kwargs):
        return self.mamba_cache.copy_inputs_before_cuda_graphs(
            input_buffers, **kwargs)

    def get_seqlen_agnostic_capture_inputs(self, batch_size: int):
        return self.mamba_cache.get_seqlen_agnostic_capture_inputs(batch_size)

988
989
990
991
992
993
994
995
996
997
    @classmethod
    def get_mamba_state_dtype_from_config(
        cls,
        vllm_config: "VllmConfig",
    ) -> tuple[torch.dtype, torch.dtype]:

        return MambaStateDtypeCalculator.mamba2_state_dtype(
            vllm_config.model_config.dtype,
            vllm_config.cache_config.mamba_cache_dtype,
            vllm_config.cache_config.mamba_ssm_cache_dtype,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
998
        )
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028

    @classmethod
    def get_mamba_state_shape_from_config(
        cls,
        vllm_config: "VllmConfig",
        use_v1: bool = True,
    ) -> tuple[tuple[int, int], tuple[int, int, int]]:
        """Calculate shapes for Mamba's convolutional and state caches.
        Args:
            vllm_config: vLLM config
            use_v1: Get shapes for V1 (or V0)
        Returns:
            Tuple containing:
            - conv_state_shape: Shape for convolutional state cache
            - temporal_state_shape: Shape for state space model cache
        """
        parallel_config = vllm_config.parallel_config
        hf_config = vllm_config.model_config.hf_config
        intermediate_size =\
                hf_config.mamba_num_heads * hf_config.hidden_size_per_head

        return MambaStateShapeCalculator.mamba2_state_shape(
            intermediate_size=intermediate_size,
            tp_world_size=parallel_config.tensor_parallel_size,
            n_groups=0,
            num_heads=hf_config.mamba_num_heads,
            head_dim=hf_config.hidden_size_per_head,
            state_size=hf_config.mamba_d_state,
            conv_kernel=hf_config.mamba_d_conv,
            use_v1=use_v1,
Shinichi Hemmi's avatar
Shinichi Hemmi committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
        )

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[torch.Tensor]:
        logits = self.logits_processor(self.lm_head, hidden_states,
                                       sampling_metadata)
        return logits

1040
1041
1042
1043
1044
1045
1046
1047
    def sample(
        self,
        logits: Optional[torch.Tensor],
        sampling_metadata: SamplingMetadata,
    ) -> Optional[SamplerOutput]:
        next_tokens = self.sampler(logits, sampling_metadata)
        return next_tokens

1048
    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
Shinichi Hemmi's avatar
Shinichi Hemmi committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
        params_dict = dict(self.named_parameters())
        for name, loaded_weight in weights:

            # Both tie_word_embeddings=True and lm_head.weight in the safetensor
            # at the same time causes dict key access error.
            if name == "lm_head.weight" and self.config.tie_word_embeddings:
                assert "lm_head.weight" not in params_dict
                continue

            # Update the weight names to be compatible with the vllm version
            # of the model.
            # Do not change the order of the replacements.
            replacements = {
                # Rename incompatible weight names.
                ".A_log": ".A",
                ".B_norm_weight": ".B_norm.weight",
                ".C_norm_weight": ".C_norm.weight",
                ".dt_norm_weight": ".dt_norm.weight",
1067
1068
                ".q_weight": ".q_norm.weight",
                ".k_weight": ".k_norm.weight",
Shinichi Hemmi's avatar
Shinichi Hemmi committed
1069
1070
1071
1072
1073
1074
            }
            # Apply replacements based on the defined mappings
            for old, new in replacements.items():
                if old in name:
                    name = name.replace(old, new)

1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
            # Reshape the in_proj weights to match the shape expected
            # by MergedColumnParallelLinear.
            # This works both for unquantized weights and
            # for quantized weights.
            # In the quantized case, the weights are already transposed.
            # Also, in addition to the quantized weights,
            # the zero points and scales have to be reshaped as well.
            # Packing should not be affected by this.
            if ".mixer.in_proj.weight" in name \
                or "mixer.in_proj.qweight" in name \
                or "mixer.in_proj.scales" in name \
                or "mixer.in_proj.qzeros" in name:
                if "mixer.in_proj.weight" in name:
                    loaded_weight = loaded_weight.transpose(0, 1)
                # for weight:
                # loaded_weight.shape[0] == self.config.hidden_size
                # for qweight:
                # loaded_weight.shape[0] == self.config.hidden_size // param.pack_factor  # noqa
                # for scales and qzeros:
                # loaded_weight.shape[0] == self.config.hidden_size // self.vllm_config.quant_config.group_size  # noqa
Shinichi Hemmi's avatar
Shinichi Hemmi committed
1095
                loaded_weight = loaded_weight.reshape(
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
                    loaded_weight.shape[0], self.config.mamba_num_heads, -1)
                gate_weight, hidden_states_weight = loaded_weight.chunk(2,
                                                                        dim=-1)
                gate_weight = gate_weight.reshape(loaded_weight.shape[0], -1)
                hidden_states_weight = hidden_states_weight.reshape(
                    loaded_weight.shape[0], -1)
                loaded_weight = torch.cat([gate_weight, hidden_states_weight],
                                          dim=-1)
                if "mixer.in_proj.weight" in name:
                    loaded_weight = loaded_weight.transpose(0, 1)

Shinichi Hemmi's avatar
Shinichi Hemmi committed
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
            # Offset parameter with vllm's RMSNorm haven't been supported yet.
            if ".pre_mixer_norm" in name:
                loaded_weight += 1.0
            elif ".post_mixer_norm" in name:
                loaded_weight += 1.0 / 5
            elif ".pre_mlp_norm" in name:
                loaded_weight += 1.0
            elif ".post_mlp_norm" in name:
                loaded_weight += 1.0 / (5**1.5)
            elif "model.norm.weight" in name:
                loaded_weight += 1.0

1119
1120
1121
1122
            # Skip layers on other devices.
            if is_pp_missing_parameter(name, self):
                continue

Shinichi Hemmi's avatar
Shinichi Hemmi committed
1123
1124
1125
1126
            param = params_dict[name]
            weight_loader = getattr(param, "weight_loader",
                                    default_weight_loader)
            weight_loader(param, loaded_weight)