"vscode:/vscode.git/clone" did not exist on "0278f1ac3ac90c245a9a000cb11eb3146103cfd1"
h2ovl.py 17.4 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
from vllm.multimodal.parse import (
    ImageEmbeddingItems,
    ImageProcessorItems,
    MultiModalDataItems,
24
    MultiModalUUIDItems,
25
)
26
from vllm.multimodal.processing.processor import (
27
28
29
30
31
    MultiModalProcessingInfo,
    PromptReplacement,
    PromptUpdate,
    PromptUpdateDetails,
)
32
from vllm.tokenizers import TokenizerLike
33
34

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

49
50
51
52
53
54

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

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

63
64
65
66
67
68
69
    return min_dynamic_patch, max_dynamic_patch


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

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

83
84
85
86
87
88
89
90
91
92
93
94
95
96
    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

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

    # 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]
110
111
112

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

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


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

129
130
131
132
133
134
135
136
137
138
139
140
141
142
    # 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,
    )

143
144
145
146
147
148
149
150
151
152
153
154
155
    # 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)
156

157
    assert len(processed_images) == blocks
158

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

163
164
165
    return processed_images, target_aspect_ratio


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

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

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


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

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

    return pixel_values


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

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

264
        self.use_msac = use_msac
265

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

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

278
        return PromptUpdateDetails.select_text(repl_full, IMG_CONTEXT)
279

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

        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,
        )
307

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

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

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

        use_thumbnail = self.use_thumbnail

        if use_msac:
            target_ratios_1 = self.resolve_target_ratios(
                use_thumbnail=False,  # Applied in calculate_targets
347
                override_min_num=1,
348
349
350
351
352
353
354
355
356
357
358
359
            )
            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,
360
                override_min_num=3,
361
362
363
364
365
366
367
368
369
370
            )
            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
371
        else:
372
373
374
375
376
377
378
379
380
381
382
383
            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
384

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

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

401
402
403
404
405
406
407
408
        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,
409
410
            )
            for image in images
411
412
413
414
        ]


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

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


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

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

        num_images = len(image_num_patches)
460

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

466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
            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)

481
            return hf_processor.get_image_repl(feature_size, num_patches)
482

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

491
492
    def _cached_apply_hf_processor(
        self,
493
        prompt: str | list[int],
494
        mm_data_items: MultiModalDataItems,
495
        mm_uuid_items: MultiModalUUIDItems | None,
496
        hf_processor_mm_kwargs: Mapping[str, object],
497
        tokenization_kwargs: Mapping[str, object],
498
    ) -> tuple[list[int], MultiModalProcessingInfo, bool]:
499
500
501
502
503
        # 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
        if mm_data_items.get_count("image", strict=False) > 1:
504
            return self._apply_hf_processor(
505
                prompt=prompt,
506
                mm_data_items=mm_data_items,
507
                mm_uuid_items=mm_uuid_items,
508
                hf_processor_mm_kwargs=hf_processor_mm_kwargs,
509
                tokenization_kwargs=tokenization_kwargs,
510
511
512
513
514
            )

        return super()._cached_apply_hf_processor(
            prompt=prompt,
            mm_data_items=mm_data_items,
515
            mm_uuid_items=mm_uuid_items,
516
            hf_processor_mm_kwargs=hf_processor_mm_kwargs,
517
            tokenization_kwargs=tokenization_kwargs,
518
519
        )

520

521
522
523
@MULTIMODAL_REGISTRY.register_processor(
    H2OVLMultiModalProcessor,
    info=H2OVLProcessingInfo,
524
525
    dummy_inputs=BaseInternVLDummyInputsBuilder,
)
526
527
528
529
class H2OVLChatModel(InternVLChatModel):
    def _init_vision_model(
        self,
        config: PretrainedConfig,
530
        quant_config: QuantizationConfig | None,
531
532
533
534
535
536
537
        *,
        is_mono: bool,
        prefix: str,
    ):
        if not is_mono:
            vision_feature_layer = config.select_layer
            if vision_feature_layer < 0:
538
539
540
                num_hidden_layers = (
                    config.vision_config.num_hidden_layers + vision_feature_layer + 1
                )
541
542
543
544
545
546
547
548
549
550
551
552
            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)