step3_vl.py 38.8 KB
Newer Older
Song's avatar
Song committed
1
2
3
4
5
6
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import math
from collections.abc import Iterable, Mapping, Sequence
from itertools import product
from math import ceil, sqrt
7
from typing import Annotated, Any, Literal, TypeAlias
Song's avatar
Song committed
8
9
10
11
12
13
14
15
16
17
18

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from transformers import BatchFeature, PretrainedConfig, TensorType

from vllm.config import VllmConfig
19
from vllm.config.multimodal import BaseDummyOptions
Song's avatar
Song committed
20
21
from vllm.distributed import get_tensor_model_parallel_world_size
from vllm.model_executor.layers.activation import get_act_fn
22
from vllm.model_executor.layers.attention.mm_encoder_attention import MMEncoderAttention
23
from vllm.model_executor.layers.conv import Conv2dLayer
24
25
26
27
28
from vllm.model_executor.layers.linear import (
    ColumnParallelLinear,
    QKVParallelLinear,
    RowParallelLinear,
)
Song's avatar
Song committed
29
30
from vllm.model_executor.layers.quantization import QuantizationConfig
from vllm.multimodal import MULTIMODAL_REGISTRY
31
32
33
34
35
from vllm.multimodal.inputs import (
    MultiModalDataDict,
    MultiModalFieldConfig,
    MultiModalKwargsItems,
)
Song's avatar
Song committed
36
from vllm.multimodal.parse import ImageSize, MultiModalDataItems
37
from vllm.multimodal.processing import (
38
    BaseDummyInputsBuilder,
39
40
41
42
43
44
    BaseMultiModalProcessor,
    BaseProcessingInfo,
    PromptReplacement,
    PromptUpdate,
    PromptUpdateDetails,
)
Song's avatar
Song committed
45
from vllm.sequence import IntermediateTensors
46
from vllm.tokenizers import TokenizerLike
Song's avatar
Song committed
47
from vllm.transformers_utils.configs import Step3VisionEncoderConfig
48
from vllm.utils.tensor_schema import TensorSchema, TensorShape
Song's avatar
Song committed
49
50

from .interfaces import MultiModalEmbeddings, SupportsMultiModal, SupportsPP
51
52
53
54
55
56
from .utils import (
    AutoWeightsLoader,
    WeightsMapper,
    init_vllm_registered_model,
    maybe_prefix,
)
57
from .vision import run_dp_sharded_vision_model
Song's avatar
Song committed
58
59


60
61
62
63
64
65
66
67
68
69
70
71
class Step3VLImagePixelInputs(TensorSchema):
    """
    Dimensions:
        - bn: Batch size * number of images
        - c: Number of channels (3)
        - h: Height
        - w: Width
        - bnp: Batch size * number of images * number of patches
        - hp: Height of patch
        - wp: Width of patch
    """

Song's avatar
Song committed
72
    type: Literal["pixel_values"]
73
74
    pixel_values: Annotated[torch.Tensor, TensorShape("bn", 3, "h", "w")]
    patch_pixel_values: Annotated[
75
        torch.Tensor | None, TensorShape("bnp", 3, "hp", "wp")
76
77
78
    ]
    num_patches: Annotated[torch.Tensor, TensorShape("bn")]

Song's avatar
Song committed
79

80
81
82
83
84
85
86
class Step3VLImageEmbeddingInputs(TensorSchema):
    """
    Dimensions:
        - bn: Batch size * number of images
        - f: Image feature size
        - h: Hidden size (must match the hidden size of language model backbone)
    """
Song's avatar
Song committed
87

88
89
    type: Literal["image_embeds"] = "image_embeds"
    data: Annotated[torch.Tensor, TensorShape("bn", "f", "h")]
Song's avatar
Song committed
90
91


92
Step3VLImageInputs: TypeAlias = Step3VLImagePixelInputs | Step3VLImageEmbeddingInputs
Song's avatar
Song committed
93
94
95
96
97
98
99
100
101
102
103
104

ImageWithPatches = tuple[Image.Image, list[Image.Image], list[int] | None]

MAX_IMAGE_SIZE: int = 3024


class Step3VisionProcessor:
    def __init__(self, size, interpolation_mode="bicubic", patch_size=None):
        mean = [0.48145466, 0.4578275, 0.40821073]
        std = [0.26862954, 0.26130258, 0.27577711]
        patch_size = patch_size if patch_size is not None else size

105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        self.transform = transforms.Compose(
            [
                transforms.ToTensor(),
                transforms.Normalize(mean, std),
                transforms.Resize(
                    (size, size),
                    interpolation=InterpolationMode.BICUBIC
                    if interpolation_mode == "bicubic"
                    else InterpolationMode.BILINEAR,
                    antialias=True,
                ),
            ]
        )

        self.patch_transform = (
            transforms.Compose(
                [
                    transforms.ToTensor(),
                    transforms.Normalize(mean, std),
                    transforms.Resize(
                        (patch_size, patch_size),
                        interpolation=InterpolationMode.BICUBIC
                        if interpolation_mode == "bicubic"
                        else InterpolationMode.BILINEAR,
                        antialias=True,
                    ),
                ]
            )
            if patch_size is not None
            else None
        )
Song's avatar
Song committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

    def __call__(self, image, is_patch=False):
        if is_patch:
            return {"pixel_values": self.patch_transform(image).unsqueeze(0)}
        else:
            return {"pixel_values": self.transform(image).unsqueeze(0)}


