minicpmv.py 50.8 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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
24
"""Inference-only MiniCPM-V model compatible with HuggingFace weights."""
25
26
import math
import re
27
from collections import defaultdict
28
from collections.abc import Iterable, Mapping, Sequence
29
from functools import cached_property, partial
30
31
from typing import (Any, Callable, Dict, List, Literal, Optional, Set, Tuple,
                    TypedDict, Union)
32

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

41
from vllm.config import VllmConfig
42
from vllm.model_executor.layers.quantization import QuantizationConfig
43
from vllm.model_executor.layers.resampler import (BaseResampler, Resampler2,
44
                                                  get_2d_sincos_pos_embed)
Joe Runde's avatar
Joe Runde committed
45
from vllm.model_executor.layers.sampler import SamplerOutput, get_sampler
Jee Jee Li's avatar
Jee Jee Li committed
46
from vllm.model_executor.model_loader.utils import set_default_torch_dtype
47
48
from vllm.model_executor.models.llama import LlamaForCausalLM
from vllm.model_executor.models.minicpm import MiniCPMForCausalLM
49
from vllm.model_executor.models.module_mapping import MultiModelKeys
50
from vllm.model_executor.models.qwen2 import Qwen2ForCausalLM
51
from vllm.model_executor.sampling_metadata import SamplingMetadata
52
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalKwargs
53
from vllm.multimodal.inputs import (MultiModalDataDict, MultiModalFieldConfig,
54
55
56
57
                                    MultiModalInputs, NestedTensors,
                                    PlaceholderRange)
from vllm.multimodal.parse import (DictEmbeddingItems, ImageItem,
                                   ImageProcessorItems, ImageSize,
58
59
                                   ModalityData, ModalityDataItems,
                                   MultiModalDataItems, MultiModalDataParser,
60
                                   VideoItem, VideoProcessorItems)
61
from vllm.multimodal.processing import (BaseMultiModalProcessor,
62
63
                                        BaseProcessingInfo, PromptReplacement,
                                        PromptUpdate)
64
from vllm.multimodal.profiling import BaseDummyInputsBuilder, ProcessorInputs
65
from vllm.platforms import current_platform
66
from vllm.sequence import IntermediateTensors
67
from vllm.utils import flatten_2d_lists
68

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

74
CPU_DEVICE = torch.device("cpu")
75

76
RawImageType = Union[Image.Image, torch.Tensor]
77
78


Jee Jee Li's avatar
Jee Jee Li committed
79
class MiniCPMVImagePixelInputs(TypedDict):
80
    type: Literal["pixel_values"]
81
    pixel_values: list[torch.Tensor]
Jee Jee Li's avatar
Jee Jee Li committed
82
    """
83
    Shape: `(batch_size * num_images * num_slices, num_channels, height, width)`
Jee Jee Li's avatar
Jee Jee Li committed
84
85
86
87
88
89
90

    Note that the image size may vary, so we pass it as a list
    instead of a batched tensor.
    """

    image_bounds: torch.Tensor
    """
91
    Shape: `(batch_size * num_images * num_slices, 2)`
Jee Jee Li's avatar
Jee Jee Li committed
92
93
94
95
96
97

    This should be in `(start, stop)` format.
    """

    tgt_sizes: torch.Tensor
    """
98
    Shape: `(batch_size * num_images * num_slices, 2)`
Jee Jee Li's avatar
Jee Jee Li committed
99
100
101
102
103

    This should be in `(height, width)` format.
    """


104
105
class MiniCPMVImageEmbeddingInputs(TypedDict):
    type: Literal["image_embeds"]
106
    image_embeds: torch.Tensor
107
    """
108
109
    Shape: `(batch_size * num_images * num_slices, 
             image_feature_size, hidden_size)`
110
111
112
113
114
115
116

    `hidden_size` must match the hidden size of language model backbone.
    instead of a batched tensor.
    """

    image_bounds: torch.Tensor
    """
117
    Shape: `(batch_size * num_images * num_slices, 2)`
118
119
120
121
122
123
124
125

    This should be in `(start, stop)` format.
    """


MiniCPMVImageInputs = Union[MiniCPMVImagePixelInputs,
                            MiniCPMVImageEmbeddingInputs]

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


class Resampler2_5(BaseResampler):

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    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,
                 max_size: Tuple[int, int] = (70, 70),
                 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
147
148
149

        self.max_size = max_size
        self._set_2d_pos_cache(self.max_size)
150

Alphi's avatar
Alphi committed
151
152
    def _set_2d_pos_cache(self,
                          max_size: Tuple[int, int],
Jee Jee Li's avatar
Jee Jee Li committed
153
154
155
156
157
                          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)
158
159
        self.register_buffer("pos_embed", pos_embed, persistent=False)

Alphi's avatar
Alphi committed
160
    def _adjust_pos_cache(self, tgt_sizes: torch.Tensor,
Jee Jee Li's avatar
Jee Jee Li committed
161
162
163
164
165
                          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)

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

