minicpmv.py 53.6 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
22
23
24
# Adapted from
# https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
# Copyright 2023 The vLLM team.
# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
#
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
# and OPT implementations in this library. It has been modified from its
# original forms to accommodate minor architectural differences compared
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
#
# 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.
Alphi's avatar
Alphi committed
25
"""Inference-only MiniCPM-V model compatible with HuggingFace weights."""
26
import math
27
from collections import defaultdict
28
from collections.abc import Iterable, Mapping, Sequence
29
from functools import partial
30
from typing import Annotated, Any, Callable, Literal, Optional, Union
31

32
import numpy as np
33
import torch
Alphi's avatar
Alphi committed
34
import torch.types
35
from torch import nn
36
from transformers import BatchFeature, PretrainedConfig
37
from typing_extensions import TypeVar
38

39
from vllm.config import VllmConfig
40
from vllm.model_executor.layers.quantization import QuantizationConfig
tc-mb's avatar
tc-mb committed
41
42
from vllm.model_executor.layers.quantization.awq import AWQConfig
from vllm.model_executor.layers.quantization.awq_marlin import AWQMarlinConfig
43
from vllm.model_executor.layers.resampler import (BaseResampler, Resampler2,
44
                                                  get_2d_sincos_pos_embed)
Jee Jee Li's avatar
Jee Jee Li committed
45
from vllm.model_executor.model_loader.utils import set_default_torch_dtype
46
47
from vllm.model_executor.models.llama import LlamaForCausalLM
from vllm.model_executor.models.minicpm import MiniCPMForCausalLM
48
from vllm.model_executor.models.module_mapping import MultiModelKeys
49
from vllm.model_executor.models.qwen2 import Qwen2ForCausalLM
50
from vllm.model_executor.sampling_metadata import SamplingMetadata
51
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalKwargsItems
52
53
from vllm.multimodal.inputs import (MultiModalDataDict, MultiModalFieldConfig,
                                    NestedTensors)
54
55
from vllm.multimodal.parse import (DictEmbeddingItems, ImageItem,
                                   ImageProcessorItems, ImageSize,
56
57
                                   ModalityData, ModalityDataItems,
                                   MultiModalDataItems, MultiModalDataParser,
58
                                   VideoItem, VideoProcessorItems)
59
from vllm.multimodal.processing import (BaseMultiModalProcessor,
60
                                        BaseProcessingInfo, PromptReplacement,
61
62
                                        PromptUpdate, PromptUpdateDetails,
                                        ResolvedPromptUpdate, _seq2text)
63
from vllm.multimodal.profiling import BaseDummyInputsBuilder
64
from vllm.platforms import current_platform
65
from vllm.sequence import IntermediateTensors
66
from vllm.utils import flatten_2d_lists
67
from vllm.utils.tensor_schema import TensorSchema, TensorShape
68

Jee Jee Li's avatar
Jee Jee Li committed
69
from .idefics2_vision_model import Idefics2VisionTransformer
70
71
72
73
from .interfaces import (MultiModalEmbeddings, SupportsLoRA,
                         SupportsMultiModal, SupportsPP)
from .utils import (AutoWeightsLoader, flatten_bn, maybe_prefix,
                    merge_multimodal_embeddings)
74

75
76
77
# For profile run
_MAX_FRAMES_PER_VIDEO = 16

78

79
class MiniCPMVImagePixelInputs(TensorSchema):
Jee Jee Li's avatar
Jee Jee Li committed
80
    """
81
82
83
84
85
86
    Dimensions:
        - bns: Batch size * number of images * number of slices
        - bn: Batch size * number of images
        - c: Number of channels
        - h: Height
        - w: Width
Jee Jee Li's avatar
Jee Jee Li committed
87
88
    """

89
90
91
92
93
94
    type: Literal["pixel_values"] = "pixel_values"

    # Note that the image size may vary, so we pass it as a list instead of a
    # batched tensor.
    pixel_values: Annotated[
        list[torch.Tensor],
95
        TensorShape("bns", "c", "h", "w", dynamic_dims={"h", "w"}),
96
97
98
99
100
101
102
103
104
105
106
107
    ]
    tgt_sizes: Annotated[
        torch.Tensor,
        TensorShape("bns", 2),  # This should be in `(height, width)` format.
    ]
    num_slices: Annotated[
        torch.Tensor,
        TensorShape("bn"),
    ]


class MiniCPMVImageEmbeddingInputs(TensorSchema):
Jee Jee Li's avatar
Jee Jee Li committed
108
    """
109
110
111
112
    Dimensions:
        - bn: Batch size * number of images
        - ns: Number of slices
        - hs: Hidden size (must match language model backbone)
Jee Jee Li's avatar
Jee Jee Li committed
113
114
    """

115
    type: Literal["image_embeds"]
116
117
118
119
    image_embeds: Annotated[
        Union[torch.Tensor, list[torch.Tensor]],
        TensorShape("bn", "ns", "hs"),
    ]
120
121
122
123
124


MiniCPMVImageInputs = Union[MiniCPMVImagePixelInputs,
                            MiniCPMVImageEmbeddingInputs]

Jee Jee Li's avatar
Jee Jee Li committed
125
126
127
128
129
DEFAULT_LN = partial(nn.LayerNorm, eps=1e-6)


class Resampler2_5(BaseResampler):

130
131
132
133
134
135
    def __init__(self,
                 num_queries: int,
                 embed_dim: int,
                 num_heads: int,
                 kv_dim: Optional[int] = None,
                 norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
136
                 max_size: tuple[int, int] = (70, 70),
137
138
139
140
141
142
143
144
145
                 quant_config: Optional[QuantizationConfig] = None,
                 prefix: str = "") -> None:
        super().__init__(num_queries,
                         embed_dim,
                         num_heads,
                         kv_dim,
                         norm_layer,
                         quant_config=quant_config,
                         prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
146
147
148

        self.max_size = max_size
        self._set_2d_pos_cache(self.max_size)
149

Alphi's avatar
Alphi committed
150
    def _set_2d_pos_cache(self,
151
                          max_size: tuple[int, int],
Jee Jee Li's avatar
Jee Jee Li committed
152
153
154
155
156
                          device: torch.types.Device = "cpu") -> None:
        pos_embed_arr = get_2d_sincos_pos_embed(self.embed_dim,
                                                max_size,
                                                version=(2, 5))
        pos_embed = torch.from_numpy(pos_embed_arr).float().to(device)
157
158
        self.register_buffer("pos_embed", pos_embed, persistent=False)

Alphi's avatar
Alphi committed
159
    def _adjust_pos_cache(self, tgt_sizes: torch.Tensor,
Jee Jee Li's avatar
Jee Jee Li committed
160
161
162
163
164
                          device: torch.types.Device) -> None:
        max_h = tgt_sizes[:, 0].max().item()
        max_w = tgt_sizes[:, 1].max().item()
        assert isinstance(max_h, int) and isinstance(max_w, int)

165
        if max_h > self.max_size[0] or max_w > self.max_size[1]:
Jee Jee Li's avatar
Jee Jee Li committed
166
            self.max_size = (
167
                max(max_h, self.max_size[0]),
Jee Jee Li's avatar
Jee Jee Li committed
168
169
                max(max_w, self.max_size[1]),
            )
170
171
            self._set_2d_pos_cache(self.max_size, device)

Jee Jee Li's avatar
Jee Jee Li committed
172
173
    def forward(self, x: torch.Tensor,
                tgt_sizes: torch.Tensor) -> torch.Tensor:
174
175
176
177
178
179
180
181
182
183
        assert x.shape[0] == tgt_sizes.shape[0]
        bs = x.shape[0]

        device = x.device
        dtype = x.dtype

        patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]

        self._adjust_pos_cache(tgt_sizes, device=device)