class ImagePatcher:
    def determine_window_size(self, long: int, short: int) -> int:
        if long <= 728:
            return short if long / short > 1.5 else 0
        return min(short, 504) if long / short > 4 else 504

    def slide_window(
        self,
        width: int,
        height: int,
        sizes: list[tuple[int, int]],
        steps: list[tuple[int, int]],
        img_rate_thr: float = 0.6,
    ) -> tuple[list[tuple[int, int, int, int]], tuple[int, int]]:
        assert 1 >= img_rate_thr >= 0, "The `in_rate_thr` should lie in 0~1"
        windows = []
        # Sliding windows.
        for size, step in zip(sizes, steps):
            size_w, size_h = size
            step_w, step_h = step

165
            x_num = 1 if width <= size_w else ceil((width - size_w) / step_w + 1)
Song's avatar
Song committed
166
167
168
169
            x_start = [step_w * i for i in range(x_num)]
            if len(x_start) > 1 and x_start[-1] + size_w > width:
                x_start[-1] = width - size_w

170
            y_num = 1 if height <= size_h else ceil((height - size_h) / step_h + 1)
Song's avatar
Song committed
171
172
173
174
175
176
177
178
179
            y_start = [step_h * i for i in range(y_num)]
            if len(y_start) > 1 and y_start[-1] + size_h > height:
                y_start[-1] = height - size_h

            start = np.array(list(product(y_start, x_start)), dtype=int)
            start[:, [0, 1]] = start[:, [1, 0]]
            windows.append(np.concatenate([start, start + size], axis=1))
        windows = np.concatenate(windows, axis=0)

180
181
182
183
        return [
            (int(box[0]), int(box[1]), int(box[2] - box[0]), int(box[3] - box[1]))
            for box in windows
        ], (x_num, y_num)
Song's avatar
Song committed
184
185
186
187
188
189
190
191
192
193

    def square_pad(self, img: Image.Image) -> Image.Image:
        w, h = img.size
        if w == h:
            return img
        size = max(w, h)
        padded = Image.new(img.mode, (size, size), 0)
        padded.paste(img, (0, 0))
        return padded

194
195
196
    def get_image_size_for_padding(
        self, img_width: int, img_height: int
    ) -> tuple[int, int]:
Song's avatar
Song committed
197
198
199
200
201
202
        ratio = img_width / img_height
        if min(img_height, img_width) < 32 and (ratio > 4 or ratio < 1 / 4):
            new_size = max(img_height, img_width)
            return new_size, new_size
        return img_width, img_height

203
204
205
    def get_image_size_for_preprocess(
        self, img_width: int, img_height: int
    ) -> tuple[int, int]:
Song's avatar
Song committed
206
207
208
209
210
211
        if max(img_height, img_width) > MAX_IMAGE_SIZE:
            scale_factor = MAX_IMAGE_SIZE / max(img_height, img_width)
            img_width = int(img_width * scale_factor)
            img_height = int(img_height * scale_factor)
        return img_width, img_height

212
213
214
    def get_image_size_for_crop(
        self, img_width: int, img_height: int, window_size: int
    ):
Song's avatar
Song committed
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
        w_ratio = img_width / window_size
        h_ratio = img_height / window_size

        if w_ratio < 1:
            width_new = img_width
        else:
            decimal_w = w_ratio - img_width // window_size
            w_ratio = int(w_ratio) + 1 if decimal_w > 0.2 else int(w_ratio)
            width_new = window_size * w_ratio
        if h_ratio < 1:
            height_new = img_height
        else:
            decimal_h = h_ratio - img_height // window_size
            h_ratio = int(h_ratio) + 1 if decimal_h > 0.2 else int(h_ratio)
            height_new = window_size * h_ratio
        return int(width_new), int(height_new)

    def patch_crop(self, img: Image.Image, i: int, j: int, th: int, tw: int):
        target = img.crop((j, i, j + tw, i + th))
        return target

236
237
    def get_num_patches(self, img_width: int, img_height: int) -> tuple[int, int]:
        img_width, img_height = self.get_image_size_for_padding(img_width, img_height)
Song's avatar
Song committed
238
        img_width, img_height = self.get_image_size_for_preprocess(
239
240
241
242
243
            img_width, img_height
        )
        window_size = self.determine_window_size(
            max(img_height, img_width), min(img_height, img_width)
        )
Song's avatar
Song committed
244
245
246
247
        if window_size == 0:
            return 0, 0
        else:
            img_width, img_height = self.get_image_size_for_crop(
248
249
                img_width, img_height, window_size
            )
Song's avatar
Song committed
250
            center_list, (x_num, y_num) = self.slide_window(
251
252
253
254
255
                img_width,
                img_height,
                [(window_size, window_size)],
                [(window_size, window_size)],
            )
Song's avatar
Song committed
256
257
258
259
260
261
262
263
264
265
            full_rows = (len(center_list) - 1) // x_num + 1
            if len(center_list) > 0 and len(center_list) % x_num == 0:
                full_rows -= 1
            return len(center_list), full_rows

    def __call__(
        self, img: Image.Image
    ) -> tuple[Image.Image, list[Image.Image], list[bool] | None]:
        img_width, img_height = img.size
        new_img_width, new_img_height = self.get_image_size_for_padding(
266
267
            img_width, img_height
        )
Song's avatar
Song committed
268
269
270
271
272
        if new_img_width != img_width or new_img_height != img_height:
            img = self.square_pad(img)
            img_width, img_height = img.size

        new_img_width, new_img_height = self.get_image_size_for_preprocess(
273
274
275
            img_width, img_height
        )
        img = img.resize((new_img_width, new_img_height), Image.Resampling.BILINEAR)