Jee Jee Li's avatar
Jee Jee Li committed
173
174
    def forward(self, x: torch.Tensor,
                tgt_sizes: torch.Tensor) -> torch.Tensor:
175
176
177
178
179
180
181
182
183
184
        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
185
186
187
        max_patch_len = patch_len.max().item()
        assert isinstance(max_patch_len, int)

188
189
190
191
192
193
        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
194
            tgt_h, tgt_w = tgt_sizes[i].tolist()
195
196
197
198
199
200
201
202
            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
203
        x, _ = self.kv_proj(x)  # B * L * D
204
205
206
207
208
209
210
211
        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
212
213
            key_padding_mask=key_padding_mask,
        )[0]
214
215
216
217
218
219
220
221
        #  out: Q * B * D
        x = out.permute(1, 0, 2)  # B * Q * D

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


222
223
224
225
226
227
228
229
230
231
232
233
234
def get_version_by_config(config: PretrainedConfig) -> Tuple[int, ...]:
    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("."))


235
236
def _minicpmv_field_config(hf_inputs: Mapping[str, torch.Tensor]):
    return dict(
237
        pixel_values=MultiModalFieldConfig.batched("image"),
238
        image_sizes=MultiModalFieldConfig.batched("image"),
239
240
241
        tgt_sizes=MultiModalFieldConfig.batched("image"),
        image_embeds=MultiModalFieldConfig.batched("image"),
        video_pixel_values=MultiModalFieldConfig.batched("video"),
242
        video_image_sizes=MultiModalFieldConfig.batched("video"),
243
244
        video_tgt_sizes=MultiModalFieldConfig.batched("video"),
        video_embeds=MultiModalFieldConfig.batched("video"),
245
246
247
248
249
250
251
252
    )


class MiniCPMVImageEmbeddingItems(DictEmbeddingItems):

    def __init__(
        self,
        data: Mapping[str, torch.Tensor],
253
254
255
256
        fields_factory: Callable[
            [Mapping[str, torch.Tensor]],
            Mapping[str, MultiModalFieldConfig],
        ],
257
258
259
260
261
    ) -> None:
        super().__init__(
            data,
            modality="image",
            required_fields={"image_embeds", "image_sizes"},
262
            fields_factory=fields_factory,
263
264
265
266
267
268
269
270
271
272
273
274
        )

    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],
275
276
277
278
        fields_factory: Callable[
            [Mapping[str, torch.Tensor]],
            Mapping[str, MultiModalFieldConfig],
        ],
279
280
281
282
283
    ) -> None:
        super().__init__(
            data,
            modality="video",
            required_fields={"video_embeds", "video_image_sizes"},
284
            fields_factory=fields_factory,
285
286
287
288
289
290
291
292
293
294
        )

    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"])


295
296
297
298
299
300
301
class MiniCPMVMultiModalDataParser(MultiModalDataParser):

    def _parse_image_data(
        self,
        data: Union[dict[str, torch.Tensor], ModalityData[ImageItem]],
    ) -> ModalityDataItems[Any, Any]:
        if isinstance(data, dict):
302
303
            return MiniCPMVImageEmbeddingItems(
                data,
304
                fields_factory=_minicpmv_field_config,
305
306
            )

307
308
309
310
311
312
313
        return super()._parse_image_data(data)

    def _parse_video_data(
        self,
        data: Union[dict[str, torch.Tensor], ModalityData[VideoItem]],
    ) -> ModalityDataItems[Any, Any]:
        if isinstance(data, dict):
314
315
            return MiniCPMVVideoEmbeddingItems(
                data,
316
                fields_factory=_minicpmv_field_config,
317
318
            )

319
320
321
322
323
324
325
326
327
328
        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()

329
330
    def get_hf_processor(self, **kwargs: object):
        hf_processor = self.ctx.get_hf_processor(**kwargs)
331
332
333
334
335
336
337
338
339

        # 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())

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
        return hf_processor

    def get_image_processor(self):
        hf_processor = self.get_hf_processor()
        image_processor = hf_processor.image_processor  # type: ignore
        return image_processor

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

    def get_supported_mm_limits(self) -> Mapping[str, Optional[int]]:
        if self.get_model_version() == (2, 6):
            return {"image": None, "video": None}
        else:
            return {"image": None}