Jee Jee Li's avatar
Jee Jee Li committed
184
185
186
        max_patch_len = patch_len.max().item()
        assert isinstance(max_patch_len, int)

187
188
189
190
191
192
        key_padding_mask = torch.zeros((bs, max_patch_len),
                                       dtype=torch.bool,
                                       device=device)

        pos_embed = []
        for i in range(bs):
Jee Jee Li's avatar
Jee Jee Li committed
193
            tgt_h, tgt_w = tgt_sizes[i].tolist()
194
195
196
197
198
199
200
201
            pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape(
                (tgt_h * tgt_w, -1)).to(dtype))  # patches * D
            key_padding_mask[i, patch_len[i]:] = True
        pos_embed = torch.nn.utils.rnn.pad_sequence(pos_embed,
                                                    batch_first=True,
                                                    padding_value=0.0).permute(
                                                        1, 0,
                                                        2)  # BLD => L * B * D
Jee Jee Li's avatar
Jee Jee Li committed
202
        x, _ = self.kv_proj(x)  # B * L * D
203
204
205
206
207
208
209
210
        x = self.ln_kv(x).permute(1, 0, 2)  # L * B * D

        q = self.ln_q(self.query)  # Q * D

        out = self.attn(
            self._repeat(q, bs),  # Q * B * D
            x + pos_embed,  # L * B * D +  L * B * D
            x,
Jee Jee Li's avatar
Jee Jee Li committed
211
212
            key_padding_mask=key_padding_mask,
        )[0]
213
214
215
216
217
218
219
220
        #  out: Q * B * D
        x = out.permute(1, 0, 2)  # B * Q * D

        x = self.ln_post(x)
        x = x @ self.proj
        return x


221
def get_version_by_config(config: PretrainedConfig) -> tuple[int, ...]:
222
223
224
225
226
227
228
229
230
231
232
233
    version_float = getattr(config, "version", None)

    # The old configs do not include version number
    # TODO: Remove this after the HF repos are updated
    if version_float is None:
        if config.hidden_size == 2304 and config.query_num == 64:
            return (2, 0)
        return (2, 5)
    version_str = str(version_float)
    return tuple(int(x) for x in version_str.split("."))


234
def _minicpmv_field_config(hf_inputs: Mapping[str, torch.Tensor]):
235
236
237
238
239
240
    pixel_values = hf_inputs.get("pixel_values", torch.empty(0))
    num_images = len(pixel_values)

    video_pixel_values = hf_inputs.get("video_pixel_values", torch.empty(0))
    num_videos = len(video_pixel_values)

241
    return dict(
242
        pixel_values=MultiModalFieldConfig.batched("image"),
243
        image_sizes=MultiModalFieldConfig.batched("image"),
244
245
246
        tgt_sizes=MultiModalFieldConfig.batched("image"),
        image_embeds=MultiModalFieldConfig.batched("image"),
        video_pixel_values=MultiModalFieldConfig.batched("video"),
247
        video_image_sizes=MultiModalFieldConfig.batched("video"),
248
249
        video_tgt_sizes=MultiModalFieldConfig.batched("video"),
        video_embeds=MultiModalFieldConfig.batched("video"),
250
251
        image_token_id=MultiModalFieldConfig.shared("image", num_images),
        video_token_id=MultiModalFieldConfig.shared("video", num_videos),
252
253
254
255
256
257
258
259
    )


class MiniCPMVImageEmbeddingItems(DictEmbeddingItems):

    def __init__(
        self,
        data: Mapping[str, torch.Tensor],
260
261
262
263
        fields_factory: Callable[
            [Mapping[str, torch.Tensor]],
            Mapping[str, MultiModalFieldConfig],
        ],
264
265
266
267
268
    ) -> None:
        super().__init__(
            data,
            modality="image",
            required_fields={"image_embeds", "image_sizes"},
269
            fields_factory=fields_factory,
270
271
272
273
274
275
276
277
278
279
280
281
        )

    def get_image_size(self, index: int) -> ImageSize:
        image_size = self.get(index)["image_sizes"].tolist()
        return ImageSize(width=image_size[0], height=image_size[1])


class MiniCPMVVideoEmbeddingItems(DictEmbeddingItems):

    def __init__(
        self,
        data: Mapping[str, torch.Tensor],
282
283
284
285
        fields_factory: Callable[
            [Mapping[str, torch.Tensor]],
            Mapping[str, MultiModalFieldConfig],
        ],
286
287
288
289
290
    ) -> None:
        super().__init__(
            data,
            modality="video",
            required_fields={"video_embeds", "video_image_sizes"},
291
            fields_factory=fields_factory,
292
293
294
295
296
297
298
299
300
301
        )

    def get_frame_size(self, index: int) -> ImageSize:
        frame_size = self.get(index)["video_image_sizes"].tolist()
        return ImageSize(width=frame_size[0], height=frame_size[1])

    def get_num_frames(self, index: int) -> int:
        return len(self.get(index)["video_image_sizes"])


302
303
304
305
306
class MiniCPMVMultiModalDataParser(MultiModalDataParser):

    def _parse_image_data(
        self,
        data: Union[dict[str, torch.Tensor], ModalityData[ImageItem]],
307
    ) -> Optional[ModalityDataItems[Any, Any]]:
308
        if isinstance(data, dict):
309
310
            return MiniCPMVImageEmbeddingItems(
                data,
311
                fields_factory=_minicpmv_field_config,
312
313
            )

314
315
316
317
318
        return super()._parse_image_data(data)

    def _parse_video_data(
        self,
        data: Union[dict[str, torch.Tensor], ModalityData[VideoItem]],
319
    ) -> Optional[ModalityDataItems[Any, Any]]:
320
        if isinstance(data, dict):
321
322
            return MiniCPMVVideoEmbeddingItems(
                data,
323
                fields_factory=_minicpmv_field_config,
324
325
            )

326
327
328
329
330
331
332
333
334
335
        return super()._parse_video_data(data)


class MiniCPMVProcessingInfo(BaseProcessingInfo):
    image_pattern = "(<image>./</image>)"
    video_pattern = "(<video>./</video>)"

    def get_hf_config(self):
        return self.ctx.get_hf_config()

336
337
    def get_hf_processor(self, **kwargs: object):
        hf_processor = self.ctx.get_hf_processor(**kwargs)
338
339
340
341
342
343
344
345
346

        # NumPy arrays are considered as Iterable but not Sequence in
        # https://github.com/huggingface/transformers/blob/main/src/transformers/image_transforms.py#L428
        image_processor = hf_processor.image_processor  # type: ignore
        for attr in ("mean", "std"):
            val = getattr(image_processor, attr)
            if isinstance(val, np.ndarray):
                setattr(image_processor, attr, val.tolist())