Song's avatar
Song committed
276
        window_size = self.determine_window_size(
277
278
            max(new_img_height, new_img_width), min(new_img_height, new_img_width)
        )
Song's avatar
Song committed
279
280
281
282
283

        if window_size == 0:
            return img, [], None
        else:
            new_img_width, new_img_height = self.get_image_size_for_crop(
284
285
                new_img_width, new_img_height, window_size
            )
Song's avatar
Song committed
286
            if (new_img_width, new_img_height) != (img_width, img_height):
287
288
289
                img_for_crop = img.resize(
                    (new_img_width, new_img_height), Image.Resampling.BILINEAR
                )
Song's avatar
Song committed
290
291
292
293
294
295
            else:
                img_for_crop = img

            patches = []
            newlines = []
            center_list, (x_num, y_num) = self.slide_window(
296
297
298
299
300
                new_img_width,
                new_img_height,
                [(window_size, window_size)],
                [(window_size, window_size)],
            )
Song's avatar
Song committed
301
302
            for patch_id, center_lf_point in enumerate(center_list):
                x, y, patch_w, patch_h = center_lf_point
303
                big_patch = self.patch_crop(img_for_crop, y, x, patch_h, patch_w)
Song's avatar
Song committed
304
305
306
307
308
309
310
                patches.append(big_patch)
                if (patch_id + 1) % x_num == 0:
                    newlines.append(patch_id)

            if newlines and newlines[-1] == len(patches) - 1:
                newlines.pop()

311
312
313
314
315
316
317
            return (
                img,
                patches,
                [i in newlines for i in range(len(patches))]
                if len(patches) > 0
                else None,
            )
Song's avatar
Song committed
318
319
320
321
322
323


class Step3VLProcessor:
    def __init__(
        self,
        config: PretrainedConfig,
324
        tokenizer: TokenizerLike,
Song's avatar
Song committed
325
326
327
328
329
330
331
332
    ) -> None:
        super().__init__()

        self.config = config
        self.tokenizer = tokenizer

        self.image_size = 728
        self.patch_size = 504
333
334
335
        self.image_preprocessor = Step3VisionProcessor(
            self.image_size, "bilinear", self.patch_size
        )
Song's avatar
Song committed
336
337
338
339

        self.num_image_feature_size = 169
        self.num_patch_feature_size = 81
        self.image_token = "<im_patch>"
340
341
        self.image_feature_placeholder = self.image_token * self.num_image_feature_size
        self.patch_feature_placeholder = self.image_token * self.num_patch_feature_size
Song's avatar
Song committed
342
343
344
345
346
347
348
349

        self.patcher = ImagePatcher()

    @property
    def image_token_id(self) -> int:
        return self.tokenizer.get_vocab()[self.image_token]

    def get_num_image_tokens(self, img_width: int, img_height: int) -> int:
350
        num_patches, num_newlines = self.patcher.get_num_patches(img_width, img_height)
Song's avatar
Song committed
351

352
353
354
355
356
357
        return (
            num_patches * (self.num_patch_feature_size + 2)
            + self.num_image_feature_size
            + 2
            + num_newlines
        )
Song's avatar
Song committed
358

359
    def _split_images(self, images: list[Image.Image]) -> list[ImageWithPatches]:
Song's avatar
Song committed
360
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
        result = []
        for img in images:
            result.append(self.patcher(img))
        return result

    def _convert_images_to_pixel_values(
        self,
        images: list[Image.Image],
        is_patch: bool = False,
    ) -> list[torch.Tensor]:
        return [
            self.image_preprocessor(img, is_patch=is_patch)["pixel_values"]
            for img in images
        ]

    def _get_patch_repl(
        self,
        num_patches: int,
        patch_newline_mask: list[bool] | None,
    ) -> tuple[str, list[int]]:
        text = ""
        token_ids = []
        for i in range(num_patches):
            assert len(patch_newline_mask) == num_patches
            text += f"<patch_start>{self.patch_feature_placeholder}<patch_end>"
            token_ids.extend(
386
387
388
389
                [self.tokenizer.convert_tokens_to_ids("<patch_start>")]
                + [self.image_token_id] * self.num_patch_feature_size
                + [self.tokenizer.convert_tokens_to_ids("<patch_end>")]
            )
Song's avatar
Song committed
390
391
392
            if patch_newline_mask and patch_newline_mask[i]:
                text += "<patch_newline>"
                token_ids.append(
393
394
                    self.tokenizer.convert_tokens_to_ids("<patch_newline>")
                )
Song's avatar
Song committed
395
396
397
398
399
400
401
        return text, token_ids

    def _get_image_repl(
        self,
        num_images: int,
    ) -> tuple[str, list[int]]:
        text = f"<im_start>{self.image_feature_placeholder}<im_end>"
402
403
404
405
406
        token_ids = (
            [self.tokenizer.convert_tokens_to_ids("<im_start>")]
            + [self.image_token_id] * self.num_image_feature_size
            + [self.tokenizer.convert_tokens_to_ids("<im_end>")]
        )
Song's avatar
Song committed
407
408
409
410
411
412
        return text * num_images, token_ids * num_images

    def _get_image_repl_features(
        self,
        num_images: int,
        num_patches: int,
413
        patch_new_line_idx: list[bool] | None,
Song's avatar
Song committed
414
415
416
    ) -> tuple[str, list[int]]:
        if num_patches > 0:
            patch_repl, patch_repl_ids = self._get_patch_repl(
417
418
                num_patches, patch_new_line_idx
            )
