h2ovl.py 16.8 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
6
7
8
9
10
# adapted from https://huggingface.co/h2oai/h2ovl-mississippi-2b/blob/main/modeling_h2ovl_chat.py
# https://huggingface.co/h2oai/h2ovl-mississippi-2b/blob/main/image_process.py
# --------------------------------------------------------
# H2OVL-Mississippi
# Copyright (c) 2024 H2O.AI
# Licensed under Apache 2.0 License [see LICENSE for details]
# --------------------------------------------------------
11
from collections.abc import Mapping, Sequence
12
13
14
15
16
17

import torch
from PIL import Image
from transformers import PretrainedConfig

from vllm.model_executor.layers.quantization import QuantizationConfig
18
from vllm.multimodal import MULTIMODAL_REGISTRY
19
from vllm.multimodal.inputs import MultiModalKwargsItems
20
21
22
23
24
from vllm.multimodal.parse import (
    ImageEmbeddingItems,
    ImageProcessorItems,
    MultiModalDataItems,
)
25
from vllm.multimodal.processing.processor import (
26
    MultiModalProcessingInfo,
27
    ProcessorInputs,
28
29
30
    PromptReplacement,
    PromptUpdate,
    PromptUpdateDetails,
31
    TimingContext,
32
)
33
from vllm.tokenizers import TokenizerLike
34
35

from .intern_vit import InternVisionModel
36
37
38
39
40
41
42
43
44
45
46
47
48
from .internvl import (
    IMG_CONTEXT,
    IMG_END,
    IMG_START,
    BaseInternVLDummyInputsBuilder,
    BaseInternVLMultiModalProcessor,
    BaseInternVLProcessingInfo,
    BaseInternVLProcessor,
    InternVLChatModel,
    build_transform,
    find_closest_aspect_ratio,
    get_internvl_target_ratios,
)
49

50
51
52
53
54
55

def resolve_h2ovl_min_max_num(
    *,
    min_dynamic_patch: int,
    max_dynamic_patch: int,
    dynamic_image_size: bool,
56
    use_thumbnail: bool,
57
) -> tuple[int, int]:
58
    min_dynamic_patch = min_dynamic_patch if dynamic_image_size else 1
59
60
61
62
    max_dynamic_patch = max_dynamic_patch if dynamic_image_size else 1

    if use_thumbnail and max_dynamic_patch != 1:
        max_dynamic_patch += 1
63

64
65
66
67
68
69
70
    return min_dynamic_patch, max_dynamic_patch


def get_h2ovl_target_ratios(
    min_num: int,
    max_num: int,
    *,
71
    prior_aspect_ratio: tuple[int, int] | None,
72
73
) -> list[tuple[int, int]]:
    target_ratios = get_internvl_target_ratios(min_num, max_num)
74
75
76
77

    # if prior_aspect_ratio is provided, filter the target ratios
    if prior_aspect_ratio is not None:
        target_ratios = [
78
79
80
81
            ratio
            for ratio in target_ratios
            if prior_aspect_ratio[0] % ratio[0] != 0
            and prior_aspect_ratio[1] % ratio[1] != 0
82
83
        ]

84
85
86
87
88
89
90
91
92
93
94
95
96
97
    return target_ratios


# modified to include blocks generated in second pass
def calculate_h2ovl_targets(
    *,
    orig_width: int,
    orig_height: int,
    target_ratios: list[tuple[int, int]],
    image_size: int,
    use_thumbnail: bool,
) -> tuple[int, int, int, tuple[int, int]]:
    aspect_ratio = orig_width / orig_height

98
    # find the closest aspect ratio to the target
99
100
101
102
103
104
105
    target_aspect_ratio = find_closest_aspect_ratio(
        aspect_ratio,
        target_ratios,
        width=orig_width,
        height=orig_height,
        image_size=image_size,
    )