347
348
        return hf_processor

349
350
    def get_image_processor(self, **kwargs: object):
        return self.get_hf_processor(**kwargs).image_processor
351
352
353
354
355

    def get_model_version(self):
        return get_version_by_config(self.get_hf_config())

    def get_supported_mm_limits(self) -> Mapping[str, Optional[int]]:
356
        mm_limits = {"image": None}
tc-mb's avatar
tc-mb committed
357
358
359
        if self.get_model_version() == (2,
                                        6) or self.get_model_version() == (4,
                                                                           0):
360
361
362
            mm_limits["video"] = None

        return mm_limits
363

364
365
366
367
368
369
370
371
372
373
    def get_slice_image_placeholder(
        self,
        image_size: ImageSize,
        # For MiniCPM V/O 2.6
        image_idx: int = 0,
        max_slice_nums: Optional[int] = None,
        use_image_id: bool = True,
    ) -> str:
        image_processor = self.get_image_processor()
        version = self.get_model_version()
374

375
376
        if version == (2, 0) or version == (2, 5):
            return image_processor.get_slice_image_placeholder(image_size)
377

378
379
380
381
382
383
        return image_processor.get_slice_image_placeholder(
            image_size,
            image_idx=image_idx,
            max_slice_nums=max_slice_nums,
            use_image_id=use_image_id,
        )
384

385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
    def get_sliced_grid(
        self,
        image_size: ImageSize,
        # For MiniCPM V/O 2.6
        max_slice_nums: Optional[int] = None,
    ) -> Optional[tuple[int, int]]:
        image_processor = self.get_image_processor()
        version = self.get_model_version()

        if version == (2, 0) or version == (2, 5):
            return image_processor.get_sliced_grid(image_size)

        if max_slice_nums is None:
            max_slice_nums = image_processor.max_slice_nums

        return image_processor.get_sliced_grid(
            image_size,
            max_slice_nums=max_slice_nums,
        )

405
406
407
408
409
    def get_num_image_tokens(
        self,
        image_size: ImageSize,
        max_slice_nums: Optional[int] = None,
    ) -> int:
410
411
412
        image_processor = self.get_image_processor()

        grid = self.get_sliced_grid(
413
414
415
            image_size,
            max_slice_nums=max_slice_nums,
        )
416
417
418
419
        if grid is None:
            ncols = nrows = 0
        else:
            ncols, nrows = grid
420

421
        return (ncols * nrows + 1) * image_processor.image_feature_size
422
423
424

    def get_max_image_tokens(self) -> int:
        image_size = self.get_image_size_with_most_features()
425
426
427
428
        return self.get_num_image_tokens(image_size)

    def get_image_max_slice_num(self) -> int:
        return getattr(self.get_hf_config(), "max_slice_num", 9)
429
430

    def get_image_size_with_most_features(self) -> ImageSize:
431
432
433
434
435
436
437
438
439
440
441
442
        image_size = getattr(self.get_hf_config(), "image_size", 448)
        max_slice_num = self.get_image_max_slice_num()
        return ImageSize(width=image_size, height=image_size * max_slice_num)

    def get_max_video_frame_tokens(self) -> int:
        frame_size = self.get_video_frame_size_with_most_features()

        return self.get_num_image_tokens(
            frame_size,
            max_slice_nums=self.get_video_max_slice_num(),
        )