Song's avatar
Song committed
419
420
421
422
423
424
        else:
            patch_repl = ""
            patch_repl_ids = []
        image_repl, image_repl_ids = self._get_image_repl(num_images)
        return patch_repl + image_repl, patch_repl_ids + image_repl_ids

425
    def replace_placeholder(self, text: str, placeholder: str, repls: list[str]) -> str:
Song's avatar
Song committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
        parts = text.split(placeholder)

        if len(parts) - 1 != len(repls):
            raise ValueError(
                "The number of placeholders does not match the number of replacements."  # noqa: E501
            )

        result = [parts[0]]
        for i, repl in enumerate(repls):
            result.append(repl)
            result.append(parts[i + 1])

        return "".join(result)

    def __call__(
        self,
442
443
444
        text: str | list[str] | None = None,
        images: Image.Image | list[Image.Image] | None = None,
        return_tensors: str | TensorType | None = None,
Song's avatar
Song committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
    ) -> BatchFeature:
        if text is None:
            text = []
        if not isinstance(text, list):
            text = [text]
        if images is None:
            images = []
        if not isinstance(images, list):
            images = [images]

        if len(images) == 0:
            image_inputs = {}
            text_inputs = self.tokenizer(text)
        else:
            splitted_images_data = self._split_images(images)
            pixel_values_lst = []
            patch_pixel_values_lst = []
            patch_newline_mask_lst = []
            image_repl_str_lst = []
            image_repl_ids_lst = []
            num_patches = []
            for raw_img, img_patches, patch_newline_mask in splitted_images_data:  # noqa: E501
467
                pixel_values_lst.extend(self._convert_images_to_pixel_values([raw_img]))
Song's avatar
Song committed
468
469
470

                if len(img_patches) > 0:
                    patch_pixel_values_lst.extend(
471
472
                        self._convert_images_to_pixel_values(img_patches, is_patch=True)
                    )
Song's avatar
Song committed
473
474
475
                num_patches.append(len(img_patches))

                image_repl_str, image_repl_ids = self._get_image_repl_features(
476
477
                    1, len(img_patches), patch_newline_mask
                )
Song's avatar
Song committed
478
479
480
481
482
483
484
485
486
487
488
                image_repl_str_lst.append(image_repl_str)
                image_repl_ids_lst.extend(image_repl_ids)

                if patch_newline_mask is not None:
                    patch_newline_mask_lst.extend(patch_newline_mask)

            image_inputs = {
                "pixel_values": torch.cat(pixel_values_lst),
                "num_patches": num_patches,
            }
            if patch_pixel_values_lst:
489
                image_inputs["patch_pixel_values"] = torch.cat(patch_pixel_values_lst)
Song's avatar
Song committed
490
491
            if patch_newline_mask_lst:
                image_inputs["patch_newline_mask"] = torch.tensor(
492
493
                    patch_newline_mask_lst, dtype=torch.bool
                )
Song's avatar
Song committed
494
495

            text = [
496
497
                self.replace_placeholder(t, self.image_token, image_repl_str_lst)
                for t in text
Song's avatar
Song committed
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
            ]
            text_inputs = self.tokenizer(text)

        return BatchFeature(
            {
                **text_inputs,
                **image_inputs,
            },
            tensor_type=return_tensors,
        )


class Step3VLProcessingInfo(BaseProcessingInfo):
    def get_hf_processor(self) -> Step3VLProcessor:
        return Step3VLProcessor(
            self.get_hf_config(),
            self.get_tokenizer(),
        )

517
    def get_supported_mm_limits(self) -> Mapping[str, int | None]:
Song's avatar
Song committed
518
519
520
521
522
523
        return {"image": None}

    def get_max_image_tokens(self) -> int:
        hf_processor = self.get_hf_processor()
        return hf_processor.get_num_image_tokens(
            self.get_image_size_with_most_features().width,
524
525
            self.get_image_size_with_most_features().height,
        )
Song's avatar
Song committed
526
527
528
529
530
531
532
533
534
535
536
537
538

    def get_mm_max_tokens_per_item(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> Mapping[str, int]:
        return {"image": self.get_max_image_tokens()}

    def get_image_size_with_most_features(self) -> ImageSize:
        return ImageSize(3024, 3024)

    def get_num_mm_tokens(self, mm_data: MultiModalDataDict) -> int:
        if len(mm_data) != 1 or "image" not in mm_data:
539
            raise ValueError("mm_data could only contain one key 'image' for steo1o")
Song's avatar
Song committed
540
541
542
543
544

        image_data = mm_data["image"]
        if not isinstance(image_data, (list, tuple)):
            image_data = [image_data]

545
546
547
548
        return sum(
            self.get_hf_processor().get_num_image_tokens(img.width, img.height)
            for img in image_data
        )
Song's avatar
Song committed
549
550
551
552
553
554
555
556
557
558
559


class Step3VLDummyInputsBuilder(BaseDummyInputsBuilder[Step3VLProcessingInfo]):
    def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
        num_images = mm_counts.get("image", 0)
        return "<im_patch>" * num_images

    def get_dummy_mm_data(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
560
        mm_options: Mapping[str, BaseDummyOptions] | None = None,
Song's avatar
Song committed
561
    ) -> MultiModalDataDict:
562
        target_width, target_height = self.info.get_image_size_with_most_features()
Song's avatar
Song committed
563
564
        num_images = mm_counts.get("image", 0)

565
566
        image_overrides = mm_options.get("image") if mm_options else None

Song's avatar
Song committed
567
        return {
568
569
570
571
572
573
            "image": self._get_dummy_images(
                width=target_width,
                height=target_height,
                num_images=num_images,
                overrides=image_overrides,
            )
Song's avatar
Song committed
574
575
576
        }


577
class Step3VLMultiModalProcessor(BaseMultiModalProcessor[Step3VLProcessingInfo]):
Song's avatar
Song committed
578
579
580
581
    def _get_prompt_updates(
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, Any],
582
        out_mm_kwargs: MultiModalKwargsItems,
Song's avatar
Song committed
583
584
585
586
587
    ) -> Sequence[PromptUpdate]:
        hf_processor = self.info.get_hf_processor(**hf_processor_mm_kwargs)
        image_placeholder_token_id = hf_processor.image_token_id

        def get_replacement_step1o(item_idx: int):