356
357
358
359
360
    def get_mm_max_tokens_per_item(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> Mapping[str, int]:
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
        mm_max_tokens = {"image": self.get_max_image_tokens()}
        if self.get_model_version() == (2, 6):
            mm_max_tokens["video"] = self.get_max_video_tokens(seq_len)
        return mm_max_tokens

    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,
                                         self.get_video_max_slice_num())

    def get_max_video_tokens(self, seq_len: int) -> int:
        return self.get_max_video_frame_tokens(
        ) * self.get_num_frames_with_most_features(seq_len)

    def get_slice_query_num(self) -> int:
        hf_config = self.get_hf_config()
        query_num = getattr(hf_config, "query_num", 64)
        return query_num

    def get_max_slice_num(self) -> int:
        hf_config = self.get_hf_config()
        max_slice_num = getattr(hf_config, "max_slice_num", 9)
        return max_slice_num

    def get_sliced_grid(self, image_size: ImageSize,
                        max_slice_num: int) -> Tuple[int, int]:
        if self.get_model_version() == (2, 6):
            slice_grid = self.get_image_processor().get_sliced_grid(
                image_size, max_slice_num)
        else:
            slice_grid = self.get_image_processor().get_sliced_grid(image_size)
        return slice_grid

    def get_num_image_tokens(self, image_size: ImageSize,
                             max_slice_num: int) -> int:
        slice_grid = self.get_sliced_grid(image_size, max_slice_num)
        num_tokens = self.get_slice_query_num(
        ) + 2  # <image>(<unk> * query_num)</image>
        if slice_grid is not None:
            if self.get_model_version() == (2, 6):
                num_additional_tokens = 0
            else:
                # <slice><image>(<unk> * query_num)</image></slice>
                num_additional_tokens = 2
            num_tokens += ((self.get_slice_query_num() + 2) \
                            * slice_grid[0] * slice_grid[1]) \
                            + slice_grid[1] - 1 + num_additional_tokens
        return num_tokens

    def get_image_slice_nums(self, image_size: torch.Tensor,
                             max_slice_nums: int) -> int:
        grid = self.get_sliced_grid(image_size, max_slice_nums)
        return 1 if grid is None else grid[0] * grid[1] + 1

    def get_max_image_tokens(self) -> int:
        image_size = self.get_image_size_with_most_features()
        return self.get_num_image_tokens(image_size, self.get_max_slice_num())

    def get_image_size_with_most_features(self) -> ImageSize:
        # Result in the max possible feature size (h:w = 9:1)
        return self.get_default_image_sizes(self.get_max_slice_num())

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

426
427
    def get_video_frame_size_with_most_features(self) -> ImageSize:
        return self.get_default_image_sizes(self.get_video_max_slice_num())
428

429
430
431
432
    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
433

434
435
    def get_num_frames_with_most_features(self, seq_len: int) -> int:
        mm_config = self.ctx.get_mm_config()
436
437
        max_images = mm_config.get_limit_per_prompt("image")
        max_videos = mm_config.get_limit_per_prompt("video")
438

439
440
441
442
443
444
        # count <image_idx></image_idx> tokens
        # which are not in get_max_image_tokens
        max_image_tokens = self.get_max_image_tokens(
        ) * max_images + 4 * max_images
        max_total_frames = self.get_max_video_frames(seq_len -
                                                     max_image_tokens)
445

446
        num_frames = max(max_total_frames // max(max_videos, 1), 1)
447

448
        return num_frames
449

450
451
452
    def get_default_image_sizes(self, num_slices: int) -> ImageSize:
        image_size = getattr(self.get_hf_config(), "image_size", 448)
        return ImageSize(width=image_size, height=image_size * num_slices)
453
454


455
456
457
458
459
460
_I = TypeVar("_I",
             bound=MiniCPMVProcessingInfo,
             default=MiniCPMVProcessingInfo)


class MiniCPMVDummyInputsBuilder(BaseDummyInputsBuilder[_I]):
461

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
    def get_dummy_processor_inputs(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> ProcessorInputs:
        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 = \
            self.info.get_num_frames_with_most_features(seq_len)

        mm_data = {
            "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,
        }

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

        return ProcessorInputs(prompt_text=image_prompt_texts +
                               video_prompt_texts,
                               mm_data=mm_data)
495

496

497
class MiniCPMVMultiModalProcessor(BaseMultiModalProcessor[_I]):
498
499
500
501
502
503
504
505

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

    def get_slice_image_placeholder(self, image_size: ImageSize,
                                    **kwargs) -> str:
        image_processor = self.info.get_image_processor()
        version = self.info.get_model_version()
506
        if version == (2, 0) or version == (2, 5):
507
508
            return image_processor.get_slice_image_placeholder(image_size)
        return image_processor.get_slice_image_placeholder(
509
510
511
512
513
            image_size, **kwargs)

    def get_image_prompt_texts(self,
                               image_size: ImageSize,
                               image_idx: int = 0) -> str:
514
515
        return self.get_slice_image_placeholder(image_size,
                                                image_idx=image_idx)
516
517
518

    def get_video_prompt_texts(self, image_size: ImageSize,
                               num_frames: int) -> str:
519
520
521
522
523
524
        return self.get_slice_image_placeholder(
            image_size=image_size,
            image_idx=0,
            max_slice_nums=self.info.get_video_max_slice_num(),
            use_image_id=False,
        ) * num_frames
525
526
527

    def get_special_tokens(self) -> Dict[str, torch.Tensor]:
        tokenizer = self.info.get_tokenizer()
528

529
        special_tokens = {
530
531
            "im_start_id": tokenizer.im_start_id,
            "im_end_id": tokenizer.im_end_id,
532
533
        }
        if hasattr(tokenizer, "slice_start_id"):
534
535
536
537
            special_tokens["slice_start_id"] = tokenizer.slice_start_id
            special_tokens["slice_end_id"] = tokenizer.slice_end_id

        return {k: torch.tensor(v) for k, v in special_tokens.items()}
538

539
540
541
542
543
    def process_images(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, NestedTensors]:
544
545
546
547
548
549
550
551
552
553
554
555
556
        if (images := mm_data.get("images")) is None:
            return {}

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

        return 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,
            out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
        )
557

558
559
560
561
562
    def process_videos(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, NestedTensors]:
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
        if (videos := mm_data.get("videos")) is None:
            return {}

        parsed_videos = (self._get_data_parser().parse_mm_data({
            "video": videos
        }).get_items("video", VideoProcessorItems))

        max_slice_num = self.info.get_video_max_slice_num()

        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": max_slice_num
            },
            out_keys={"pixel_values", "image_sizes", "tgt_sizes"},
        )

        return {f"video_{k}": v for k, v in video_inputs.items()}