443
444
445
446
447
448
449
450
    def get_max_video_tokens(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> int:
        num_frames = self.get_num_frames_with_most_features(seq_len, mm_counts)
        num_video_tokens_total = self.get_max_video_frame_tokens() * num_frames
        return num_video_tokens_total
451
452
453

    def get_video_max_slice_num(self) -> int:
        return 1
454

455
    def get_video_frame_size_with_most_features(self) -> ImageSize:
456
457
458
        image_size = getattr(self.get_hf_config(), "image_size", 448)
        max_slice_num = self.get_video_max_slice_num()
        return ImageSize(width=image_size, height=image_size * max_slice_num)
459

460
461
462
463
    def get_max_video_frames(self, max_tokens: int) -> int:
        num_frame_tokens = self.get_max_video_frame_tokens()
        num_frames = max_tokens // num_frame_tokens
        return num_frames
464

465
466
467
468
469
470
471
    def get_num_frames_with_most_features(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> int:
        max_images = mm_counts.get("image", 0)
        max_videos = mm_counts.get("video", 0)
472

473
        max_image_tokens = self.get_max_image_tokens() * max_images
474
475
        max_total_frames = self.get_max_video_frames(seq_len -
                                                     max_image_tokens)
476
477
        max_frames_per_video = min(max_total_frames // max(max_videos, 1),
                                   _MAX_FRAMES_PER_VIDEO)
478

479
        return max(max_frames_per_video, 1)
480
481


482
483
484
485
486
487
_I = TypeVar("_I",
             bound=MiniCPMVProcessingInfo,
             default=MiniCPMVProcessingInfo)


class MiniCPMVDummyInputsBuilder(BaseDummyInputsBuilder[_I]):
488

489
490
491
492
493
494
495
496
497
498
    def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
        num_images = mm_counts.get("image", 0)
        num_videos = mm_counts.get("video", 0)

        image_prompt_texts = self.info.image_pattern * num_images
        video_prompt_texts = self.info.video_pattern * num_videos

        return image_prompt_texts + video_prompt_texts

    def get_dummy_mm_data(
499
500
501
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
502
    ) -> MultiModalDataDict:
503
504
505
506
507
508
509
510
        num_images = mm_counts.get("image", 0)
        num_videos = mm_counts.get("video", 0)

        image_width, image_height = \
            self.info.get_image_size_with_most_features()
        video_width, video_height = \
            self.info.get_video_frame_size_with_most_features()
        num_video_frames = \
511
            self.info.get_num_frames_with_most_features(seq_len, mm_counts)
512

513
        return {
514
515
516
517
518
519
520
521
522
523
524
525
            "image":
            self._get_dummy_images(width=image_width,
                                   height=image_height,
                                   num_images=num_images),
            "video": [
                self._get_dummy_images(width=video_width,
                                       height=video_height,
                                       num_images=num_video_frames)
            ] * num_videos,
        }


526
class MiniCPMVMultiModalProcessor(BaseMultiModalProcessor[_I]):
527
528
529
530
531
532
533

    def _get_data_parser(self) -> MultiModalDataParser:
        return MiniCPMVMultiModalDataParser()

    def get_image_prompt_texts(self,
                               image_size: ImageSize,
                               image_idx: int = 0) -> str:
534
535
536
537
        return self.info.get_slice_image_placeholder(
            image_size,
            image_idx=image_idx,
        )
538
539
540

    def get_video_prompt_texts(self, image_size: ImageSize,
                               num_frames: int) -> str:
541
        return self.info.get_slice_image_placeholder(
542
543
544
545
546
            image_size=image_size,
            image_idx=0,
            max_slice_nums=self.info.get_video_max_slice_num(),
            use_image_id=False,
        ) * num_frames
547

548
549
550
551
    def process_images(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
552
        tok_kwargs: Mapping[str, object],
553
    ) -> Mapping[str, NestedTensors]:
554
555
556
557
558
        if (images := mm_data.get("images")) is None:
            return {}

        parsed_images = (self._get_data_parser().parse_mm_data({
            "image": images
559
560
        }).get_items("image",
                     (MiniCPMVImageEmbeddingItems, ImageProcessorItems)))
561

562
563
564
565
566
567
568
        if isinstance(parsed_images, MiniCPMVImageEmbeddingItems):
            image_inputs = {}
        else:
            image_inputs = self._base_call_hf_processor(
                prompts=[self.info.image_pattern] * len(parsed_images),
                mm_data={"images": [[image] for image in parsed_images]},
                mm_kwargs=mm_kwargs,
569
                tok_kwargs=tok_kwargs,
570
571
572
573
574
575
576
577
                out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
            )

        tokenizer = self.info.get_tokenizer()
        unk_token_id = tokenizer.get_vocab()["<unk>"]
        image_inputs["image_token_id"] = torch.tensor(unk_token_id)

        return image_inputs
578

579
580
581
582
    def process_videos(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
583
        tok_kwargs: Mapping[str, object],
584
    ) -> Mapping[str, NestedTensors]:
585
586
587
588
589
        if (videos := mm_data.get("videos")) is None:
            return {}

        parsed_videos = (self._get_data_parser().parse_mm_data({
            "video": videos
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
        }).get_items("video",
                     (MiniCPMVVideoEmbeddingItems, VideoProcessorItems)))

        if isinstance(parsed_videos, MiniCPMVVideoEmbeddingItems):
            video_inputs = {}
        else:
            video_inputs = self._base_call_hf_processor(
                prompts=[
                    self.info.image_pattern * len(video)
                    for video in parsed_videos
                ],
                mm_data={"images": list(parsed_videos)},
                mm_kwargs={
                    **mm_kwargs,
                    "max_slice_nums":
                    self.info.get_video_max_slice_num(),
                },
607
                tok_kwargs=tok_kwargs,
608
609
610
                out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
            )

611
612
        video_inputs = {f"video_{k}": v for k, v in video_inputs.items()}

613
        tokenizer = self.info.get_tokenizer()
614
615
        unk_token_id = tokenizer.get_vocab()["<unk>"]
        video_inputs["video_token_id"] = torch.tensor(unk_token_id)
616

617
        return video_inputs
618

619
620
621
622
    def process_mm_inputs(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
623
        tok_kwargs: Mapping[str, object],
624
    ) -> Mapping[str, NestedTensors]:
625
        return {
626
627
            **self.process_images(mm_data, mm_kwargs, tok_kwargs),
            **self.process_videos(mm_data, mm_kwargs, tok_kwargs),
628
        }
629

630
    def _base_call_hf_processor(
631
        self,
632
633
        prompts: list[str],
        mm_data: Mapping[str, Sequence[object]],
634
        mm_kwargs: Mapping[str, object],
635
        tok_kwargs: Mapping[str, object],
636
637
        *,
        out_keys: set[str],
638
    ) -> dict[str, NestedTensors]:
639
        # This processor supports zipping prompt and mm_data together
tc-mb's avatar
tc-mb committed
640
641
        if self.info.get_model_version() == (
                2, 6) or self.info.get_model_version() == (4, 0):
642
643
644
645
            inputs = super()._call_hf_processor(
                prompt=prompts,  # type: ignore
                mm_data=mm_data,
                mm_kwargs=mm_kwargs,
646
                tok_kwargs=tok_kwargs,
647
648
649
650
651
652
653
654
655
656
657
658
            )
        else:
            inputs = defaultdict[str, list[torch.Tensor]](list)

            for i, prompt in enumerate(prompts):
                inputs_one = super()._call_hf_processor(
                    prompt=prompt,
                    mm_data={
                        k: v[i]
                        for k, v in mm_data.items()
                    },
                    mm_kwargs=mm_kwargs,
659
                    tok_kwargs=tok_kwargs,
660
661
662
663
664
665
666
                )

                for k, v in inputs_one.items():
                    assert len(v) == 1, (k, len(v))
                    inputs[k].append(v[0])

        return {k: inputs[k] for k in out_keys}
667
668
669
670
671
672

    def _call_hf_processor(
        self,
        prompt: str,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
673
        tok_kwargs: Mapping[str, object],
674
675
    ) -> BatchFeature:
        tokenizer = self.info.get_tokenizer()
676

677
678
        input_ids = torch.tensor([tokenizer.encode(prompt, **tok_kwargs)])
        mm_inputs = self.process_mm_inputs(mm_data, mm_kwargs, tok_kwargs)
679
680

        return BatchFeature({
681
            "input_ids": input_ids,
682
            **mm_inputs,
683
        })
684

685
    def _hf_processor_applies_updates(
686
687
688
689
        self,
        prompt_text: str,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
690
        tokenization_kwargs: Mapping[str, object],
691
692
693
    ) -> bool:
        return False

694
    def _get_prompt_updates(
695
696
697
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
698
        out_mm_kwargs: MultiModalKwargsItems,
699
    ) -> Sequence[PromptUpdate]:
tc-mb's avatar
tc-mb committed
700
701
702
703
704
705
706
707
708
709
710
711
        placeholders = [("image", self.info.image_pattern),
                        ("video", self.info.video_pattern)]

        # hard code for inconsistency of encode-decode image_pattern
        additional_placeholders = []
        tokenizer = self.info.get_tokenizer()
        for modality, pattern in placeholders:
            sub_pattern = tokenizer.decode(
                tokenizer.encode(pattern, add_special_tokens=False))
            if sub_pattern != pattern:
                additional_placeholders.append((modality, sub_pattern))
        placeholders += additional_placeholders
712

713
714
715
716
717
718
        def get_image_replacement(item_idx: int):
            images = mm_items.get_items(
                "image", (MiniCPMVImageEmbeddingItems, ImageProcessorItems))

            image_size = images.get_image_size(item_idx)

719
720
721
722
            return PromptUpdateDetails.select_text(
                self.get_image_prompt_texts(image_size, item_idx),
                "<unk>",
            )
723
724
725
726
727
728
729
730

        def get_video_replacement(item_idx: int):
            videos = mm_items.get_items(
                "video", (MiniCPMVVideoEmbeddingItems, VideoProcessorItems))

            frame_size = videos.get_frame_size(item_idx)
            num_frames = videos.get_num_frames(item_idx)

731
732
733
734
            return PromptUpdateDetails.select_text(
                self.get_video_prompt_texts(frame_size, num_frames),
                "<unk>",
            )
735
736
737
738
739

        get_replacement = {
            "image": get_image_replacement,
            "video": get_video_replacement,
        }
740
741
742

        return [
            PromptReplacement(modality=modality,
tc-mb's avatar
tc-mb committed
743
                              target=pattern,
744
                              replacement=get_replacement[modality])
tc-mb's avatar
tc-mb committed
745
            for modality, pattern in placeholders
746
        ]
747

748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
    def _recompute_cached_prompt_update(
        self,
        cached_update: ResolvedPromptUpdate,
        new_item_idx: int,
    ) -> ResolvedPromptUpdate:
        new_update = super()._recompute_cached_prompt_update(
            cached_update,
            new_item_idx,
        )

        if cached_update.modality == "image":
            tokenizer = self.info.get_tokenizer()
            image_processor = self.info.get_image_processor()
            version = self.info.get_model_version()

            text = _seq2text(tokenizer, cached_update.content.full)
            prev_item_idx = cached_update.item_idx

            if version == (2, 0) or version == (2, 5):
                im_start = image_processor.im_start_token
                im_end = image_processor.im_end_token
            else:
                im_start = image_processor.im_id_start
                im_end = image_processor.im_id_end

            new_update = new_update.with_content(
                PromptUpdateDetails.select_text(
                    text.replace(
                        f"{im_start}{prev_item_idx}{im_end}",
                        f"{im_start}{new_item_idx}{im_end}",
                        1,
                    ),
                    "<unk>",
                ))

        return new_update

785
786
    def _get_mm_fields_config(
        self,
787
        hf_inputs: BatchFeature,
788
789
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, MultiModalFieldConfig]:
790
        return _minicpmv_field_config(hf_inputs)
791

792
793

class MiniCPMVBaseModel(nn.Module, SupportsMultiModal, SupportsPP):
Jee Jee Li's avatar
Jee Jee Li committed
794
795
796
797
    """
    The abstract class of MiniCPMV can only be inherited, but cannot be
    instantiated.
    """
798

799
800
801
802
803
804
805
806
807
    @classmethod
    def get_placeholder_str(cls, modality: str, i: int) -> Optional[str]:
        if modality.startswith("image"):
            return "(<image>./</image>)"
        if modality.startswith("video"):
            return "(<video>./</video>)"

        raise ValueError("Only image or video modality is supported")

808
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
809
810
811
        config = vllm_config.model_config.hf_config
        multimodal_config = vllm_config.model_config.multimodal_config
        quant_config = vllm_config.quant_config
812
        super().__init__()
813
814
815
816
        # All MiniCPM-V models disable `tie_word_embeddings` but
        # `PretrainedConfig.tie_word_embeddings` defaults to True; we cannot
        # check `tie_word_embeddings` until vLLM integrate MiniCPM-V model
        # and config class
817
818
        self.config = config
        self.multimodal_config = multimodal_config
819
        self.use_data_parallel = multimodal_config.mm_encoder_tp_mode == "data"
820

821
        self.version = get_version_by_config(self.config)
822
823
824
825
826
        self.llm = self.init_llm(vllm_config=vllm_config,
                                 prefix=maybe_prefix(prefix, "llm"))
        self.vpm = self.init_vision_module(config,
                                           quant_config,
                                           prefix=maybe_prefix(prefix, "vpm"))
Jee Jee Li's avatar
Jee Jee Li committed
827
828
        self.vision_dim = (self.vpm.embed_dim if self.version == (2, 0) else
                           self.vpm.embeddings.embed_dim)
Alphi's avatar
Alphi committed
829
        self.embed_dim = self.config.hidden_size
830

831
832
833
        self.resampler = self.init_resampler(self.embed_dim,
                                             self.vision_dim,
                                             quant_config=quant_config,
834
835
                                             prefix=maybe_prefix(
                                                 prefix, "resampler"))
836

837
        self.mm_token_ids = set[int]()
838
839
840
        self.make_empty_intermediate_tensors = (
            self.llm.make_empty_intermediate_tensors)

841
    def _parse_and_validate_vision_input(
Jee Jee Li's avatar
Jee Jee Li committed
842
        self,
843
        modality: str,
Jee Jee Li's avatar
Jee Jee Li committed
844
        **kwargs: object,
845
    ) -> Optional[MiniCPMVImageInputs]:
846
847
        pixel_values = kwargs.pop("pixel_values", None)
        image_embeds = kwargs.pop("image_embeds", None)
848

849
        if pixel_values is None and image_embeds is None:
850
851
            return None

852
853
854
855
856
857
858
859
860
861
862
863
        image_token_id = kwargs.pop("image_token_id")
        if image_token_id is not None:
            assert isinstance(image_token_id, torch.Tensor)
            self.mm_token_ids.add(image_token_id.flatten().unique().item())

        if image_embeds is not None:
            if not isinstance(image_embeds, (torch.Tensor, list)):
                raise ValueError(
                    f"Incorrect type of image_embeds for {modality=}. "
                    f"Got type: {type(image_embeds)}")

            image_embeds_flat = flatten_bn(image_embeds)
864

865
            return MiniCPMVImageEmbeddingInputs(
866
                type="image_embeds",
867
                image_embeds=image_embeds_flat,
868
            )
869

870
871
872
873
        if not isinstance(pixel_values, (torch.Tensor, list)):
            raise ValueError(
                f"Incorrect type of pixel_values for {modality=}. "
                f"Got type: {type(pixel_values)}")
874

875
876
877
878
879
880
881
882
883
884
        tgt_sizes = kwargs.pop("tgt_sizes")
        if not isinstance(tgt_sizes, (torch.Tensor, list)):
            raise ValueError(f"Incorrect type of tgt_sizes for {modality=}. "
                             f"Got type: {type(tgt_sizes)}")

        num_slices = [[len(p) for p in ps] for ps in pixel_values]
        num_slices_flat = flatten_bn(torch.tensor(num_slices))

        pixel_values_flat = flatten_bn(flatten_2d_lists(pixel_values))
        tgt_sizes_flat = flatten_bn(flatten_2d_lists(tgt_sizes), concat=True)
885

886
        return MiniCPMVImagePixelInputs(
887
888
            type="pixel_values",
            pixel_values=pixel_values_flat,
889
890
            tgt_sizes=tgt_sizes_flat,
            num_slices=num_slices_flat,
Jee Jee Li's avatar
Jee Jee Li committed
891
        )
892

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    def _parse_and_validate_multimodal_inputs(self, **kwargs: object) -> dict:
        modalities = {}

        # Preserve the order of modalities if there are multiple of them
        # from the order of kwargs.
        for input_key in kwargs:
            if input_key in ("pixel_values",
                             "image_embeds") and "images" not in modalities:
                modalities["images"] = self._parse_and_validate_vision_input(
                    "images", **kwargs)
            if input_key in ("video_pixel_values",
                             "video_embeds") and "videos" not in modalities:

                def _image_key(video_key: str):
                    if video_key == "video_token_id":
                        return "image_token_id"

                    return video_key.removeprefix("video_")

                modalities["videos"] = self._parse_and_validate_vision_input(
                    "videos", **{
                        _image_key(k): v
                        for k, v in kwargs.items()
                    })

        return modalities

    def _process_vision_input(
        self,
        image_input: MiniCPMVImageInputs,
    ) -> Union[torch.Tensor, list[torch.Tensor], tuple[torch.Tensor, ...]]:
        if image_input["type"] == "image_embeds":
            return image_input["image_embeds"]

        image_features_flat = self.get_vision_hidden_states(image_input)

929
930
931
932
933
        num_slices = image_input["num_slices"]
        return [
            e.flatten(0, 1)
            for e in image_features_flat.split(num_slices.tolist())
        ]
934
935
936
937
938
939
940
941
942
943
944
945

    def _process_multimodal_inputs(self, modalities: dict):
        # The result multimodal_embeddings is tuple of tensors, with each
        # tensor correspoending to a multimodal data item (image or video).
        multimodal_embeddings: tuple[torch.Tensor, ...] = ()

        # NOTE: It is important to iterate over the keys in this dictionary
        # to preserve the order of the modalities.
        for modality in modalities:
            if modality == "images":
                image_input = modalities["images"]
                image_features = self._process_vision_input(image_input)
946
                multimodal_embeddings += tuple(image_features)
947
948
949
            if modality == "videos":
                video_input = modalities["videos"]
                video_features = self._process_vision_input(video_input)
950
                multimodal_embeddings += tuple(video_features)
951
952
953

        return multimodal_embeddings

954
955
956
    def get_language_model(self) -> torch.nn.Module:
        return self.llm

957
958
    def get_multimodal_embeddings(self,
                                  **kwargs: object) -> MultiModalEmbeddings:
959
960
        modalities = self._parse_and_validate_multimodal_inputs(**kwargs)
        if not modalities:
961
            return []
962
963
964
965
966
967
968
969
970

        return self._process_multimodal_inputs(modalities)

    def get_input_embeddings(
        self,
        input_ids: torch.Tensor,
        multimodal_embeddings: Optional[MultiModalEmbeddings] = None,
    ) -> torch.Tensor:
        inputs_embeds = self.llm.get_input_embeddings(input_ids)
971
972
        if multimodal_embeddings is not None \
            and len(multimodal_embeddings) != 0:
973
974
975
976
            assert len(self.mm_token_ids) > 0
            inputs_embeds = merge_multimodal_embeddings(
                input_ids,
                inputs_embeds,
977
                multimodal_embeddings,
978
979
980
                list(self.mm_token_ids),
            )
        return inputs_embeds
981

982
983
984
985
986
    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors] = None,
987
        inputs_embeds: Optional[torch.Tensor] = None,
Jee Jee Li's avatar
Jee Jee Li committed
988
989
        **kwargs: Any,
    ) -> torch.Tensor:
990
        if intermediate_tensors is not None:
991
992
993
994
995
996
997
            inputs_embeds = None

        # NOTE: In v1, inputs_embeds is always generated at model runner from
        # `get_multimodal_embeddings` and `get_input_embeddings`, this
        # condition is only for v0 compatibility.
        elif inputs_embeds is None:
            vision_embeddings = self.get_multimodal_embeddings(**kwargs)
Jee Jee Li's avatar
Jee Jee Li committed
998

999
1000
1001
            inputs_embeds = self.get_input_embeddings(input_ids,
                                                      vision_embeddings)
            input_ids = None
1002

1003
        hidden_states = self.llm.model(
1004
            input_ids=input_ids,
Jee Jee Li's avatar
Jee Jee Li committed
1005
1006
            positions=positions,
            intermediate_tensors=intermediate_tensors,
1007
            inputs_embeds=inputs_embeds,
Jee Jee Li's avatar
Jee Jee Li committed
1008
        )
1009
        return hidden_states
1010

1011
1012
1013
1014
1015
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[torch.Tensor]:
1016
        return self.llm.compute_logits(hidden_states, sampling_metadata)
1017

1018
1019
    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
1020
1021
        loader = AutoWeightsLoader(self)
        return loader.load_weights(weights)
Jee Jee Li's avatar
Jee Jee Li committed
1022