106
107
108
109
110

    # calculate the target width and height
    target_width = image_size * target_aspect_ratio[0]
    target_height = image_size * target_aspect_ratio[1]
    blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
111
112
113

    # add thumbnail image if num_blocks != 1
    if use_thumbnail and blocks != 1:
114
        blocks += 1
115

116
117
118
119
    return blocks, target_width, target_height, target_aspect_ratio


# adapted from https://huggingface.co/OpenGVLab/InternVL2-1B
120
121
# refactored to handle prior_aspect_ratio
def dynamic_preprocess_h2ovl(
122
    image: Image.Image,
123
124
    *,
    target_ratios: list[tuple[int, int]],
125
126
    image_size: int,
    use_thumbnail: bool,
127
) -> tuple[list[Image.Image], tuple[int, int]]:
128
129
    orig_width, orig_height = image.size

130
131
132
133
134
135
136
137
138
139
140
141
142
143
    # calculate the number of blocks without thumbnail
    (
        blocks,
        target_width,
        target_height,
        target_aspect_ratio,
    ) = calculate_h2ovl_targets(
        orig_width=orig_width,
        orig_height=orig_height,
        target_ratios=target_ratios,
        image_size=image_size,
        use_thumbnail=False,
    )

144
145
146
147
148
149
150
151
152
153
154
155
156
    # resize the image
    resized_img = image.resize((target_width, target_height))
    processed_images = []
    for i in range(blocks):
        box = (
            (i % (target_width // image_size)) * image_size,
            (i // (target_width // image_size)) * image_size,
            ((i % (target_width // image_size)) + 1) * image_size,
            ((i // (target_width // image_size)) + 1) * image_size,
        )
        # split the image
        split_img = resized_img.crop(box)
        processed_images.append(split_img)
157

158
    assert len(processed_images) == blocks
159

160
161
162
    if use_thumbnail and len(processed_images) != 1:
        thumbnail_img = image.resize((image_size, image_size))
        processed_images.append(thumbnail_img)
163

164
165
166
    return processed_images, target_aspect_ratio


167
def _preprocess_image(
168
    image: Image.Image,
169
170
171
172
173
    *,
    input_size: int,
    min_num: int,
    max_num: int,
    use_thumbnail: bool,
174
    prior_aspect_ratio: tuple[int, int] | None,
175
176
177
178
179
180
181
) -> tuple[torch.Tensor, tuple[int, int]]:
    target_ratios = get_h2ovl_target_ratios(
        min_num,
        max_num,
        prior_aspect_ratio=prior_aspect_ratio,
    )

182
    transform = build_transform(input_size=input_size)
183
    images, target_aspect_ratio = dynamic_preprocess_h2ovl(
184
185
186
        image,
        image_size=input_size,
        use_thumbnail=use_thumbnail,
187
        target_ratios=target_ratios,
188
    )
189
190

    pixel_values = torch.stack([transform(image) for image in images])
191
192
193
    return pixel_values, target_aspect_ratio


194
195
# refactored to use the _preprocess_image function
def image_to_pixel_values_h2ovl(
196
    image: Image.Image,
197
    *,
198
199
200
201
    input_size: int,
    min_num: int,
    max_num: int,
    use_thumbnail: bool,
202
    use_msac: bool,
203
204
) -> torch.Tensor:
    # when MSAC is turned on, we need to process the image twice
205
    if use_msac:
206
        # first pass
207
        pixel_values1, aspect_ratio1 = _preprocess_image(
208
209
            image,
            input_size=input_size,
210
            min_num=1,
211
212
            max_num=max_num,
            use_thumbnail=True,
213
            prior_aspect_ratio=None,
214
215
        )
        # second pass
216
        pixel_values2, _ = _preprocess_image(
217
218
            image,
            input_size=input_size,
219
            min_num=3,
220
            max_num=max_num,
221
222
            use_thumbnail=True,
            prior_aspect_ratio=aspect_ratio1,
223
224
225
        )
        # combine pixel values
        pixel_values = torch.cat(
226
227
            [pixel_values2[:-1], pixel_values1[:-1], pixel_values2[-1:]], 0
        )
228
229

    else:
230
        pixel_values, _ = _preprocess_image(
231
232
233
234
235
            image,
            input_size=input_size,
            min_num=min_num,
            max_num=max_num,
            use_thumbnail=use_thumbnail,
236
            prior_aspect_ratio=None,
237
238
239
240
241
        )

    return pixel_values


242
243
244
245
class H2OVLProcessor(BaseInternVLProcessor):
    def __init__(
        self,
        config: PretrainedConfig,
246
        tokenizer: TokenizerLike,
247
        *,
248
249
250
251
        min_dynamic_patch: int | None = None,
        max_dynamic_patch: int | None = None,
        dynamic_image_size: bool | None = None,
        use_msac: bool | None = None,
252
253
254
255
    ) -> None:
        super().__init__(
            config,
            tokenizer,
256
            min_dynamic_patch=min_dynamic_patch,
257
258
259
            max_dynamic_patch=max_dynamic_patch,
            dynamic_image_size=dynamic_image_size,
        )
260

261
262
263
        if use_msac is None:
            use_msac = config.use_msac
        assert isinstance(use_msac, bool)
264

265
        self.use_msac = use_msac
266

267
268
269
    @property
    def image_token_id(self) -> int:
        return self.tokenizer.get_vocab()[IMG_CONTEXT]
270

271
    def get_image_repl(
272
273
        self,
        feature_size: int,
274
        num_patches: int | None,
275
276
277
    ) -> PromptUpdateDetails[str]:
        repl_features = IMG_CONTEXT * feature_size
        repl_full = IMG_START + repl_features + IMG_END
278

279
        return PromptUpdateDetails.select_text(repl_full, IMG_CONTEXT)
280

281
    def resolve_min_max_num(
282
283
        self,
        *,
284
285
286
287
        min_dynamic_patch: int | None = None,
        max_dynamic_patch: int | None = None,
        dynamic_image_size: bool | None = None,
        use_thumbnail: bool | None = None,
288
    ) -> tuple[int, int]:
289
290
291
292
293
294
295
296
297
298
299
300
        min_dynamic_patch = (
            self.min_dynamic_patch if min_dynamic_patch is None else min_dynamic_patch
        )
        max_dynamic_patch = (
            self.max_dynamic_patch if max_dynamic_patch is None else max_dynamic_patch
        )
        dynamic_image_size = (
            self.dynamic_image_size
            if dynamic_image_size is None
            else dynamic_image_size
        )
        use_thumbnail = self.use_thumbnail if use_thumbnail is None else use_thumbnail
301
302
303
304
305
306
307

        return resolve_h2ovl_min_max_num(
            min_dynamic_patch=min_dynamic_patch,
            max_dynamic_patch=max_dynamic_patch,
            dynamic_image_size=dynamic_image_size,
            use_thumbnail=use_thumbnail,
        )
308

309
310
311
    def resolve_target_ratios(
        self,
        *,
312
313
314
315
316
317
        min_dynamic_patch: int | None = None,
        max_dynamic_patch: int | None = None,
        dynamic_image_size: bool | None = None,
        use_thumbnail: bool | None = None,
        prior_aspect_ratio: tuple[int, int] | None = None,
        override_min_num: int | None = None,
318
319
    ) -> list[tuple[int, int]]:
        min_num, max_num = self.resolve_min_max_num(
320
            min_dynamic_patch=min_dynamic_patch,
321
322
323
324
            max_dynamic_patch=max_dynamic_patch,
            dynamic_image_size=dynamic_image_size,
            use_thumbnail=use_thumbnail,
        )
325
326
        if override_min_num is not None:
            min_num = override_min_num
327

328
329
330
331
        return get_h2ovl_target_ratios(
            min_num,
            max_num,
            prior_aspect_ratio=prior_aspect_ratio,
332
333
        )

334
335
336
337
338
    def get_num_image_tokens(
        self,
        *,
        image_width: int,
        image_height: int,
339
        use_msac: bool | None = None,
340
    ) -> int:
341
        use_msac = self.use_msac if use_msac is None else use_msac
342
343
344
345
346
347

        use_thumbnail = self.use_thumbnail

        if use_msac:
            target_ratios_1 = self.resolve_target_ratios(
                use_thumbnail=False,  # Applied in calculate_targets
348
                override_min_num=1,
349
350
351
352
353
354
355
356
357
358
359
360
            )
            num_patches_1, _, _, aspect_ratio_1 = calculate_h2ovl_targets(
                orig_width=image_width,
                orig_height=image_height,
                image_size=self.image_size,
                target_ratios=target_ratios_1,
                use_thumbnail=True,
            )

            target_ratios_2 = self.resolve_target_ratios(
                use_thumbnail=False,  # Applied in calculate_targets
                prior_aspect_ratio=aspect_ratio_1,
361
                override_min_num=3,
362
363
364
365
366
367
368
369
370
371
            )
            num_patches_2, _, _, _ = calculate_h2ovl_targets(
                orig_width=image_width,
                orig_height=image_height,
                image_size=self.image_size,
                target_ratios=target_ratios_2,
                use_thumbnail=True,
            )

            num_patches = num_patches_1 + num_patches_2 - 1
372
        else:
373
374
375
376
377
378
379
380
381
382
383
384
            target_ratios = self.resolve_target_ratios(
                use_thumbnail=False,  # Applied in calculate_targets
            )
            num_patches, _, _, _ = calculate_h2ovl_targets(
                orig_width=image_width,
                orig_height=image_height,
                image_size=self.image_size,
                target_ratios=target_ratios,
                use_thumbnail=use_thumbnail,
            )

        return num_patches * self.num_image_token
385

386
387
388
    def _images_to_pixel_values_lst(
        self,
        images: list[Image.Image],
389
390
391
        min_dynamic_patch: int | None = None,
        max_dynamic_patch: int | None = None,
        dynamic_image_size: bool | None = None,
392
393
394
395
    ) -> list[torch.Tensor]:
        use_msac = self.use_msac if len(images) == 1 else False

        min_num, max_num = self.resolve_min_max_num(
396
            min_dynamic_patch=min_dynamic_patch,
397
398
399
            max_dynamic_patch=max_dynamic_patch,
            dynamic_image_size=dynamic_image_size,
            use_thumbnail=False,  # Applied in image_to_pixel_values
400
401
        )

402
403
404
405
406
407
408
409
        return [
            image_to_pixel_values_h2ovl(
                image,
                input_size=self.image_size,
                min_num=min_num,
                max_num=max_num,
                use_thumbnail=self.use_thumbnail,
                use_msac=use_msac,
410
411
            )
            for image in images
412
413
414
415
        ]


class H2OVLProcessingInfo(BaseInternVLProcessingInfo):
416
    def get_hf_processor(self, **kwargs: object) -> H2OVLProcessor:
417
418
419
420
421
        return self.ctx.init_processor(
            H2OVLProcessor,
            config=self.get_hf_config(),
            tokenizer=self.get_tokenizer(),
            **kwargs,
422
423
424
425
426
427
428
        )

    def get_num_image_tokens(
        self,
        *,
        image_width: int,
        image_height: int,
429
        processor: H2OVLProcessor,
430
        use_msac: bool | None = None,
431
432
433
434
435
436
    ) -> int:
        return processor.get_num_image_tokens(
            image_width=image_width,
            image_height=image_height,
            use_msac=use_msac,
        )
437
438


439
class H2OVLMultiModalProcessor(BaseInternVLMultiModalProcessor[H2OVLProcessingInfo]):
440
    def _get_prompt_updates(
441
442
443
        self,
        mm_items: MultiModalDataItems,
        hf_processor_mm_kwargs: Mapping[str, object],
444
        out_mm_kwargs: MultiModalKwargsItems,
445
    ) -> Sequence[PromptUpdate]:
446
447
        hf_processor = self.info.get_hf_processor(**hf_processor_mm_kwargs)

448
449
450
        out_mm_data = out_mm_kwargs.get_data()
        if "image_num_patches" in out_mm_data:
            image_num_patches = out_mm_data["image_num_patches"]
451
452
            assert isinstance(image_num_patches, torch.Tensor)
            image_num_patches = image_num_patches.tolist()
453
        elif "image_embeds" in out_mm_data:
454
455
            # TODO: Use image size information in dictionary embedding inputs
            # to compute num_patches (similar to Qwen2-VL)
456
            image_num_patches = [None] * len(out_mm_data["image_embeds"])
457
        else:
458
459
460
            image_num_patches = []

        num_images = len(image_num_patches)
461

462
463
        def get_replacement_internvl(item_idx: int):
            images = mm_items.get_items(
464
465
                "image", (ImageEmbeddingItems, ImageProcessorItems)
            )
466

467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
            if isinstance(images, ImageEmbeddingItems):
                feature_size = images.get_feature_size(item_idx)
            else:
                image_size = images.get_image_size(item_idx)
                feature_size = self.info.get_num_image_tokens(
                    image_width=image_size.width,
                    image_height=image_size.height,
                    processor=hf_processor,
                    use_msac=None if num_images == 1 else False,
                )

            num_patches = image_num_patches[item_idx]
            if num_patches is not None:
                assert isinstance(num_patches, int)

482
            return hf_processor.get_image_repl(feature_size, num_patches)
483

484
485
486
487
488
489
490
        return [
            PromptReplacement(
                modality="image",
                target="<image>",
                replacement=get_replacement_internvl,
            )
        ]
491

492
493
    def _cached_apply_hf_processor(
        self,
494
495
        inputs: ProcessorInputs,
        timing_ctx: TimingContext,
496
    ) -> tuple[list[int], MultiModalProcessingInfo, bool]:
497
498
499
500
        # The processor logic is different for len(images) <= 1 vs > 1
        # Since the processing cache assumes that the processor output is
        # invariant of how many images are passed per prompt, we only
        # perform caching for the most common case
501
502
        if inputs.mm_data_items.get_count("image", strict=False) > 1:
            return self._apply_hf_processor(inputs, timing_ctx)
503

504
        return super()._cached_apply_hf_processor(inputs, timing_ctx)
505

506

507
508
509
@MULTIMODAL_REGISTRY.register_processor(
    H2OVLMultiModalProcessor,
    info=H2OVLProcessingInfo,
510
511
    dummy_inputs=BaseInternVLDummyInputsBuilder,
)
512
513
514
515
class H2OVLChatModel(InternVLChatModel):
    def _init_vision_model(
        self,
        config: PretrainedConfig,
516
        quant_config: QuantizationConfig | None,
517
518
519
520
521
522
523
        *,
        is_mono: bool,
        prefix: str,
    ):
        if not is_mono:
            vision_feature_layer = config.select_layer
            if vision_feature_layer < 0:
524
525
526
                num_hidden_layers = (
                    config.vision_config.num_hidden_layers + vision_feature_layer + 1
                )
527
528
529
530
531
532
533
534
535
536
537
538
            else:
                num_hidden_layers = vision_feature_layer + 1

            return InternVisionModel(
                config.vision_config,
                quant_config=quant_config,
                num_hidden_layers_override=num_hidden_layers,
                prefix=prefix,
            )
        else:
            msg = "Monolith mode is not applicable to H2OVL"
            raise NotImplementedError(msg)