584

585
586
    def get_placeholder_match_pattern(self) -> str:
        return r"\(<(image|video)>./</\1>\)"
587

588
589
590
591
    def process_mm_inputs(
        self,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
592
    ) -> Mapping[str, NestedTensors]:
593
        return {
594
595
            **self.process_images(mm_data, mm_kwargs),
            **self.process_videos(mm_data, mm_kwargs),
596
        }
597

598
    def _base_call_hf_processor(
599
        self,
600
601
        prompts: list[str],
        mm_data: Mapping[str, Sequence[object]],
602
        mm_kwargs: Mapping[str, object],
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
        *,
        out_keys: set[str],
    ) -> Mapping[str, NestedTensors]:
        # This processor supports zipping prompt and mm_data together
        if self.info.get_model_version() == (2, 6):
            inputs = super()._call_hf_processor(
                prompt=prompts,  # type: ignore
                mm_data=mm_data,
                mm_kwargs=mm_kwargs,
            )
        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,
                )

                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}
631
632
633
634
635
636
637
638
639
640

    def _call_hf_processor(
        self,
        prompt: str,
        mm_data: Mapping[str, object],
        mm_kwargs: Mapping[str, object],
    ) -> BatchFeature:
        # Do not support combination inputs of images and videos for now
        # Try to handle interleaved multimodal data
        tokenizer = self.info.get_tokenizer()
641
        mm_inputs = self.process_mm_inputs(mm_data, mm_kwargs)
642
643

        return BatchFeature({
644
645
646
            "input_ids":
            torch.tensor([tokenizer.encode(prompt)]),
            **mm_inputs,
647
        })
648

649
    def _hf_processor_applies_updates(
650
651
652
653
654
655
656
        self,
        prompt_text: str,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> bool:
        return False

657
    def _get_prompt_updates(
658
659
660
661
662
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
        out_mm_kwargs: MultiModalKwargs,
    ) -> Sequence[PromptUpdate]:
663
664
665
        placeholder = {
            "image": self.info.image_pattern,
            "video": self.info.video_pattern,
666
        }
667

668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
        def get_image_replacement(item_idx: int):
            images = mm_items.get_items(
                "image", (MiniCPMVImageEmbeddingItems, ImageProcessorItems))

            image_size = images.get_image_size(item_idx)

            return self.get_image_prompt_texts(image_size, item_idx)

        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)

            return self.get_video_prompt_texts(frame_size, num_frames)

        get_replacement = {
            "image": get_image_replacement,
            "video": get_video_replacement,
        }
689
690
691
692

        return [
            PromptReplacement(modality=modality,
                              target=placeholder[modality],
693
                              replacement=get_replacement[modality])
694
695
            for modality in ("image", "video")
        ]
696

697
698
    def _get_mm_fields_config(
        self,
699
        hf_inputs: BatchFeature,
700
701
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, MultiModalFieldConfig]:
702
        return _minicpmv_field_config(hf_inputs)
703
704
705
706
707
708

    def apply(
        self,
        prompt: Union[str, List[int]],
        mm_data: MultiModalDataDict,
        hf_processor_mm_kwargs: Mapping[str, object],
709
        return_mm_hashes: bool = False,
710
711
712
713
714
715
716
717
    ) -> MultiModalInputs:
        if isinstance(prompt, list):
            prompt = self.info.get_tokenizer().decode(prompt)
        matches = re.findall(self.get_placeholder_match_pattern(), prompt)
        mm_orders = {
            f"{modality}_orders":
            torch.tensor(
                [index for index, m in enumerate(matches) if m == modality])
718
            for modality in self.info.get_supported_mm_limits()
719
        }
720
721
        result = super().apply(prompt, mm_data, hf_processor_mm_kwargs,
                               return_mm_hashes)