1023
1024
1025
1026
1027
1028
1029
1030
    def get_mm_mapping(self) -> MultiModelKeys:
        """
        Get the module prefix in multimodal models
        """
        return MultiModelKeys.from_string_field(language_model="llm",
                                                connector="resampler",
                                                tower_model="vpm")

Jee Jee Li's avatar
Jee Jee Li committed
1031
1032
    def init_llm(
        self,
1033
        vllm_config: VllmConfig,
1034
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1035
1036
1037
    ) -> nn.Module:
        raise NotImplementedError

1038
1039
1040
1041
    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig],
1042
        prefix: str = "",
1043
    ) -> nn.Module:
Jee Jee Li's avatar
Jee Jee Li committed
1044
1045
        raise NotImplementedError

1046
1047
1048
1049
1050
    def init_resampler(self,
                       embed_dim: int,
                       vision_dim: int,
                       quant_config: Optional[QuantizationConfig] = None,
                       prefix: str = "") -> nn.Module:
Jee Jee Li's avatar
Jee Jee Li committed
1051
1052
        raise NotImplementedError

1053
1054
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
Jee Jee Li's avatar
Jee Jee Li committed
1055
1056
1057
        raise NotImplementedError


1058
class MiniCPMV2_0(MiniCPMVBaseModel):
Jee Jee Li's avatar
Jee Jee Li committed
1059

1060
1061
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1062
1063
1064
1065
        assert self.version == (2, 0)

    def init_llm(
        self,
1066
        vllm_config: VllmConfig,
1067
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1068
    ) -> nn.Module:
1069
        return MiniCPMForCausalLM(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1070

1071
1072
1073
1074
    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig],
1075
        prefix: str = "",
1076
    ) -> nn.Module:
1077
        # TODO: refactor vision model through timm wrapper from transformers
Jee Jee Li's avatar
Jee Jee Li committed
1078
1079
1080
1081
        try:
            import timm
        except ImportError:
            raise ImportError("Please install timm==0.9.10") from ImportError
1082

Jee Jee Li's avatar
Jee Jee Li committed
1083
1084
1085
1086
1087
1088
1089
1090
1091
        with set_default_torch_dtype(torch.float16):
            model = timm.create_model(
                "vit_so400m_patch14_siglip_384.webli",
                pretrained=False,
                num_classes=0,
                dynamic_img_size=True,
                dynamic_img_pad=True,
            )

1092
1093
        model = model.to(dtype=torch.get_default_dtype())

Jee Jee Li's avatar
Jee Jee Li committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
        if (isinstance(model, timm.models.VisionTransformer)
                and model.attn_pool is not None):
            model.attn_pool = torch.nn.Identity()

        if self.config.drop_vision_last_layer:
            model.blocks = model.blocks[:-1]

        return model

1103
1104
1105
1106
1107
    def init_resampler(self,
                       embed_dim: int,
                       vision_dim: int,
                       quant_config: Optional[QuantizationConfig] = None,
                       prefix: str = "") -> nn.Module:
Jee Jee Li's avatar
Jee Jee Li committed
1108
        with set_default_torch_dtype(torch.float16):
1109
1110
1111
1112
1113
1114
1115
1116
1117
            resampler = Resampler2(embed_dim=embed_dim,
                                   num_heads=embed_dim // 128,
                                   grid_size=int(
                                       math.sqrt(self.config.query_num)),
                                   kv_dim=vision_dim,
                                   adaptive=False,
                                   do_post_projection=True,
                                   quant_config=quant_config,
                                   prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1118

1119
1120
        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())
Jee Jee Li's avatar
Jee Jee Li committed
1121

