minicpmv.py 38.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# coding=utf-8
# 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
23
"""Inference-only MiniCPM-V model compatible with HuggingFace weights."""
24
25
import math
import re
26
from array import array
27
from functools import partial
28
29
from typing import (Any, Callable, Iterable, List, Mapping, Optional, Tuple,
                    TypedDict, Union)
30
31
32
33

import numpy as np
import torch
import torch.nn.functional as F
Alphi's avatar
Alphi committed
34
import torch.types
35
36
37
from PIL import Image
from torch import nn
from torch.nn.init import trunc_normal_
38
from transformers import PretrainedConfig
39
40
41
42

from vllm.attention import AttentionMetadata
from vllm.config import CacheConfig, MultiModalConfig
from vllm.inputs import INPUT_REGISTRY, InputContext, LLMInputs
Jee Jee Li's avatar
Jee Jee Li committed
43
44
from vllm.logger import init_logger
from vllm.model_executor.layers.linear import ReplicatedLinear
Alphi's avatar
Alphi committed
45
from vllm.model_executor.layers.logits_processor import LogitsProcessor
46
from vllm.model_executor.layers.quantization import QuantizationConfig
47
from vllm.model_executor.layers.sampler import Sampler
Alphi's avatar
Alphi committed
48
from vllm.model_executor.layers.vocab_parallel_embedding import ParallelLMHead
Jee Jee Li's avatar
Jee Jee Li committed
49
from vllm.model_executor.model_loader.utils import set_default_torch_dtype
50
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
51
from vllm.model_executor.models.interfaces import SupportsMultiModal
Alphi's avatar
Alphi committed
52
53
54
from vllm.model_executor.models.llama import LlamaModel
from vllm.model_executor.models.minicpm import MiniCPMModel
from vllm.model_executor.models.qwen2 import Qwen2Model
55
56
from vllm.model_executor.sampling_metadata import SamplingMetadata
from vllm.multimodal import MULTIMODAL_REGISTRY
57
58
from vllm.multimodal.image import cached_get_image_processor
from vllm.multimodal.utils import cached_get_tokenizer
59
60
from vllm.sequence import (VLLM_TOKEN_ID_ARRAY_TYPE, IntermediateTensors,
                           SamplerOutput, SequenceData)
61

Jee Jee Li's avatar
Jee Jee Li committed
62
63
64
65
from .idefics2_vision_model import Idefics2VisionTransformer

logger = init_logger(__name__)

66
_KEYS_TO_MODIFY_MAPPING = {
Alphi's avatar
Alphi committed
67
68
    "llm.lm_head": "lm_head",
    "llm.model": "llm",
69
70
71
}


Jee Jee Li's avatar
Jee Jee Li committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class MiniCPMVImagePixelInputs(TypedDict):
    pixel_values: List[torch.Tensor]
    """
    Shape: `(batch_size * num_images, num_channels, height, width)`

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

    image_bounds: torch.Tensor
    """
    Shape: `(batch_size * num_images, 2)`

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

    tgt_sizes: torch.Tensor
    """
    Shape: `(batch_size * num_images, 2)`

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


MiniCPMVImageInputs = MiniCPMVImagePixelInputs

DEFAULT_LN = partial(nn.LayerNorm, eps=1e-6)


Alphi's avatar
Alphi committed
101
def get_abs_pos(abs_pos: torch.Tensor, tgt_size: torch.Tensor):
102
103
104
105
106
107
108
    # abs_pos: L, C
    # tgt_size: (H, W)
    # return: M, C
    src_size = int(math.sqrt(abs_pos.size(0)))
    # tgt_size = int(math.sqrt(tgt_size))
    dtype = abs_pos.dtype

Jee Jee Li's avatar
Jee Jee Li committed
109
    return (F.interpolate(
110
111
112
113
        abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
        size=(tgt_size[0], tgt_size[1]),
        mode="bicubic",
        align_corners=False,
Jee Jee Li's avatar
Jee Jee Li committed
114
    ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype))
115
116
117


# https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
Jee Jee Li's avatar
Jee Jee Li committed
118
119
120
121
122
123
def get_2d_sincos_pos_embed(
        embed_dim: int,
        grid_size: Union[int, Tuple[int, int]],
        cls_token: bool = False,
        version: Tuple[int, int] = (2, 0),
):
124
125
126
    """
    grid_size: int of the grid height and width
    return:
Jee Jee Li's avatar
Jee Jee Li committed
127
    pos_embed: [grid_size*grid_size, embed_dim] or