722
723
724
725
726
727
728
729
730
731
732
        # Exclude <image_id>x</image_id> from placeholders
        if "image" in result["mm_placeholders"] and \
            self.info.get_model_version() == (2, 6):
            result["mm_placeholders"]["image"] = [
                PlaceholderRange(offset=p["offset"] + 3 + idx // 10,
                                 length=p["length"] - 3 - idx // 10)
                for idx, p in enumerate(result["mm_placeholders"]["image"])
            ]
        result["mm_kwargs"].update(**mm_orders)
        result["mm_kwargs"].update(**self.get_special_tokens())
        return result
733
734


735
736
class MiniCPMVBaseModel(nn.Module, SupportsMultiModal, SupportsPP,
                        SupportsV0Only):
Jee Jee Li's avatar
Jee Jee Li committed
737
738
739
740
    """
    The abstract class of MiniCPMV can only be inherited, but cannot be
    instantiated.
    """
741

742
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
743
744
745
        config = vllm_config.model_config.hf_config
        multimodal_config = vllm_config.model_config.multimodal_config
        quant_config = vllm_config.quant_config
746
        super().__init__()
747
748
749
750
        # 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
751
752
753
        self.config = config
        self.multimodal_config = multimodal_config

754
        self.version = get_version_by_config(self.config)
755
756
757
758
759
        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
760
761
        self.vision_dim = (self.vpm.embed_dim if self.version == (2, 0) else
                           self.vpm.embeddings.embed_dim)
Alphi's avatar
Alphi committed
762
        self.embed_dim = self.config.hidden_size
763

764
765
766
        self.resampler = self.init_resampler(self.embed_dim,
                                             self.vision_dim,
                                             quant_config=quant_config,
767
768
                                             prefix=maybe_prefix(
                                                 prefix, "resampler"))
769

770
771
772
        self.make_empty_intermediate_tensors = (
            self.llm.make_empty_intermediate_tensors)

773
774
775
776
777
778
779
    @cached_property
    def sampler(self):
        if hasattr(self.llm, "sampler"):
            return self.llm.sampler

        return get_sampler()

780
    def get_embedding_with_vision(
Jee Jee Li's avatar
Jee Jee Li committed
781
782
        self,
        input_ids: torch.Tensor,
783
        image_inputs: Optional[MiniCPMVImageInputs],
784
    ) -> torch.Tensor:
785
        vlm_embedding: torch.Tensor = self.llm.get_input_embeddings(input_ids)
Jee Jee Li's avatar
Jee Jee Li committed
786

787
788
789
790
791
792
793
794
        if image_inputs is None:
            return vlm_embedding

        if image_inputs["type"] == "image_embeds":
            vision_hidden_states = image_inputs["image_embeds"].to(
                device=vlm_embedding.device,
                dtype=vlm_embedding.dtype,
            )
795
        else:
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
            vision_hidden_states = self.get_vision_hidden_states(image_inputs)

        # See NOTE in _parse_and_validate_inputs
        image_bounds = image_inputs["image_bounds"]
        if len(image_bounds) > 0:
            image_indices = torch.stack([
                torch.arange(start, end, dtype=torch.long)
                for start, end in image_bounds.tolist()
            ]).to(vlm_embedding.device)

            vlm_embedding.scatter_(
                0,
                image_indices.view(-1, 1).repeat(1, vlm_embedding.shape[-1]),
                vision_hidden_states.view(-1, vision_hidden_states.shape[-1]),
            )
811

812
        return vlm_embedding
813

814
815
816
817
818
819
820
821
822
823
824
825
826
827
    def _get_image_bounds(
            self,
            input_ids: torch.Tensor,
            im_start_id: torch.Tensor,
            im_end_id: torch.Tensor,
            slice_start_id: Optional[torch.Tensor] = None,
            slice_end_id: Optional[torch.Tensor] = None) -> torch.Tensor:
        # All the images in the batch should share the same special image
        # bound token ids.
        start_cond = input_ids == im_start_id[0]
        end_cond = input_ids == im_end_id[0]
        if slice_start_id is not None:
            start_cond |= (input_ids == slice_start_id[0])
            end_cond |= (input_ids == slice_end_id[0])
Alphi's avatar
Alphi committed
828

Jee Jee Li's avatar
Jee Jee Li committed
829
        image_start_tokens, = torch.where(start_cond)
830
        image_start_tokens += 1
Jee Jee Li's avatar
Jee Jee Li committed
831
        image_end_tokens, = torch.where(end_cond)
Alphi's avatar
Alphi committed
832
        valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
Jee Jee Li's avatar
Jee Jee Li committed
833

834
        if valid_image_nums == 0:
Jee Jee Li's avatar
Jee Jee Li committed
835
836
837
            return torch.zeros((0, 2), device=input_ids.device)

        return torch.hstack([
838
839
840
841
            image_start_tokens[:valid_image_nums].unsqueeze(-1),
            image_end_tokens[:valid_image_nums].unsqueeze(-1),
        ])

842
    def _parse_and_validate_image_inputs(
Jee Jee Li's avatar
Jee Jee Li committed
843
844
845
        self,
        input_ids: torch.Tensor,
        **kwargs: object,
846
    ) -> Optional[MiniCPMVImageInputs]:
847
848
        image_keys = {"pixel_values", "tgt_sizes"}
        pixel_data = {
849
            "image": {
850
851
                key: kwargs.pop(key, None)
                for key in image_keys
852
853
            },
            "video": {
854
855
                key: kwargs.pop("video_" + key, None)
                for key in image_keys
856
857
            }
        }
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
        embed_data = {
            "image": kwargs.pop("image_embeds", None),
            "video": kwargs.pop("video_embeds", None),
        }

        all_pixel_data = [
            v for vs in pixel_data.values() for v in vs.values()
            if v is not None
        ]
        all_embed_data = [v for v in embed_data.values() if v is not None]
        if len(all_pixel_data) == 0 and len(all_embed_data) == 0:
            return None

        im_start_id = kwargs.pop("im_start_id")
        if not isinstance(im_start_id, torch.Tensor):
            raise ValueError("Incorrect type of im_start_id. "
                             f"Got type: {type(im_start_id)}")

        im_end_id = kwargs.pop("im_end_id")
        if not isinstance(im_end_id, torch.Tensor):
            raise ValueError("Incorrect type of im_end_id. "
                             f"Got type: {type(im_end_id)}")

881
        slice_start_id = kwargs.pop("slice_start_id", None)
882
883
884
885
886
        if slice_start_id is not None and not isinstance(
                slice_start_id, torch.Tensor):
            raise ValueError("Incorrect type of slice_start_id. "
                             f"Got type: {type(slice_start_id)}")

887
        slice_end_id = kwargs.pop("slice_end_id", None)
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
        if slice_end_id is not None and not isinstance(slice_end_id,
                                                       torch.Tensor):
            raise ValueError("Incorrect type of slice_end_id. "
                             f"Got type: {type(slice_end_id)}")

        if len(all_embed_data) > 0:
            if len(all_embed_data) > 1:
                raise ValueError("Incorrect inputs for vision embeddings. "
                                 "Image embeds and video embeds can not "
                                 "exist simultaneously.")

            vision_embeds, = all_embed_data
            if not isinstance(vision_embeds, (torch.Tensor, list)):
                raise ValueError(f"Incorrect type of vision_embeds. "
                                 f"Got type: {type(vision_embeds)}")
903

904
            return MiniCPMVImageEmbeddingInputs(
905
906
907
                type="image_embeds",
                image_embeds=flatten_bn(flatten_2d_lists(vision_embeds),
                                        concat=True),
908
909
910
911
                image_bounds=self._get_image_bounds(input_ids, im_start_id,
                                                    im_end_id, slice_start_id,
                                                    slice_end_id),
            )
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933

        order_data = dict[str, Union[torch.Tensor, list[torch.Tensor]]]()
        for modality in ("image", "video"):
            modality_orders = kwargs.pop(f"{modality}_orders", None)
            if modality_orders is not None:
                if not isinstance(modality_orders, (torch.Tensor, list)):
                    raise ValueError(f"Incorrect type of {modality}_orders. "
                                     f"Got type: {type(modality_orders)}")

                order_data[modality] = modality_orders

        batch_sizes = {
            modality: len(modality_orders)
            for modality, modality_orders in order_data.items()
        }
        unique_batch_sizes = set(batch_sizes.values())
        assert len(unique_batch_sizes) == 1, (
            f"Found inconsistent batch sizes: {batch_sizes}")
        batch_size, = unique_batch_sizes

        pixel_values_flat = list[torch.Tensor]()
        tgt_sizes_flat = list[torch.Tensor]()
934
        for b in range(batch_size):
935
936
937
938
            mm_orders_b = [(idx_b.item(), modality)
                           for modality, modality_orders in order_data.items()
                           for idx_b in modality_orders[b]]

939
            for _, modality in sorted(mm_orders_b, key=lambda x: x[0]):
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
                modality_pixel_data = pixel_data[modality]

                modality_pixel_values = modality_pixel_data["pixel_values"]
                if not isinstance(modality_pixel_values, (torch.Tensor, list)):
                    raise ValueError(
                        f"Incorrect type of pixel_values for {modality=}. "
                        f"Got type: {type(modality_pixel_values)}")

                modality_tgt_sizes = modality_pixel_data["tgt_sizes"]
                if not isinstance(modality_tgt_sizes, (torch.Tensor, list)):
                    raise ValueError(
                        f"Incorrect type of tgt_sizes for {modality=}. "
                        f"Got type: {type(modality_tgt_sizes)}")

                pixel_values_flat += flatten_2d_lists(modality_pixel_values[b])
                tgt_sizes_flat += flatten_2d_lists(modality_tgt_sizes[b])
Jee Jee Li's avatar
Jee Jee Li committed
956
957
958
959
960
961
962
963
964
965
966

        # NOTE: Input IDs does not contain image tokens during memory profiling,
        # so we allow it to be empty
        if len(pixel_values_flat) != len(tgt_sizes_flat):
            raise ValueError("Inconsistent flattened lengths, found: "
                             f"{len(pixel_values_flat)} vs. "
                             f"{len(tgt_sizes_flat)}")

        if len(pixel_values_flat) == 0:
            return None

967
        return MiniCPMVImagePixelInputs(
968
969
970
            type="pixel_values",
            pixel_values=pixel_values_flat,
            tgt_sizes=torch.stack(tgt_sizes_flat),
971
972
973
            image_bounds=self._get_image_bounds(input_ids, im_start_id,
                                                im_end_id, slice_start_id,
                                                slice_end_id),
Jee Jee Li's avatar
Jee Jee Li committed
974
        )
975

976
977
978
979
    def _parse_and_validate_inputs(self, input_ids: torch.Tensor,
                                   **kwargs: object):
        return self._parse_and_validate_image_inputs(input_ids, **kwargs)

980
981
982
983
984
    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        intermediate_tensors: Optional[IntermediateTensors] = None,
Jee Jee Li's avatar
Jee Jee Li committed
985
986
        **kwargs: Any,
    ) -> torch.Tensor:
987
988
989
        if intermediate_tensors is not None:
            vlm_embeddings = None
        else:
990
991
            image_inputs = \
                self._parse_and_validate_inputs(input_ids, **kwargs)
992
            vlm_embeddings = self.get_embedding_with_vision(
993
                input_ids, image_inputs)
Jee Jee Li's avatar
Jee Jee Li committed
994

995
996
997
998
999
        # always pass the input via `inputs_embeds`
        # to make sure the computation graph is consistent
        # for `torch.compile` integration
        input_ids = None

1000
        output = self.llm.model(
1001
            input_ids=input_ids,
Jee Jee Li's avatar
Jee Jee Li committed
1002
1003
1004
1005
            positions=positions,
            intermediate_tensors=intermediate_tensors,
            inputs_embeds=vlm_embeddings,
        )
1006
1007
        return output

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

    def sample(
        self,
        logits: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[SamplerOutput]:
Alphi's avatar
Alphi committed
1020
        next_tokens = self.sampler(logits, sampling_metadata)
1021
1022
        return next_tokens

1023
1024
    def load_weights(self, weights: Iterable[Tuple[str,
                                                   torch.Tensor]]) -> Set[str]:
1025
1026
        loader = AutoWeightsLoader(self)
        return loader.load_weights(weights)
Jee Jee Li's avatar
Jee Jee Li committed
1027

1028
1029
1030
1031
1032
1033
1034
1035
    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
1036
1037
    def init_llm(
        self,
1038
        vllm_config: VllmConfig,
1039
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1040
1041
1042
    ) -> nn.Module:
        raise NotImplementedError

1043
1044
1045
1046
    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig],