588
589
            out_item = out_mm_kwargs["image"][item_idx]
            num_patches = int(out_item["num_patches"].data)
Song's avatar
Song committed
590
            if num_patches > 0:
591
                patch_newline_mask = out_item["patch_newline_mask"].data
Song's avatar
Song committed
592
                image_repl_ids = hf_processor._get_image_repl_features(
593
594
                    1, num_patches, patch_newline_mask.tolist()
                )[1]
Song's avatar
Song committed
595
            else:
596
                image_repl_ids = hf_processor._get_image_repl_features(1, 0, None)[1]
Song's avatar
Song committed
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
            return PromptUpdateDetails.select_token_id(
                seq=image_repl_ids,
                embed_token_id=image_placeholder_token_id,
            )

        return [
            PromptReplacement(
                modality="image",
                target=[image_placeholder_token_id],
                replacement=get_replacement_step1o,
            )
        ]

    def _get_mm_fields_config(
        self,
        hf_inputs: BatchFeature,
        hf_processor_mm_kwargs: Mapping[str, object],
    ) -> Mapping[str, MultiModalFieldConfig]:
        num_patches = hf_inputs.get("num_patches", torch.empty(0))

        return dict(
            pixel_values=MultiModalFieldConfig.batched("image"),
            patch_pixel_values=MultiModalFieldConfig.flat_from_sizes(
620
621
                "image", num_patches
            ),
Song's avatar
Song committed
622
623
            num_patches=MultiModalFieldConfig.batched("image"),
            patch_newline_mask=MultiModalFieldConfig.flat_from_sizes(
624
625
                "image", num_patches
            ),
Song's avatar
Song committed
626
627
628
629
630
631
632
633
634
635
636
637
638
        )


def get_abs_pos(abs_pos, tgt_size):
    dim = abs_pos.size(-1)
    abs_pos_new = abs_pos.squeeze(0)
    cls_token, old_pos_embed = abs_pos_new[:1], abs_pos_new[1:]

    src_size = int(math.sqrt(abs_pos_new.shape[0] - 1))
    tgt_size = int(math.sqrt(tgt_size))
    dtype = abs_pos.dtype

    if src_size != tgt_size:
639
640
641
642
643
        old_pos_embed = (
            old_pos_embed.view(1, src_size, src_size, dim)
            .permute(0, 3, 1, 2)
            .contiguous()
        )
Song's avatar
Song committed
644
645
646
647
        old_pos_embed = old_pos_embed.to(torch.float32)
        new_pos_embed = F.interpolate(
            old_pos_embed,
            size=(tgt_size, tgt_size),
648
            mode="bicubic",
Song's avatar
Song committed
649
650
651
652
653
654
            antialias=True,
            align_corners=False,
        ).to(dtype)
        new_pos_embed = new_pos_embed.permute(0, 2, 3, 1)
        new_pos_embed = new_pos_embed.view(tgt_size * tgt_size, dim)
        vision_pos_embed = torch.cat([cls_token, new_pos_embed], dim=0)
655
        vision_pos_embed = vision_pos_embed.view(1, tgt_size * tgt_size + 1, dim)
Song's avatar
Song committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
        return vision_pos_embed
    else:
        return abs_pos


class Step3VisionEmbeddings(nn.Module):
    def __init__(self, config: Step3VisionEncoderConfig):
        super().__init__()
        self.config = config
        self.embed_dim = config.hidden_size
        self.image_size = config.image_size
        self.patch_size = config.patch_size

        self.class_embedding = nn.Parameter(torch.randn(1, self.embed_dim))

671
        self.patch_embedding = Conv2dLayer(
Song's avatar
Song committed
672
673
674
675
676
677
678
            in_channels=config.num_channels,
            out_channels=self.embed_dim,
            kernel_size=self.patch_size,
            stride=self.patch_size,
            bias=True,
        )