128
129
130
131
132
133
134
135
136
137
138
139
                [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
    """
    if isinstance(grid_size, int):
        grid_h_size, grid_w_size = grid_size, grid_size
    else:
        grid_h_size, grid_w_size = grid_size[0], grid_size[1]

    grid_h = np.arange(grid_h_size, dtype=np.float32)
    grid_w = np.arange(grid_w_size, dtype=np.float32)
    grid = np.meshgrid(grid_w, grid_h)  # here w goes first
    grid = np.stack(grid, axis=0)

Alphi's avatar
Alphi committed
140
    if version == (2, 0):
141
142
143
144
145
146
147
148
149
150
        grid = grid.reshape([2, 1, grid_h_size, grid_w_size])
        pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid, version)
        if cls_token:
            pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed],
                                       axis=0)
    else:
        pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid, version)
    return pos_embed


Alphi's avatar
Alphi committed
151
def get_2d_sincos_pos_embed_from_grid(embed_dim: int,
Jee Jee Li's avatar
Jee Jee Li committed
152
                                      grid: np.ndarray,
Alphi's avatar
Alphi committed
153
                                      version: Tuple[int, int] = (2, 0)):
154
155
156
157
158
159
160
161
    assert embed_dim % 2 == 0

    # use half of dimensions to encode grid_h
    emb_h = get_1d_sincos_pos_embed_from_grid(
        embed_dim // 2, grid[0], version)  # (H*W, D/2) or (H, W, D/2)
    emb_w = get_1d_sincos_pos_embed_from_grid(
        embed_dim // 2, grid[1], version)  # (H*W, D/2) or (H, W, D/2)

Alphi's avatar
Alphi committed
162
    if version == (2, 0):
163
164
165
166
167
168
        emb = np.concatenate([emb_h, emb_w], axis=1)  # (H*W, D)
    else:
        emb = np.concatenate([emb_h, emb_w], axis=-1)  # (H, W, D)
    return emb


Alphi's avatar
Alphi committed
169
def get_1d_sincos_pos_embed_from_grid(embed_dim: int,
Jee Jee Li's avatar
Jee Jee Li committed
170
                                      pos: np.ndarray,
Alphi's avatar
Alphi committed
171
                                      version: Tuple[int, int] = (2, 0)):
172
173
174
175
176
177
178
    """
    embed_dim: output dimension for each position
    pos: a list of positions to be encoded: size (M,) / (H, W)
    out: (M, D) / (H, W, D)
    """
    assert embed_dim % 2 == 0
    omega = np.arange(embed_dim // 2, dtype=np.float32)
Jee Jee Li's avatar
Jee Jee Li committed
179
180
    omega /= embed_dim / 2.0
    omega = 1.0 / 10000**omega  # (D/2,)
181

Alphi's avatar
Alphi committed
182
    if version == (2, 0):
183
        pos = pos.reshape(-1)  # (M,)
Jee Jee Li's avatar
Jee Jee Li committed
184
        out = np.einsum("m,d->md", pos, omega)  # (M, D/2), outer product
185
186
187
188
        emb_sin = np.sin(out)  # (M, D/2)
        emb_cos = np.cos(out)  # (M, D/2)
        emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (M, D)
    else:
Jee Jee Li's avatar
Jee Jee Li committed
189
        out = np.einsum("hw,d->hwd", pos, omega)  # (H, W, D/2), outer product
190
191
192
193
194
195
        emb_sin = np.sin(out)  # (H, W, D/2)
        emb_cos = np.cos(out)  # (H, W, D/2)
        emb = np.concatenate([emb_sin, emb_cos], axis=-1)  # (H, W, D)
    return emb


Jee Jee Li's avatar
Jee Jee Li committed
196
class BaseResampler(nn.Module):
197
198
199
200
201
202
203
    """
    A 2D perceiver-resampler network with one cross attention layers by
        (grid_size**2) learnable queries and 2d sincos pos_emb
    Outputs:
        A tensor with the shape of (grid_size**2, embed_dim)
    """

Jee Jee Li's avatar
Jee Jee Li committed
204
205
206
207
208
209
210
211
    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,
    ) -> None:
212
213
        super().__init__()

Jee Jee Li's avatar
Jee Jee Li committed
214
        self.num_queries = num_queries
215
216
217
218
        self.embed_dim = embed_dim
        self.num_heads = num_heads

        self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
Jee Jee Li's avatar
Jee Jee Li committed
219
        trunc_normal_(self.query, std=0.02)
220
        if kv_dim is not None and kv_dim != embed_dim:
Jee Jee Li's avatar
Jee Jee Li committed
221
            self.kv_proj = ReplicatedLinear(kv_dim, embed_dim, bias=False)
222
        else:
Jee Jee Li's avatar
Jee Jee Li committed
223
224
225
226
227
            # Maintain the same return value with ReplicatedLinear.forward
            self.kv_proj = lambda *args, **kwargs: (
                nn.Identity()(*args, **kwargs),
                None,
            )
228
229
230
231
232
233
234
        self.attn = nn.MultiheadAttention(embed_dim, num_heads)
        self.ln_q = norm_layer(embed_dim)
        self.ln_kv = norm_layer(embed_dim)
        self.ln_post = norm_layer(embed_dim)
        self.proj = nn.Parameter(
            (embed_dim**-0.5) * torch.randn(embed_dim, embed_dim))

Jee Jee Li's avatar
Jee Jee Li committed
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    def _init_weights(self, m: nn.Module) -> None:
        if isinstance(m, nn.Linear):
            trunc_normal_(m.weight, std=0.02)
            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.constant_(m.bias, 0)
        elif isinstance(m, nn.LayerNorm):
            nn.init.constant_(m.bias, 0)
            nn.init.constant_(m.weight, 1.0)

    def _repeat(self, query, N: int):
        return query.unsqueeze(1).repeat(1, N, 1)


class Resampler2(BaseResampler):

    def __init__(
        self,
        grid_size: int,
        embed_dim: int,
        num_heads: int,
        kv_dim: Optional[int] = None,
        norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
        adaptive: bool = False,
    ) -> None:
        super().__init__(grid_size**2, embed_dim, num_heads, kv_dim,
                         norm_layer)

        self.adaptive = adaptive
        pos_embed_arr = get_2d_sincos_pos_embed(embed_dim,
                                                grid_size,
                                                version=(2, 0))
        self.pos_embed = nn.Parameter(
            torch.from_numpy(pos_embed_arr).float()).requires_grad_(False)

        self.apply(self._init_weights)

    def forward(
        self,
        x: torch.Tensor,
        tgt_sizes: torch.Tensor,
        attn_mask: Optional[torch.Tensor] = None,
    ):
        if self.adaptive:
            pos_embed_arr = get_2d_sincos_pos_embed(self.embed_dim,
                                                    tgt_sizes,
                                                    version=(2, 0))
            pos_embed = torch.from_numpy(pos_embed_arr).to(device=x.device,
                                                           dtype=x.dtype)
283
        else:
Jee Jee Li's avatar
Jee Jee Li committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
            pos_embed = get_abs_pos(self.pos_embed, tgt_sizes)

        x, _ = self.kv_proj(x)
        x = self.ln_kv(x).permute(1, 0, 2)

        N = x.shape[1]
        q = self.ln_q(self.query)
        out = self.attn(
            self._repeat(q, N) + self.pos_embed.unsqueeze(1),
            x + pos_embed.unsqueeze(1),
            x,
            attn_mask=attn_mask,
        )[0]
        x = out.permute(1, 0, 2)

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


class Resampler2_5(BaseResampler):

    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),
    ) -> None:
        super().__init__(num_queries, embed_dim, num_heads, kv_dim, norm_layer)

        self.max_size = max_size
        self._set_2d_pos_cache(self.max_size)
319
320
321

        self.apply(self._init_weights)

Alphi's avatar
Alphi committed
322
323
    def _set_2d_pos_cache(self,
                          max_size: Tuple[int, int],
Jee Jee Li's avatar
Jee Jee Li committed
324
325
326
327
328
                          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)
329
330
        self.register_buffer("pos_embed", pos_embed, persistent=False)

Alphi's avatar
Alphi committed
331
    def _adjust_pos_cache(self, tgt_sizes: torch.Tensor,
Jee Jee Li's avatar
Jee Jee Li committed
332
333
334
335
336
                          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)

337
        if max_h > self.max_size[0] or max_w > self.max_size[1]:
Jee Jee Li's avatar
Jee Jee Li committed
338
            self.max_size = (
339
                max(max_h, self.max_size[0]),
Jee Jee Li's avatar
Jee Jee Li committed
340
341
                max(max_w, self.max_size[1]),
            )
342
343
            self._set_2d_pos_cache(self.max_size, device)

Jee Jee Li's avatar
Jee Jee Li committed
344
345
    def forward(self, x: torch.Tensor,
                tgt_sizes: torch.Tensor) -> torch.Tensor:
346
347
348
349
350
351
352
353
354
355
        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
356
357
358
        max_patch_len = patch_len.max().item()
        assert isinstance(max_patch_len, int)

359
360
361
362
363
364
        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
365
            tgt_h, tgt_w = tgt_sizes[i].tolist()
366
367
368
369
370
371
372
373
            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
374
        x, _ = self.kv_proj(x)  # B * L * D
375
376
377
378
379
380
381
382
        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
383
384
            key_padding_mask=key_padding_mask,
        )[0]
385
386
387
388
389
390
391
392
        #  out: Q * B * D
        x = out.permute(1, 0, 2)  # B * Q * D

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


393
394
395
396
397
398
399
400
401
402
403
404
405
406
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("."))


407
def get_max_minicpmv_image_tokens(ctx: InputContext):
408
    hf_config = ctx.get_hf_config()
409
410
411
    return getattr(hf_config, "query_num", 64)


412
def dummy_seq_data_for_minicpmv(seq_len: int, num_images: int):
413
    token_ids = array(VLLM_TOKEN_ID_ARRAY_TYPE, [0]) * seq_len
414
415
416
    return SequenceData(token_ids)


417
def dummy_image_for_minicpmv(hf_config: PretrainedConfig, num_images: int):
418
419
    width = height = hf_config.image_size
    image = Image.new("RGB", (width, height), color=0)
420
    return {"image": image if num_images == 1 else [image] * num_images}
421
422


423
424
def dummy_data_for_minicpmv(ctx: InputContext, seq_len: int,
                            mm_counts: Mapping[str, int]):
425
    hf_config = ctx.get_hf_config()
426
    num_images = mm_counts["image"]
427

428
429
    seq_data = dummy_seq_data_for_minicpmv(seq_len, num_images)
    mm_data = dummy_image_for_minicpmv(hf_config, num_images)
430
431
432
433
434
435
436
437
438

    return seq_data, mm_data


def input_processor_for_minicpmv(ctx: InputContext, llm_inputs: LLMInputs):
    multi_modal_data = llm_inputs.get("multi_modal_data")
    if multi_modal_data is None or "image" not in multi_modal_data:
        return llm_inputs
    model_config = ctx.model_config
439
    version = get_version_by_config(model_config.hf_config)
440
441
    tokenizer = cached_get_tokenizer(model_config.tokenizer,
                                     trust_remote_code=True)
442
443
444
445
446
447
448
449
    image_processor = cached_get_image_processor(model_config.tokenizer)

    def get_placeholder(image_size: Tuple[int, int], num_image: int):
        if version == (2, 0) or version == (2, 5):
            return image_processor. \
                get_slice_image_placeholder(image_size)
        return image_processor. \
            get_slice_image_placeholder(image_size, num_image)
450
451
452
453
454
455
456

    prompt = llm_inputs.get("prompt")
    if prompt is None:
        token_ids = llm_inputs.get("prompt_token_ids")
        prompt = tokenizer.decode(token_ids)

    pattern = "(<image>./</image>)"
457
458
459
    images = multi_modal_data["image"]
    if isinstance(images, Image.Image):
        images = [images]
460
461
    image_tags = re.findall(pattern, prompt)

Jee Jee Li's avatar
Jee Jee Li committed
462
463
464
465
466
    if len(image_tags) == 0:
        new_token_ids = token_ids
        new_prompt = prompt
    else:
        text_chunks = prompt.split(pattern)
467
468
469
470
471
472
473
474
        new_prompt_chunks: List[str] = []
        for i in range(len(images)):
            new_prompt_chunks += [
                text_chunks[i],
                get_placeholder(images[i].size, i)
            ]
        new_prompt_chunks.append(text_chunks[-1])
        new_prompt = "".join(new_prompt_chunks)
Jee Jee Li's avatar
Jee Jee Li committed
475
476
477
478
479
480
481
        new_token_ids = tokenizer.encode(new_prompt)

    llm_inputs = LLMInputs(
        prompt_token_ids=new_token_ids,
        prompt=new_prompt,
        multi_modal_data=multi_modal_data,
    )
482
483
484
    return llm_inputs


485
class MiniCPMVBaseModel(nn.Module, SupportsMultiModal):
Jee Jee Li's avatar
Jee Jee Li committed
486
487
488
489
    """
    The abstract class of MiniCPMV can only be inherited, but cannot be
    instantiated.
    """
490
491
492

    def __init__(
        self,
Alphi's avatar
Alphi committed
493
        config: PretrainedConfig,
494
495
496
497
498
        multimodal_config: MultiModalConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ):
        super().__init__()
499
500
501
502
        # 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
503
504
505
        self.config = config
        self.multimodal_config = multimodal_config

506
        self.version = get_version_by_config(self.config)
507
508
509
510
        self.llm = self.init_llm(config, cache_config, quant_config)
        self.vpm = self.init_vision_module()
        param_dtype = torch.get_default_dtype()
        self.vpm.to(dtype=param_dtype)
Jee Jee Li's avatar
Jee Jee Li committed
511
512
        self.vision_dim = (self.vpm.embed_dim if self.version == (2, 0) else
                           self.vpm.embeddings.embed_dim)
Alphi's avatar
Alphi committed
513
        self.embed_dim = self.config.hidden_size
514
515
        self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
        self.resampler.to(device="cuda", dtype=param_dtype)
Alphi's avatar
Alphi committed
516
517
518
519
        self.lm_head = ParallelLMHead(config.vocab_size,
                                      config.hidden_size,
                                      quant_config=quant_config)
        self.logits_processor = LogitsProcessor(config.vocab_size)
520
521
        self.sampler = Sampler()

Jee Jee Li's avatar
Jee Jee Li committed
522
523
524
525
526
527
528
529
530
531
532
    def get_embedding(
        self,
        input_ids: torch.Tensor,
        image_inputs: Optional[MiniCPMVImageInputs],
    ) -> Tuple[torch.Tensor, torch.Tensor]:
        vlm_embedding: torch.Tensor = self.llm.embed_tokens(input_ids)
        if hasattr(self.config, "scale_emb"):
            vlm_embedding *= self.config.scale_emb

        if image_inputs is None:  # No image
            vision_hidden_states = torch.tensor([], device=input_ids.device)
533
        else:
Jee Jee Li's avatar
Jee Jee Li committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
            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]),
                )
550

Jee Jee Li's avatar
Jee Jee Li committed
551
        return vlm_embedding, vision_hidden_states
552

Jee Jee Li's avatar
Jee Jee Li committed
553
    def _get_image_bounds(self, input_ids: torch.Tensor) -> torch.Tensor:
554
555
        tokenizer = cached_get_tokenizer(self.config._name_or_path,
                                         trust_remote_code=True)
Jee Jee Li's avatar
Jee Jee Li committed
556
557
558
559
560
        start_cond = input_ids == tokenizer.im_start_id
        end_cond = input_ids == tokenizer.im_end_id
        if hasattr(tokenizer, "slice_start_id"):
            start_cond |= (input_ids == tokenizer.slice_start_id)
            end_cond |= (input_ids == tokenizer.slice_end_id)
Alphi's avatar
Alphi committed
561

Jee Jee Li's avatar
Jee Jee Li committed
562
        image_start_tokens, = torch.where(start_cond)
563
        image_start_tokens += 1
Jee Jee Li's avatar
Jee Jee Li committed
564
        image_end_tokens, = torch.where(end_cond)
Alphi's avatar
Alphi committed
565
        valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
Jee Jee Li's avatar
Jee Jee Li committed
566

567
        if valid_image_nums == 0:
Jee Jee Li's avatar
Jee Jee Li committed
568
569
570
            return torch.zeros((0, 2), device=input_ids.device)

        return torch.hstack([
571
572
573
574
            image_start_tokens[:valid_image_nums].unsqueeze(-1),
            image_end_tokens[:valid_image_nums].unsqueeze(-1),
        ])

Jee Jee Li's avatar
Jee Jee Li committed
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
    def _parse_and_validate_inputs(
        self,
        input_ids: torch.Tensor,
        **kwargs: object,
    ) -> Optional[MiniCPMVImageInputs]:
        pixel_values = kwargs.pop("pixel_values", [])
        tgt_sizes = kwargs.pop("tgt_sizes", [])

        if not isinstance(pixel_values, (torch.Tensor, list)):
            raise ValueError("Incorrect type of pixel values. "
                             f"Got type: {type(pixel_values)}")

        if not isinstance(tgt_sizes, (torch.Tensor, list)):
            raise ValueError("Incorrect type of target sizes. "
                             f"Got type: {type(tgt_sizes)}")

        if len(pixel_values) != len(tgt_sizes):
            raise ValueError("Inconsistent batch lengths, found: "
                             f"{len(pixel_values)} vs. {len(tgt_sizes)}")

        pixel_values_flat: List[torch.Tensor] = []
        tgt_sizes_flat: List[torch.Tensor] = []
597
598
599
600
601
602
603
604
        for pixel_b, tgt_b in zip(pixel_values, tgt_sizes):
            if len(pixel_b) != len(tgt_b):
                raise ValueError("Inconsistent N lengths, found: "
                                 f"{len(pixel_b)} vs {len(tgt_b)}")

            for pixel_n, tgt_n in zip(pixel_b, tgt_b):
                pixel_values_flat += pixel_n
                tgt_sizes_flat += tgt_n
Jee Jee Li's avatar
Jee Jee Li committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620

        # 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

        return MiniCPMVImageInputs(
            image_bounds=self._get_image_bounds(input_ids),
            pixel_values=pixel_values_flat,
            tgt_sizes=torch.stack(tgt_sizes_flat),
        )
621
622
623
624
625
626
627
628

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        kv_caches: List[torch.Tensor],
        attn_metadata: AttentionMetadata,
        intermediate_tensors: Optional[IntermediateTensors] = None,
Jee Jee Li's avatar
Jee Jee Li committed
629
630
631
632
633
634
635
636
637
638
639
640
641
642
        **kwargs: Any,
    ) -> torch.Tensor:
        image_inputs = self._parse_and_validate_inputs(input_ids, **kwargs)

        vlm_embeddings, _ = self.get_embedding(input_ids, image_inputs)

        output = self.llm(
            input_ids=None,
            positions=positions,
            kv_caches=kv_caches,
            attn_metadata=attn_metadata,
            intermediate_tensors=intermediate_tensors,
            inputs_embeds=vlm_embeddings,
        )
643
644
        return output

645
646
647
648
649
    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[torch.Tensor]:
Alphi's avatar
Alphi committed
650
651
652
        logits = self.logits_processor(self.lm_head, hidden_states,
                                       sampling_metadata)
        return logits
653
654
655
656
657
658

    def sample(
        self,
        logits: torch.Tensor,
        sampling_metadata: SamplingMetadata,
    ) -> Optional[SamplerOutput]:
Alphi's avatar
Alphi committed
659
        next_tokens = self.sampler(logits, sampling_metadata)
660
661
662
663
664
665
666
667
668
669
670
671
672
        return next_tokens

    def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
        stacked_params_mapping = [
            # (param_name, shard_name, shard_id)
            ("qkv_proj", "q_proj", "q"),
            ("qkv_proj", "k_proj", "k"),
            ("qkv_proj", "v_proj", "v"),
            ("gate_up_proj", "gate_proj", 0),
            ("gate_up_proj", "up_proj", 1),
        ]
        params_dict = dict(self.named_parameters())
        for name, loaded_weight in weights:
Alphi's avatar
Alphi committed
673
674
675
            for key_to_modify, new_key in _KEYS_TO_MODIFY_MAPPING.items():
                if key_to_modify in name:
                    name = name.replace(key_to_modify, new_key)
676
677
678
679
680
681
682
683
            if "rotary_emb.inv_freq" in name:
                continue
            if ("rotary_emb.cos_cached" in name
                    or "rotary_emb.sin_cached" in name):
                # Models trained using ColossalAI may include these tensors in
                # the checkpoint. Skip them.
                continue
            use_default_weight_loading = False
Jee Jee Li's avatar
Jee Jee Li committed
684
            if self.is_default_weight_loading(name):
685
686
                use_default_weight_loading = True
            else:
Jee Jee Li's avatar
Jee Jee Li committed
687
                for param_name, weight_name, shard_id in stacked_params_mapping:
688
689
690
691
692
693
694
695
696
697
698
699
700
                    if weight_name not in name:
                        continue
                    param = params_dict[name.replace(weight_name, param_name)]
                    weight_loader = param.weight_loader
                    weight_loader(param, loaded_weight, shard_id)
                    break
                else:
                    use_default_weight_loading = True
            if use_default_weight_loading:
                param = params_dict[name]
                weight_loader = getattr(param, "weight_loader",
                                        default_weight_loader)
                weight_loader(param, loaded_weight)
Jee Jee Li's avatar
Jee Jee Li committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731

    def init_llm(
        self,
        config: PretrainedConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ) -> nn.Module:
        raise NotImplementedError

    def init_vision_module(self) -> nn.Module:
        raise NotImplementedError

    def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
        raise NotImplementedError

    def get_vision_embedding(
        self,
        pixel_values: List[torch.Tensor],
        patch_attn_mask: Optional[torch.Tensor] = None,
        tgt_sizes: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        raise NotImplementedError

    def get_vision_hidden_states(self,
                                 data: MiniCPMVImageInputs) -> torch.Tensor:
        raise NotImplementedError

    def is_default_weight_loading(self, name: str) -> bool:
        raise NotImplementedError


732
class MiniCPMV2_0(MiniCPMVBaseModel):
Jee Jee Li's avatar
Jee Jee Li committed
733
734
735
736
737
738
739
740
741
742
743
744
745
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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904

    def __init__(
        self,
        config: PretrainedConfig,
        multimodal_config: MultiModalConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ):
        super().__init__(config, multimodal_config, cache_config, quant_config)
        assert self.version == (2, 0)

    def init_llm(
        self,
        config: PretrainedConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ) -> nn.Module:
        return MiniCPMModel(config,
                            cache_config=cache_config,
                            quant_config=quant_config)

    def init_vision_module(self) -> nn.Module:
        # TODO :refactor this vision model
        try:
            import timm
        except ImportError:
            raise ImportError("Please install timm==0.9.10") from ImportError
        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,
            )

        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

    def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
        with set_default_torch_dtype(torch.float16):
            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=True,
            )

        return resampler

    def get_vision_embedding(
        self,
        pixel_values: List[torch.Tensor],
        patch_attn_mask: Optional[torch.Tensor] = None,
        tgt_sizes: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        res = []
        dtype = self.vpm.pos_embed.data.dtype
        for pixel_value in pixel_values:
            H, W = pixel_value[0].shape[-2:]
            tgt_size = (
                math.ceil(H / self.vpm.patch_embed.patch_size[0]),
                math.ceil(W / self.vpm.patch_embed.patch_size[0]),
            )
            vision_embedding = self.vpm.forward_features(
                pixel_value.unsqueeze(0).type(dtype))
            if (hasattr(self.vpm, "num_prefix_tokens")
                    and self.vpm.num_prefix_tokens > 0):
                vision_embedding = vision_embedding[:, self.vpm.
                                                    num_prefix_tokens:]
            res.append(self.resampler(vision_embedding, tgt_size))
        return torch.vstack(res)

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

        return self.get_vision_embedding(pixel_values)

    def is_default_weight_loading(self, name: str) -> bool:
        return "resampler" in name or "vpm" in name


class MiniCPMV2_5(MiniCPMVBaseModel):

    def __init__(
        self,
        config: PretrainedConfig,
        multimodal_config: MultiModalConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ):
        super().__init__(config, multimodal_config, cache_config, quant_config)
        assert self.version == (2, 5)

    def init_llm(
        self,
        config: PretrainedConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ) -> nn.Module:
        return LlamaModel(config,
                          cache_config=cache_config,
                          quant_config=quant_config)

    def init_vision_module(self) -> nn.Module:
        model = Idefics2VisionTransformer(self.config.vision_config)
        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) -> nn.Module:
        with set_default_torch_dtype(torch.float16):
            resampler = Resampler2_5(
                num_queries=self.config.query_num,
                embed_dim=embed_dim,
                num_heads=embed_dim // 128,
                kv_dim=vision_dim,
            )
        return resampler

    def get_vision_embedding(
        self,
        pixel_values: List[torch.Tensor],
        patch_attn_mask: Optional[torch.Tensor] = None,
        tgt_sizes: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        vision_embedding = self.vpm(pixel_values,
                                    patch_attention_mask=patch_attn_mask)
        vision_embedding = self.resampler(vision_embedding, tgt_sizes)
        return vision_embedding

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

        device = self.vpm.embeddings.position_embedding.weight.device
        dtype = self.vpm.embeddings.position_embedding.weight.dtype
        all_pixel_values_lst = [
            i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
        ]

        max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
        assert isinstance(max_patches, int)

        all_pixel_values = torch.nn.utils.rnn.pad_sequence(
            all_pixel_values_lst, batch_first=True, padding_value=0.0)
        B, L, _ = all_pixel_values.shape
        all_pixel_values = all_pixel_values.permute(0, 2,
                                                    1).reshape(B, 3, -1, L)

        patch_attn_mask = torch.zeros((B, 1, max_patches),
                                      dtype=torch.bool,
                                      device=device)
        for i in range(B):
            patch_attn_mask[i, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True

        return self.get_vision_embedding(all_pixel_values.type(dtype),
                                         patch_attn_mask, tgt_sizes)

    def is_default_weight_loading(self, name: str) -> bool:
        return "resampler" in name


905
class MiniCPMV2_6(MiniCPMVBaseModel):
Jee Jee Li's avatar
Jee Jee Li committed
906
907
908
909
910
911
912
913
914

    def __init__(
        self,
        config: PretrainedConfig,
        multimodal_config: MultiModalConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ):
        super().__init__(config, multimodal_config, cache_config, quant_config)
915
        assert self.version == (2, 6)
Jee Jee Li's avatar
Jee Jee Li committed
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942

    def init_llm(
        self,
        config: PretrainedConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ) -> nn.Module:
        return Qwen2Model(config,
                          cache_config=cache_config,
                          quant_config=quant_config)

    def init_vision_module(self) -> nn.Module:
        # A custom version of SiglipVisionTransformer, won't work with TP
        from vllm.model_executor.models.na_vit import SiglipVisionTransformer

        if self.config._attn_implementation == "flash_attention_2":
            self.config.vision_config._attn_implementation = "flash_attention_2"
        else:
            # not support sdpa
            self.config.vision_config._attn_implementation = "eager"
        model = SiglipVisionTransformer(self.config.vision_config)
        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) -> nn.Module:
        with set_default_torch_dtype(torch.float16):
943
            # The resampler in 2.6 remains consistent with the one in 2.5.
Jee Jee Li's avatar
Jee Jee Li committed
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
            resampler = Resampler2_5(
                num_queries=self.config.query_num,
                embed_dim=embed_dim,
                num_heads=embed_dim // 128,
                kv_dim=vision_dim,
            )

        return resampler

    def get_vision_embedding(
        self,
        pixel_values: List[torch.Tensor],
        patch_attn_mask: Optional[torch.Tensor] = None,
        tgt_sizes: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        vision_embedding = self.vpm(
            pixel_values,
            patch_attention_mask=patch_attn_mask,
            tgt_sizes=tgt_sizes,
        ).last_hidden_state
        return vision_embedding

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

        device = self.vpm.embeddings.position_embedding.weight.device
        dtype = self.vpm.embeddings.position_embedding.weight.dtype
        all_pixel_values_lst = [
            i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
        ]

        max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
        assert isinstance(max_patches, int)

        all_pixel_values = torch.nn.utils.rnn.pad_sequence(
            all_pixel_values_lst, batch_first=True, padding_value=0.0)
        B, L, _ = all_pixel_values.shape
        all_pixel_values = all_pixel_values.permute(0, 2,
                                                    1).reshape(B, 3, -1, L)

        patch_attn_mask = torch.zeros((B, 1, max_patches),
                                      dtype=torch.bool,
                                      device=device)
        for i in range(B):
            patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
        vision_embedding = self.vpm(
            all_pixel_values.type(dtype),
            patch_attention_mask=patch_attn_mask,
            tgt_sizes=tgt_sizes,
        ).last_hidden_state

        return self.resampler(vision_embedding, tgt_sizes)

    def is_default_weight_loading(self, name: str) -> bool:
        return "resampler" in name or "vpm" in name


1003
1004
1005
1006
1007
1008
1009
_SUPPORT_VERSION = {
    (2, 0): MiniCPMV2_0,
    (2, 5): MiniCPMV2_5,
    (2, 6): MiniCPMV2_6
}


Jee Jee Li's avatar
Jee Jee Li committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
@MULTIMODAL_REGISTRY.register_image_input_mapper()
@MULTIMODAL_REGISTRY.register_max_image_tokens(get_max_minicpmv_image_tokens)
@INPUT_REGISTRY.register_dummy_data(dummy_data_for_minicpmv)
@INPUT_REGISTRY.register_input_processor(input_processor_for_minicpmv)
class MiniCPMV(MiniCPMVBaseModel):
    """
    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.
    """

    def __new__(
        cls,
        config: PretrainedConfig,
        multimodal_config: MultiModalConfig,
        cache_config: Optional[CacheConfig] = None,
        quant_config: Optional[QuantizationConfig] = None,
    ):
        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
1037
1038
1039
1040
        instance_class = _SUPPORT_VERSION.get(version, None)
        if instance_class is None:
            raise ValueError(
                "Currently, MiniCPMV only supports versions 2.0, 2.5, and 2.6")
Jee Jee Li's avatar
Jee Jee Li committed
1041
1042
        return instance_class(config, multimodal_config, cache_config,
                              quant_config)