1047
        prefix: str = "",
1048
    ) -> nn.Module:
Jee Jee Li's avatar
Jee Jee Li committed
1049
1050
        raise NotImplementedError

1051
1052
1053
1054
1055
    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
1056
1057
        raise NotImplementedError

1058
1059
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
Jee Jee Li's avatar
Jee Jee Li committed
1060
1061
1062
        raise NotImplementedError


1063
class MiniCPMV2_0(MiniCPMVBaseModel):
Jee Jee Li's avatar
Jee Jee Li committed
1064

1065
1066
    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
1067
1068
1069
1070
        assert self.version == (2, 0)

    def init_llm(
        self,
1071
        vllm_config: VllmConfig,
1072
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1073
    ) -> nn.Module:
1074
        return MiniCPMForCausalLM(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1075

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

Jee Jee Li's avatar
Jee Jee Li committed
1088
1089
1090
1091
1092
1093
1094
1095
1096
        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,
            )

1097
1098
        model = model.to(dtype=torch.get_default_dtype())

Jee Jee Li's avatar
Jee Jee Li committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
        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

1108
1109
1110
    def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.model.embed_tokens(input_ids)

1111
1112
1113
1114
1115
    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
1116
        with set_default_torch_dtype(torch.float16):
1117
1118
1119
1120
1121
1122
1123
1124
1125
            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
1126

1127
1128
        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())
Jee Jee Li's avatar
Jee Jee Li committed
1129

1130
1131
1132
1133
1134
1135
1136
1137
1138
    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
1139
1140
        for pixel_value in pixel_values:
            H, W = pixel_value[0].shape[-2:]
1141
            tgt_size = (math.ceil(H / P_h), math.ceil(W / P_w))
Jee Jee Li's avatar
Jee Jee Li committed
1142
1143
1144
            vision_embedding = self.vpm.forward_features(
                pixel_value.unsqueeze(0).type(dtype))

1145
1146
1147
            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
1148

1149
        return torch.vstack(res)
Jee Jee Li's avatar
Jee Jee Li committed
1150
1151


1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
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
1164

1165
1166
    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
1167
1168
1169
1170
        assert self.version == (2, 5)

    def init_llm(
        self,
1171
        vllm_config: VllmConfig,
1172
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1173
    ) -> nn.Module:
1174
        return LlamaForCausalLM(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1175

1176
1177
1178
1179
    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig],
1180
        prefix: str = "",