679
        self.num_patches = (self.image_size // self.patch_size) ** 2
Song's avatar
Song committed
680
681
        self.pad_tp_size = 4  # hard code for padding
        # To load the pretrained weights, we still use P+1 as the seqlen
682
683
684
685
686
687
688
689
        self.position_embedding = torch.nn.Embedding(
            self.num_patches + 1, self.embed_dim
        )
        self.register_buffer(
            "position_ids",
            torch.arange(self.num_patches + 1).expand((1, -1)),
            persistent=False,
        )
Song's avatar
Song committed
690
691
692
693

    def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
        batch_size = pixel_values.shape[0]
        patch_embeds = self.patch_embedding(
694
695
            pixel_values
        )  # shape = [*, width, grid, grid]
Song's avatar
Song committed
696
697
698
699
700
701
        patch_embeds = patch_embeds.flatten(2).transpose(1, 2)

        # pad
        class_embeds = self.class_embedding.expand(batch_size, 1, -1)
        embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
        embeddings = embeddings + get_abs_pos(
702
703
704
705
706
707
708
709
710
            self.position_embedding(self.position_ids), patch_embeds.size(1)
        )
        embeddings = torch.cat(
            [
                embeddings[:, 0, :].unsqueeze(1).repeat(1, self.pad_tp_size - 1, 1),
                embeddings,
            ],
            dim=1,
        )
Song's avatar
Song committed
711
712
713
714
715
716
        return embeddings


class Step3VisionAttention(nn.Module):
    """Multi-headed attention from 'Attention Is All You Need' paper"""

717
718
719
    def __init__(
        self,
        config,
720
        quant_config: QuantizationConfig | None = None,
721
722
723
        prefix: str = "",
        use_data_parallel: bool = False,
    ):
Song's avatar
Song committed
724
725
726
727
728
729
730
731
        super().__init__()
        self.config = config
        self.embed_dim = config.hidden_size
        self.total_num_heads = config.num_attention_heads
        self.head_dim = self.embed_dim // self.total_num_heads

        self.scale = self.head_dim**-0.5

732
        tp_size = 1 if use_data_parallel else get_tensor_model_parallel_world_size()
Song's avatar
Song committed
733
734
        assert self.total_num_heads % tp_size == 0
        self.num_heads = self.total_num_heads // tp_size
735
736
737

        self.q_size = self.num_heads * self.head_dim

738
739
740
741
742
743
744
745
746
        self.qkv_proj = QKVParallelLinear(
            self.embed_dim,
            self.head_dim,
            self.total_num_heads,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.qkv_proj",
            disable_tp=use_data_parallel,
        )
747
748
749
750
751
752
753
754
        self.out_proj = RowParallelLinear(
            self.embed_dim,
            self.embed_dim,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.out_proj",
            disable_tp=use_data_parallel,
        )
Song's avatar
Song committed
755

756
757
        # Use unified MMEncoderAttention with automatic backend selection
        self.attn = MMEncoderAttention(self.num_heads, self.head_dim, self.scale)
Song's avatar
Song committed
758
759
760
761
762
763
764
765
766
767
768

    def forward(
        self,
        hidden_states: torch.Tensor,
    ):
        """Input shape: Batch x Time x Channel"""
        bsz, tgt_len, _ = hidden_states.size()

        # get query proj
        qkv, _ = self.qkv_proj(hidden_states)
        q, k, v = qkv.chunk(chunks=3, dim=-1)
769

770
        # Use unified MMEncoderAttention with automatic backend selection
771
        attn_output = self.attn(q, k, v)
Song's avatar
Song committed
772
773
774
775
776
777
778

        attn_output, _ = self.out_proj(attn_output)

        return attn_output


class Step3VisionMLP(nn.Module):
779
780
781
    def __init__(
        self,
        config,
782
        quant_config: QuantizationConfig | None = None,
783
784
785
        prefix: str = "",
        use_data_parallel: bool = False,
    ):
Song's avatar
Song committed
786
787
788
        super().__init__()
        self.config = config
        self.activation_fn = get_act_fn(config.hidden_act)
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
        self.fc1 = ColumnParallelLinear(
            config.hidden_size,
            config.intermediate_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.fc1",
            disable_tp=use_data_parallel,
        )
        self.fc2 = RowParallelLinear(
            config.intermediate_size,
            config.hidden_size,
            bias=True,
            quant_config=quant_config,
            prefix=f"{prefix}.fc2",
            disable_tp=use_data_parallel,
        )
Song's avatar
Song committed
805
806
807
808
809
810
811
812
813

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states, _ = self.fc1(hidden_states)
        hidden_states = self.activation_fn(hidden_states)
        hidden_states, _ = self.fc2(hidden_states)
        return hidden_states


class Step3VisionEncoderLayer(nn.Module):
814
815
816
    def __init__(
        self,
        config: Step3VisionEncoderConfig,
817
        quant_config: QuantizationConfig | None = None,
818
819
820
        prefix: str = "",
        use_data_parallel: bool = False,
    ):
Song's avatar
Song committed
821
        super().__init__()
822
        self.use_data_parallel = use_data_parallel
Song's avatar
Song committed
823
        self.embed_dim = config.hidden_size
824
825
826
827
        self.self_attn = Step3VisionAttention(
            config,
            quant_config,
            prefix=f"{prefix}.self_attn",
828
829
830
831
832
833
834
835
836
837
            use_data_parallel=self.use_data_parallel,
        )
        self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
        self.mlp = Step3VisionMLP(
            config,
            quant_config,
            prefix=f"{prefix}.mlp",
            use_data_parallel=self.use_data_parallel,
        )
        self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
Song's avatar
Song committed
838
839
840
841
842

    def forward(
        self,
        hidden_states: torch.Tensor,
    ) -> torch.FloatTensor:
843
844
        hidden_states = hidden_states + self.layer_norm1(self.self_attn(hidden_states))
        hidden_states = hidden_states + self.layer_norm2(self.mlp(hidden_states))
Song's avatar
Song committed
845
846
847
848
        return hidden_states


class Step3VisionEncoder(nn.Module):
849
850
851
    def __init__(
        self,
        config: Step3VisionEncoderConfig,
852
        quant_config: QuantizationConfig | None = None,
853
854
855
        prefix: str = "",
        use_data_parallel: bool = False,
    ):
Song's avatar
Song committed
856
857
        super().__init__()
        self.config = config
858
        self.use_data_parallel = use_data_parallel
859
860
861
862
863
864
865
866
867
868
869
        self.layers = nn.ModuleList(
            [
                Step3VisionEncoderLayer(
                    config,
                    quant_config,
                    prefix=f"{prefix}.layers.{i}",
                    use_data_parallel=self.use_data_parallel,
                )
                for i in range(config.num_hidden_layers)
            ]
        )
Song's avatar
Song committed
870
871
872
873
874
875
876
877
878
879
880
881

    def forward(
        self,
        inputs_embeds,
    ):
        hidden_states = inputs_embeds
        for encoder_layer in self.layers:
            hidden_states = encoder_layer(hidden_states)
        return hidden_states


class Step3VisionTransformer(nn.Module):
882
883
884
    def __init__(
        self,
        config: Step3VisionEncoderConfig,
885
        quant_config: QuantizationConfig | None = None,
886
887
888
        prefix: str = "",
        use_data_parallel: bool = False,
    ):
Song's avatar
Song committed
889
890
        super().__init__()
        self.config = config
891
        self.use_data_parallel = use_data_parallel
Song's avatar
Song committed
892
893
        self.image_size = config.image_size
        self.embeddings = Step3VisionEmbeddings(config)
894
895
896
897
        self.transformer = Step3VisionEncoder(
            config,
            quant_config,
            prefix=f"{prefix}.transformer",
898
899
            use_data_parallel=self.use_data_parallel,
        )
Song's avatar
Song committed
900
901
902
903
904
905

    def forward(
        self,
        pixel_values: torch.Tensor,
    ):
        hidden_states = self.embeddings(pixel_values)
906
        if self.use_data_parallel:
907
            hidden_states = run_dp_sharded_vision_model(hidden_states, self.transformer)
908
909
        else:
            hidden_states = self.transformer(inputs_embeds=hidden_states)
Song's avatar
Song committed
910
911
912
        return hidden_states


913
914
915
916
917
918
919
920
921
922
923
924
@MULTIMODAL_REGISTRY.register_processor(
    Step3VLMultiModalProcessor,
    info=Step3VLProcessingInfo,
    dummy_inputs=Step3VLDummyInputsBuilder,
)
class Step3VLForConditionalGeneration(nn.Module, SupportsMultiModal, SupportsPP):
    hf_to_vllm_mapper = WeightsMapper(
        orig_to_new_prefix={
            "model.": "language_model.model.",
            "lm_head.": "language_model.lm_head.",
        }
    )
Song's avatar
Song committed
925

926
927
    supports_encoder_tp_data = True

Song's avatar
Song committed
928
    @classmethod
929
    def get_placeholder_str(cls, modality: str, i: int) -> str | None:
Song's avatar
Song committed
930
931
932
933
934
935
936
937
938
939
940
941
942
        if modality.startswith("image"):
            return "<im_patch>"

        raise ValueError("Only image modality is supported")

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
        super().__init__()

        config = vllm_config.model_config.hf_config
        multimodal_config = vllm_config.model_config.multimodal_config

        self.config = config
        self.multimodal_config = multimodal_config
943
        self.use_data_parallel = multimodal_config.mm_encoder_tp_mode == "data"
Song's avatar
Song committed
944

945
        with self._mark_tower_model(vllm_config, "image"):
946
947
948
949
            self.vision_model = Step3VisionTransformer(
                config.vision_config,
                None,
                prefix=maybe_prefix(prefix, "vision_model"),
950
951
                use_data_parallel=self.use_data_parallel,
            )
952
            self.vit_downsampler = Conv2dLayer(
953
954
955
                config.vision_config.hidden_size,
                config.vision_config.output_hidden_size,
                kernel_size=2,
956
957
                stride=config.understand_projector_stride,
            )
958
            self.vit_downsampler2 = Conv2dLayer(
959
960
961
962
963
964
965
966
967
968
969
                config.vision_config.output_hidden_size,
                config.vision_config.output_hidden_size * 2,
                kernel_size=3,
                stride=2,
                padding=1,
            )
            self.vit_large_projector = nn.Linear(
                config.vision_config.output_hidden_size * 2,
                config.hidden_size,
                bias=config.projector_bias,
            )
970
971
972
973
974
975
976

        with self._mark_language_model(vllm_config):
            self.language_model = init_vllm_registered_model(
                vllm_config=vllm_config,
                hf_config=config.text_config,
                prefix=maybe_prefix(prefix, "language_model"),
            )
Song's avatar
Song committed
977
978

        self.make_empty_intermediate_tensors = (
979
980
            self.language_model.make_empty_intermediate_tensors
        )
Song's avatar
Song committed
981
982
983
984
985
986
987
988
989
990

    @property
    def device(self):
        return next(self.parameters()).device

    @property
    def dtype(self):
        return next(self.parameters()).dtype

    def _parse_and_validate_image_input(
991
        self, **kwargs: object
992
    ) -> Step3VLImageInputs | None:
Song's avatar
Song committed
993
994
995
996
997
998
999
1000
1001
1002
1003
        pixel_values = kwargs.pop("pixel_values", None)
        patch_pixel_values = kwargs.pop("patch_pixel_values", None)
        num_patches = kwargs.pop("num_patches", None)
        image_embeds = kwargs.pop("image_embeds", None)

        if pixel_values is None and image_embeds is None:
            return None

        if pixel_values is not None:
            return Step3VLImagePixelInputs(
                type="pixel_values",
1004
1005
                pixel_values=pixel_values.to(self.dtype),
                patch_pixel_values=patch_pixel_values.to(self.dtype)
1006
1007
                if patch_pixel_values is not None
                else None,
Song's avatar
Song committed
1008
1009
1010
1011
1012
1013
                num_patches=num_patches,
            )

        if image_embeds is not None:
            return Step3VLImageEmbeddingInputs(
                type="image_embeds",
1014
                image_embeds=image_embeds.to(self.dtype),
Song's avatar
Song committed
1015
            )
1016
1017

        raise AssertionError("This line should be unreachable.")
Song's avatar
Song committed
1018

1019
    def _process_image_features(self, image_features: torch.Tensor) -> torch.Tensor:
Song's avatar
Song committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
        B, P = image_features.shape[:2]
        HW = int(sqrt(P))
        image_features = image_features.permute(0, 2, 1).view(B, -1, HW, HW)
        image_features = self.vit_downsampler(image_features)
        image_features = self.vit_downsampler2(image_features)
        n_dim = image_features.size(1)
        image_features = image_features.view(B, n_dim, -1).permute(0, 2, 1)
        image_features = self.vit_large_projector(image_features)
        return image_features

1030
    def _get_vision_model_output(self, input_tensor: torch.Tensor) -> torch.Tensor:
Song's avatar
Song committed
1031
1032
1033
        return self.vision_model(input_tensor)[:, 4:]

    def _process_image_input(
1034
1035
        self, image_input: Step3VLImageInputs
    ) -> tuple[torch.Tensor, ...]:
Song's avatar
Song committed
1036
1037
1038
        if image_input["type"] == "image_embeds":
            image_features = image_input["image_embeds"]
        else:
1039
1040
1041
1042
1043
1044
            image_features = self._get_vision_model_output(image_input["pixel_values"])
            patch_image_features = (
                self._get_vision_model_output(image_input["patch_pixel_values"])
                if image_input["patch_pixel_values"] is not None
                else None
            )
Song's avatar
Song committed
1045
1046
1047
            num_patches = image_input["num_patches"]

        image_features = self._process_image_features(image_features)
1048
1049
1050
1051
1052
        patch_image_features = (
            self._process_image_features(patch_image_features)
            if patch_image_features is not None
            else None
        )
Song's avatar
Song committed
1053
1054
1055
1056
1057
1058
1059

        merged_image_features = []
        cur_patch_idx = 0
        for i, num_patch in enumerate(num_patches):
            cur_feature = []
            if num_patch > 0:
                patch_slice = patch_image_features[
1060
1061
                    cur_patch_idx : cur_patch_idx + num_patch
                ]
Song's avatar
Song committed
1062
                cur_feature.append(patch_slice.view(-1, patch_slice.shape[-1]))
1063
            cur_feature.append(image_features[i].view(-1, image_features.shape[-1]))
Song's avatar
Song committed
1064
1065
            cur_patch_idx += num_patch
            merged_image_features.append(
1066
1067
                torch.cat(cur_feature) if len(cur_feature) > 1 else cur_feature[0]
            )
Song's avatar
Song committed
1068
1069
        return merged_image_features

1070
    def embed_multimodal(self, **kwargs) -> MultiModalEmbeddings:
Song's avatar
Song committed
1071
1072
        image_input = self._parse_and_validate_image_input(**kwargs)
        if image_input is None:
1073
            return []
Song's avatar
Song committed
1074
1075
1076
        vision_embeddings = self._process_image_input(image_input)
        return vision_embeddings

1077
    def embed_input_ids(
Song's avatar
Song committed
1078
1079
        self,
        input_ids: torch.Tensor,
1080
        multimodal_embeddings: MultiModalEmbeddings | None = None,
1081
        *,
1082
        is_multimodal: torch.Tensor | None = None,
1083
1084
        # Multi-modal token ID may exceed vocab size
        handle_oov_mm_token: bool = True,
Song's avatar
Song committed
1085
    ) -> torch.Tensor:
1086
1087
        # This is to satisfy the type checker for each overload
        if multimodal_embeddings is None or is_multimodal is None:
1088
            return super().embed_input_ids(input_ids)
1089

1090
        return super().embed_input_ids(
1091
1092
1093
1094
1095
            input_ids,
            multimodal_embeddings=multimodal_embeddings,
            is_multimodal=is_multimodal,
            handle_oov_mm_token=handle_oov_mm_token,
        )
Song's avatar
Song committed
1096
1097
1098
1099
1100

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
1101
1102
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
Song's avatar
Song committed
1103
        **kwargs: object,
1104
    ) -> torch.Tensor | IntermediateTensors:
Song's avatar
Song committed
1105
1106
1107
        if intermediate_tensors is not None:
            inputs_embeds = None
        elif inputs_embeds is None:
1108
1109
            vision_embeddings = self.embed_multimodal(**kwargs)
            inputs_embeds = self.embed_input_ids(
1110
1111
1112
1113
                input_ids,
                vision_embeddings,
                is_multimodal=input_ids == self.config.image_token_id,
            )
Song's avatar
Song committed
1114
1115
            input_ids = None

1116
1117
1118
        hidden_states = self.language_model(
            input_ids, positions, intermediate_tensors, inputs_embeds=inputs_embeds
        )
Song's avatar
Song committed
1119
1120
1121
1122
1123
1124

        return hidden_states

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
1125
    ) -> torch.Tensor | None:
1126
        return self.language_model.compute_logits(hidden_states)
Song's avatar
Song committed
1127
1128

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]):
1129
1130
        loader = AutoWeightsLoader(self)
        return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)