1122
1123
1124
1125
1126
1127
1128
1129
1130
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        pixel_values = data["pixel_values"]

        P_h, P_w = self.vpm.patch_embed.patch_size
        dtype: torch.dtype = self.vpm.pos_embed.data.dtype
        num_prefix_tokens = getattr(self.vpm, "num_prefix_tokens", 0)

        res = list[torch.Tensor]()
Jee Jee Li's avatar
Jee Jee Li committed
1131
1132
        for pixel_value in pixel_values:
            H, W = pixel_value[0].shape[-2:]
1133
            tgt_size = (math.ceil(H / P_h), math.ceil(W / P_w))
Jee Jee Li's avatar
Jee Jee Li committed
1134
1135
1136
            vision_embedding = self.vpm.forward_features(
                pixel_value.unsqueeze(0).type(dtype))

1137
1138
1139
            if num_prefix_tokens > 0:
                vision_embedding = vision_embedding[:, num_prefix_tokens:]
            res.append(self.resampler(vision_embedding, tgt_size))
Jee Jee Li's avatar
Jee Jee Li committed
1140

1141
        return torch.vstack(res)
Jee Jee Li's avatar
Jee Jee Li committed
1142
1143


1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
class MiniCPMV2_5(MiniCPMVBaseModel, SupportsLoRA):
    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }
Jee Jee Li's avatar
Jee Jee Li committed
1156

1157
1158
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1159
1160
1161
1162
        assert self.version == (2, 5)

    def init_llm(
        self,
1163
        vllm_config: VllmConfig,
1164
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1165
    ) -> nn.Module:
1166
        return LlamaForCausalLM(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1167

1168
1169
1170
1171
    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig],
1172
        prefix: str = "",
1173
1174
    ) -> nn.Module:
        model = Idefics2VisionTransformer(config.vision_config,
1175
1176
                                          quant_config=quant_config,
                                          prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1177
1178
1179
1180
        if self.config.drop_vision_last_layer:
            model.encoder.layers = model.encoder.layers[:-1]
        return model

1181
1182
1183
1184
1185
    def init_resampler(self,
                       embed_dim: int,
                       vision_dim: int,
                       quant_config: Optional[QuantizationConfig] = None,
                       prefix: str = "") -> nn.Module:
Jee Jee Li's avatar
Jee Jee Li committed
1186
        with set_default_torch_dtype(torch.float16):
1187
1188
1189
1190
1191
1192
            resampler = Resampler2_5(num_queries=self.config.query_num,
                                     embed_dim=embed_dim,
                                     num_heads=embed_dim // 128,
                                     kv_dim=vision_dim,
                                     quant_config=quant_config,
                                     prefix=prefix)
1193

1194
1195
        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())
Jee Jee Li's avatar
Jee Jee Li committed
1196

1197
1198
1199
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        pixel_values = data["pixel_values"]
Jee Jee Li's avatar
Jee Jee Li committed
1200
1201
        tgt_sizes = data["tgt_sizes"]

1202
1203
1204
1205
1206
        B = len(pixel_values)
        P = pixel_values[0].shape[-2]
        L = max(item.shape[-1] for item in pixel_values)
        device = pixel_values[0].device
        dtype = pixel_values[0].dtype
Jee Jee Li's avatar
Jee Jee Li committed
1207

1208
1209
1210
1211
1212
1213
        all_pixel_values = torch.zeros((B, 3, P, L),
                                       dtype=dtype,
                                       device=device)
        for i, pixel_values_item in enumerate(pixel_values):
            L_item = pixel_values_item.shape[-1]
            all_pixel_values[i, ..., :L_item] = pixel_values_item
Jee Jee Li's avatar
Jee Jee Li committed
1214

1215
1216
1217
        num_patches = tgt_sizes.prod(-1)
        max_patches = num_patches.max().item()
        assert isinstance(max_patches, int)
Jee Jee Li's avatar
Jee Jee Li committed
1218

1219
        patch_attn_mask = torch.zeros((B, max_patches),
Jee Jee Li's avatar
Jee Jee Li committed
1220
1221
                                      dtype=torch.bool,
                                      device=device)
1222
1223
        for i, num_patches_item in enumerate(num_patches):
            patch_attn_mask[i, :num_patches_item] = True
Jee Jee Li's avatar
Jee Jee Li committed
1224

1225
1226
1227
1228
1229
1230
1231
        vision_embedding = self.vpm(
            all_pixel_values,
            patch_attention_mask=patch_attn_mask.unsqueeze(1),
            tgt_sizes=None,
        )

        return self.resampler(vision_embedding, tgt_sizes)
Jee Jee Li's avatar
Jee Jee Li committed
1232
1233


1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
class MiniCPMV2_6(MiniCPMVBaseModel, SupportsLoRA):
    packed_modules_mapping = {
        "qkv_proj": [
            "q_proj",
            "k_proj",
            "v_proj",
        ],
        "gate_up_proj": [
            "gate_proj",
            "up_proj",
        ],
    }
Jee Jee Li's avatar
Jee Jee Li committed
1246

1247
1248
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__(vllm_config=vllm_config, prefix=prefix)
1249
        assert self.version == (2, 6)
Jee Jee Li's avatar
Jee Jee Li committed
1250
1251
1252

    def init_llm(
        self,
1253
        vllm_config: VllmConfig,
1254
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1255
    ) -> nn.Module:
1256
        return Qwen2ForCausalLM(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1257

1258
1259
1260
    def init_vision_module(
        self,
        config: PretrainedConfig,
1261
        quant_config: Optional[QuantizationConfig] = None,
1262
        prefix: str = "",
1263
1264
    ) -> nn.Module:
        model = Idefics2VisionTransformer(config.vision_config,
1265
1266
                                          quant_config=quant_config,
                                          prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1267
1268
1269
1270
        if self.config.drop_vision_last_layer:
            model.encoder.layers = model.encoder.layers[:-1]
        return model

1271
1272
1273
1274
1275
    def init_resampler(self,
                       embed_dim: int,
                       vision_dim: int,
                       quant_config: Optional[QuantizationConfig] = None,
                       prefix: str = "") -> nn.Module:
Jee Jee Li's avatar
Jee Jee Li committed
1276
        with set_default_torch_dtype(torch.float16):
1277
            # The resampler in 2.6 remains consistent with the one in 2.5.
1278
1279
1280
1281
1282
1283
            resampler = Resampler2_5(num_queries=self.config.query_num,
                                     embed_dim=embed_dim,
                                     num_heads=embed_dim // 128,
                                     kv_dim=vision_dim,
                                     quant_config=quant_config,
                                     prefix=prefix)
1284

1285
1286
        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())
Jee Jee Li's avatar
Jee Jee Li committed
1287

1288
1289
1290
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        pixel_values = data["pixel_values"]
Jee Jee Li's avatar
Jee Jee Li committed
1291
1292
        tgt_sizes = data["tgt_sizes"]

1293
1294
1295
1296
1297
        B = len(pixel_values)
        P = pixel_values[0].shape[-2]
        L = max(item.shape[-1] for item in pixel_values)
        device = pixel_values[0].device
        dtype = pixel_values[0].dtype
Jee Jee Li's avatar
Jee Jee Li committed
1298

1299
1300
1301
1302
1303
1304
        all_pixel_values = torch.zeros((B, 3, P, L),
                                       dtype=dtype,
                                       device=device)
        for i, pixel_values_item in enumerate(pixel_values):
            L_item = pixel_values_item.shape[-1]
            all_pixel_values[i, ..., :L_item] = pixel_values_item
Jee Jee Li's avatar
Jee Jee Li committed
1305

1306
1307
1308
        num_patches = tgt_sizes.prod(-1)
        max_patches = num_patches.max().item()
        assert isinstance(max_patches, int)
Jee Jee Li's avatar
Jee Jee Li committed
1309

1310
        patch_attn_mask = torch.zeros((B, max_patches),
Jee Jee Li's avatar
Jee Jee Li committed
1311
1312
                                      dtype=torch.bool,
                                      device=device)
1313
1314
1315
        for i, num_patches_item in enumerate(num_patches):
            patch_attn_mask[i, :num_patches_item] = True

Jee Jee Li's avatar
Jee Jee Li committed
1316
        vision_embedding = self.vpm(
1317
1318
            all_pixel_values,
            patch_attention_mask=patch_attn_mask.unsqueeze(1),
Jee Jee Li's avatar
Jee Jee Li committed
1319
            tgt_sizes=tgt_sizes,
1320
        )
Jee Jee Li's avatar
Jee Jee Li committed
1321
1322
1323

        return self.resampler(vision_embedding, tgt_sizes)

tc-mb's avatar
tc-mb committed
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(self,
                                   skip_prefixes=["apm.", "audio", "tts"])
        return loader.load_weights(weights)


class MiniCPMV4_0(MiniCPMVBaseModel, SupportsLoRA):
    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__(vllm_config=vllm_config, prefix=prefix)
        assert self.version == (4, 0)

    def _maybe_ignore_quant_config(self, quant_config: QuantizationConfig):
        if isinstance(quant_config, (AWQConfig, AWQMarlinConfig)):
            return None
        return quant_config

    def init_llm(
        self,
        vllm_config: VllmConfig,
        prefix: str = "",
    ) -> nn.Module:
        return LlamaForCausalLM(vllm_config=vllm_config, prefix=prefix)

    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ) -> nn.Module:
        quant_config = self._maybe_ignore_quant_config(quant_config)
1367
1368
1369
1370
1371
        model = Idefics2VisionTransformer(
            config.vision_config,
            quant_config=quant_config,
            prefix=prefix,
            use_data_parallel=self.use_data_parallel)
tc-mb's avatar
tc-mb committed
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
        if self.config.drop_vision_last_layer:
            model.encoder.layers = model.encoder.layers[:-1]
        return model

    def init_resampler(
        self,
        embed_dim: int,
        vision_dim: int,
        quant_config: Optional[QuantizationConfig] = None,
        prefix: str = "",
    ) -> nn.Module:
        quant_config = self._maybe_ignore_quant_config(quant_config)
        with set_default_torch_dtype(torch.float16):
            # The resampler in 4.0 remains consistent with the one in 2.5/2.6.
            resampler = Resampler2_5(num_queries=self.config.query_num,
                                     embed_dim=embed_dim,
                                     num_heads=embed_dim // 128,
                                     kv_dim=vision_dim,
                                     quant_config=quant_config,
                                     prefix=prefix)

        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())

    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        pixel_values = data["pixel_values"]
        tgt_sizes = data["tgt_sizes"]

        B = len(pixel_values)
        P = pixel_values[0].shape[-2]
        L = max(item.shape[-1] for item in pixel_values)
        device = pixel_values[0].device
        dtype = pixel_values[0].dtype

        all_pixel_values = torch.zeros((B, 3, P, L),
                                       dtype=dtype,
                                       device=device)
        for i, pixel_values_item in enumerate(pixel_values):
            L_item = pixel_values_item.shape[-1]
            all_pixel_values[i, ..., :L_item] = pixel_values_item

        num_patches = tgt_sizes.prod(-1)
        max_patches = num_patches.max().item()
        assert isinstance(max_patches, int)

        patch_attn_mask = torch.zeros((B, max_patches),
                                      dtype=torch.bool,
                                      device=device)
        for i, num_patches_item in enumerate(num_patches):
            patch_attn_mask[i, :num_patches_item] = True

        vision_embedding = self.vpm(
            all_pixel_values,
            patch_attention_mask=patch_attn_mask.unsqueeze(1),
            tgt_sizes=tgt_sizes,
        )

        return self.resampler(vision_embedding, tgt_sizes)

    def load_weights(self, weights: Iterable[tuple[str,
                                                   torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(self,
                                   skip_prefixes=["apm.", "audio", "tts"])
        return loader.load_weights(weights)

Jee Jee Li's avatar
Jee Jee Li committed
1438

1439
1440
1441
_SUPPORT_VERSION = {
    (2, 0): MiniCPMV2_0,
    (2, 5): MiniCPMV2_5,
1442
    (2, 6): MiniCPMV2_6,
tc-mb's avatar
tc-mb committed
1443
    (4, 0): MiniCPMV4_0,
1444
1445
1446
}


1447
1448
1449
1450
1451
@MULTIMODAL_REGISTRY.register_processor(
    MiniCPMVMultiModalProcessor,
    info=MiniCPMVProcessingInfo,
    dummy_inputs=MiniCPMVDummyInputsBuilder)
class MiniCPMV(MiniCPMVBaseModel, SupportsMultiModal, SupportsLoRA):
Jee Jee Li's avatar
Jee Jee Li committed
1452
1453
1454
1455
1456
    """
    Different versions of MiniCPMV use different visual encoders and LLMs,
    which is not conducive to the current integration logic of LoRA and
    bitsandbytes in vLLM. Therefore, it is necessary to separate them.
    """
1457

1458
    def __new__(cls, *, vllm_config: VllmConfig, prefix: str = ""):
1459
        config = vllm_config.model_config.hf_config
Jee Jee Li's avatar
Jee Jee Li committed
1460
1461
1462
1463
1464
1465
1466
1467
1468
        if not hasattr(config, "version"):
            if config.hidden_size == 2304 and config.query_num == 64:
                version = (2, 0)
            else:
                version = (2, 5)
        else:
            version = str(config.version).split(".")
            version = tuple([int(x) for x in version])
        # Dispatch class based on version
1469
1470
        instance_cls = _SUPPORT_VERSION.get(version)
        if instance_cls is None:
tc-mb's avatar
tc-mb committed
1471
1472
1473
1474
            supported_versions = ", ".join(
                [f"{v[0]}.{v[1]}" for v in sorted(_SUPPORT_VERSION.keys())])
            raise ValueError(f"Currently, MiniCPMV only supports versions "
                             f"{supported_versions}. Got version: {version}")
1475
1476
1477
1478
1479
1480
1481

        # quant_config references base class members,
        # so update values before init is called
        cls.packed_modules_mapping.update(instance_cls.packed_modules_mapping)
        cls.embedding_modules.update(instance_cls.embedding_modules)
        cls.embedding_padding_modules += instance_cls.embedding_padding_modules
        return instance_cls(vllm_config=vllm_config, prefix=prefix)