1181
1182
    ) -> nn.Module:
        model = Idefics2VisionTransformer(config.vision_config,
1183
1184
                                          quant_config=quant_config,
                                          prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1185
1186
1187
1188
        if self.config.drop_vision_last_layer:
            model.encoder.layers = model.encoder.layers[:-1]
        return model

1189
1190
1191
1192
1193
    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
1194
        with set_default_torch_dtype(torch.float16):
1195
1196
1197
1198
1199
1200
            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)
1201

1202
1203
        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())
Jee Jee Li's avatar
Jee Jee Li committed
1204

1205
1206
1207
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        pixel_values = data["pixel_values"]
Jee Jee Li's avatar
Jee Jee Li committed
1208
1209
        tgt_sizes = data["tgt_sizes"]

1210
1211
1212
1213
1214
        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
1215

1216
1217
1218
1219
1220
1221
        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
1222

1223
1224
1225
        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
1226

1227
        patch_attn_mask = torch.zeros((B, max_patches),
Jee Jee Li's avatar
Jee Jee Li committed
1228
1229
                                      dtype=torch.bool,
                                      device=device)
1230
1231
        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
1232

1233
1234
1235
1236
1237
1238
1239
        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
1240
1241


1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
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
1254

1255
1256
    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__(vllm_config=vllm_config, prefix=prefix)
1257
        assert self.version == (2, 6)
Jee Jee Li's avatar
Jee Jee Li committed
1258
1259
1260

    def init_llm(
        self,
1261
        vllm_config: VllmConfig,
1262
        prefix: str = "",
Jee Jee Li's avatar
Jee Jee Li committed
1263
    ) -> nn.Module:
1264
        return Qwen2ForCausalLM(vllm_config=vllm_config, prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1265

1266
1267
1268
1269
    def init_vision_module(
        self,
        config: PretrainedConfig,
        quant_config: Optional[QuantizationConfig],
1270
        prefix: str = "",
1271
1272
    ) -> nn.Module:
        model = Idefics2VisionTransformer(config.vision_config,
1273
1274
                                          quant_config=quant_config,
                                          prefix=prefix)
Jee Jee Li's avatar
Jee Jee Li committed
1275
1276
1277
1278
        if self.config.drop_vision_last_layer:
            model.encoder.layers = model.encoder.layers[:-1]
        return model

1279
1280
1281
1282
1283
    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
1284
        with set_default_torch_dtype(torch.float16):
1285
            # The resampler in 2.6 remains consistent with the one in 2.5.
1286
1287
1288
1289
1290
1291
            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)
1292

1293
1294
        return resampler.to(device=current_platform.device_type,
                            dtype=torch.get_default_dtype())
Jee Jee Li's avatar
Jee Jee Li committed
1295

1296
1297
1298
    def get_vision_hidden_states(
            self, data: MiniCPMVImagePixelInputs) -> torch.Tensor:
        pixel_values = data["pixel_values"]
Jee Jee Li's avatar
Jee Jee Li committed
1299
1300
        tgt_sizes = data["tgt_sizes"]

1301
1302
1303
1304
1305
        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
1306

1307
1308
1309
1310
1311
1312
        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
1313

1314
1315
1316
        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
1317

1318
        patch_attn_mask = torch.zeros((B, max_patches),
Jee Jee Li's avatar
Jee Jee Li committed
1319
1320
                                      dtype=torch.bool,
                                      device=device)
1321
1322
1323
        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
1324
        vision_embedding = self.vpm(
1325
1326
            all_pixel_values,
            patch_attention_mask=patch_attn_mask.unsqueeze(1),
Jee Jee Li's avatar
Jee Jee Li committed
1327
            tgt_sizes=tgt_sizes,
1328
        )
Jee Jee Li's avatar
Jee Jee Li committed
1329
1330
1331
1332

        return self.resampler(vision_embedding, tgt_sizes)


1333
1334
1335
_SUPPORT_VERSION = {
    (2, 0): MiniCPMV2_0,
    (2, 5): MiniCPMV2_5,
1336
    (2, 6): MiniCPMV2_6,
1337
1338
1339
}


1340
1341
1342
1343
1344
@MULTIMODAL_REGISTRY.register_processor(
    MiniCPMVMultiModalProcessor,
    info=MiniCPMVProcessingInfo,
    dummy_inputs=MiniCPMVDummyInputsBuilder)
class MiniCPMV(MiniCPMVBaseModel, SupportsMultiModal, SupportsLoRA):
Jee Jee Li's avatar
Jee Jee Li committed
1345
1346
1347
1348
1349
    """
    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.
    """
1350

1351
    def __new__(cls, *, vllm_config: VllmConfig, prefix: str = ""):
1352
        config = vllm_config.model_config.hf_config
Jee Jee Li's avatar
Jee Jee Li committed
1353
1354
1355
1356
1357
1358
1359
1360
1361
        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
1362
1363
        instance_cls = _SUPPORT_VERSION.get(version)
        if instance_cls is None:
1364
1365
            raise ValueError(
                "Currently, MiniCPMV only supports versions 2.0, 2.5, and 2.6")
1366
1367
1368
1369
1370
1371
1372

        # 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)