mm_plugin.py 75.9 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team.
#
# This code is inspired by the HuggingFace's Transformers library.
# https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/models/llava/processing_llava.py
#
# 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.

chenych's avatar
chenych committed
18
import inspect
luopl's avatar
luopl committed
19
import math
luopl's avatar
luopl committed
20
import re
luopl's avatar
luopl committed
21
from copy import deepcopy
chenych's avatar
chenych committed
22
from dataclasses import dataclass
luopl's avatar
luopl committed
23
from io import BytesIO
chenych's avatar
chenych committed
24
from typing import TYPE_CHECKING, BinaryIO, Literal, Optional, TypedDict, Union
luopl's avatar
luopl committed
25
26

import numpy as np
luopl's avatar
luopl committed
27
import torch
luopl's avatar
luopl committed
28
29
30
from transformers.image_utils import get_image_size, to_numpy_array
from typing_extensions import override

chenych's avatar
chenych committed
31
32
33
34
35
36
37
38
39
40
41
from ..extras.constants import AUDIO_PLACEHOLDER, IGNORE_INDEX, IMAGE_PLACEHOLDER, VIDEO_PLACEHOLDER
from ..extras.packages import (
    is_librosa_available,
    is_pillow_available,
    is_pyav_available,
    is_transformers_version_greater_than,
)


if is_librosa_available():
    import librosa
luopl's avatar
luopl committed
42
43
44
45
46
47
48
49
50
51
52


if is_pillow_available():
    from PIL import Image
    from PIL.Image import Image as ImageObject


if is_pyav_available():
    import av


luopl's avatar
luopl committed
53
54
55
56
57
58
59
if is_transformers_version_greater_than("4.45.0"):
    from transformers.models.mllama.processing_mllama import (
        convert_sparse_cross_attention_mask_to_dense,
        get_cross_attention_token_mask,
    )


chenych's avatar
chenych committed
60
61
62
63
if is_transformers_version_greater_than("4.49.0"):
    from transformers.image_utils import make_batched_videos, make_flat_list_of_images


luopl's avatar
luopl committed
64
65
if TYPE_CHECKING:
    from av.stream import Stream
chenych's avatar
chenych committed
66
    from numpy.typing import NDArray
luopl's avatar
luopl committed
67
    from transformers import PreTrainedTokenizer, ProcessorMixin
chenych's avatar
chenych committed
68
    from transformers.feature_extraction_sequence_utils import SequenceFeatureExtractor
luopl's avatar
luopl committed
69
70
71
72
73
74
    from transformers.image_processing_utils import BaseImageProcessor

    class EncodedImage(TypedDict):
        path: Optional[str]
        bytes: Optional[bytes]

chenych's avatar
chenych committed
75
76
77
78
79
80
81
82
83
84
85
86
    ImageInput = Union[str, bytes, EncodedImage, BinaryIO, ImageObject]
    VideoInput = Union[str, BinaryIO]
    AudioInput = Union[str, BinaryIO, NDArray]

    class MMProcessor(ProcessorMixin):
        patch_size: int
        image_seq_length: int
        num_additional_image_tokens: int
        vision_feature_select_strategy: Literal["default", "full"]

        def _get_number_of_features(self, orig_height: int, orig_width: int, height: int, width: int) -> int:
            pass
luopl's avatar
luopl committed
87
88


chenych's avatar
chenych committed
89
90
91
92
def _get_paligemma_token_type_ids(imglens: list[int], seqlens: list[int], processor: "MMProcessor") -> list[list[int]]:
    r"""Get paligemma token type ids for computing loss.

    It is slightly different with the original token type ids where the prompt part is 0.
luopl's avatar
luopl committed
93
94

    Returns:
chenych's avatar
chenych committed
95
96
        batch_token_type_ids: shape (batch_size, seq_length)

luopl's avatar
luopl committed
97
98
99
    """
    batch_token_type_ids = []
    for imglen, seqlen in zip(imglens, seqlens):
chenych's avatar
chenych committed
100
        image_seqlen = imglen * processor.image_seq_length
luopl's avatar
luopl committed
101
102
103
104
105
        batch_token_type_ids.append([0] * image_seqlen + [1] * (seqlen - image_seqlen))

    return batch_token_type_ids


chenych's avatar
chenych committed
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
def _get_gemma3_token_type_ids(batch_ids: list[list[int]], processor: "MMProcessor"):
    r"""Get gemma3 token type ids for computing loss.

    Returns:
        batch_token_type_ids: shape (batch_size, seq_length)

    """
    image_token_id: int = getattr(processor, "image_token_id")
    batch_token_type_ids = []
    for token_ids in batch_ids:
        token_ids = np.array(token_ids)
        token_type_ids = np.zeros_like(token_ids)
        token_type_ids[token_ids == image_token_id] = 1
        batch_token_type_ids.append(token_type_ids.tolist())

    return batch_token_type_ids


def _make_batched_images(images: list["ImageObject"], imglens: list[int]) -> list[list["ImageObject"]]:
    r"""Make nested list of images."""
    batch_images = []
    for imglen in imglens:
        batch_images.append(images[:imglen])
        images = images[imglen:]

    return batch_images


chenych's avatar
chenych committed
134
135
136
137
138
139
@dataclass
class MMPluginMixin:
    image_token: Optional[str]
    video_token: Optional[str]
    audio_token: Optional[str]
    expand_mm_tokens: bool = True
luopl's avatar
luopl committed
140
141
142

    def _validate_input(
        self,
chenych's avatar
chenych committed
143
144
145
146
        processor: Optional["MMProcessor"],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
luopl's avatar
luopl committed
147
    ) -> None:
chenych's avatar
chenych committed
148
149
150
151
152
153
        r"""Validate if this model accepts the input modalities."""
        image_processor: BaseImageProcessor = getattr(processor, "image_processor", None)
        video_processor: BaseImageProcessor = getattr(
            processor, "video_processor", getattr(processor, "image_processor", None)
        )
        feature_extractor: SequenceFeatureExtractor = getattr(processor, "feature_extractor", None)
luopl's avatar
luopl committed
154
        if len(images) != 0 and self.image_token is None:
luopl's avatar
luopl committed
155
156
157
            raise ValueError(
                "This model does not support image input. Please check whether the correct `template` is used."
            )
luopl's avatar
luopl committed
158
159

        if len(videos) != 0 and self.video_token is None:
luopl's avatar
luopl committed
160
161
162
            raise ValueError(
                "This model does not support video input. Please check whether the correct `template` is used."
            )
luopl's avatar
luopl committed
163

chenych's avatar
chenych committed
164
165
166
167
168
169
170
171
172
173
174
        if len(audios) != 0 and self.audio_token is None:
            raise ValueError(
                "This model does not support audio input. Please check whether the correct `template` is used."
            )

        if self.image_token is not None and processor is None:
            raise ValueError("Processor was not found, please check and update your processor config.")

        if self.image_token is not None and image_processor is None:
            raise ValueError("Image processor was not found, please check and update your processor config.")

chenych's avatar
chenych committed
175
176
177
        if self.video_token is not None and video_processor is None:
            raise ValueError("Video processor was not found, please check and update your processor config.")

chenych's avatar
chenych committed
178
179
180
181
182
183
        if self.audio_token is not None and feature_extractor is None:
            raise ValueError("Audio feature extractor was not found, please check and update your processor config.")

    def _preprocess_image(
        self, image: "ImageObject", image_max_pixels: int, image_min_pixels: int, **kwargs
    ) -> "ImageObject":
chenych's avatar
chenych committed
184
        r"""Pre-process a single image."""
chenych's avatar
chenych committed
185
186
        if (image.width * image.height) > image_max_pixels:
            resize_factor = math.sqrt(image_max_pixels / (image.width * image.height))
luopl's avatar
luopl committed
187
            width, height = int(image.width * resize_factor), int(image.height * resize_factor)
chenych's avatar
chenych committed
188
189
190
191
192
193
            image = image.resize((width, height))

        if (image.width * image.height) < image_min_pixels:
            resize_factor = math.sqrt(image_min_pixels / (image.width * image.height))
            width, height = int(image.width * resize_factor), int(image.height * resize_factor)
            image = image.resize((width, height))
luopl's avatar
luopl committed
194
195
196
197
198
199

        if image.mode != "RGB":
            image = image.convert("RGB")

        return image

chenych's avatar
chenych committed
200
201
    def _get_video_sample_indices(
        self, video_stream: "Stream", video_fps: float, video_maxlen: int, **kwargs
chenych's avatar
chenych committed
202
203
    ) -> list[int]:
        r"""Compute video sample indices according to fps."""
luopl's avatar
luopl committed
204
        total_frames = video_stream.frames
chenych's avatar
chenych committed
205
206
207
        if total_frames == 0:  # infinite video
            return np.linspace(0, video_maxlen - 1, video_maxlen).astype(np.int32)

chenych's avatar
chenych committed
208
        sample_frames = max(1, math.floor(float(video_stream.duration * video_stream.time_base) * video_fps))
luopl's avatar
luopl committed
209
        sample_frames = min(total_frames, video_maxlen, sample_frames)
chenych's avatar
chenych committed
210
        return np.linspace(0, total_frames - 1, sample_frames).astype(np.int32)
luopl's avatar
luopl committed
211

chenych's avatar
chenych committed
212
213
    def _regularize_images(self, images: list["ImageInput"], **kwargs) -> dict[str, list["ImageObject"]]:
        r"""Regularize images to avoid error. Including reading and pre-processing."""
luopl's avatar
luopl committed
214
215
        results = []
        for image in images:
chenych's avatar
chenych committed
216
            if isinstance(image, (str, BinaryIO)):
luopl's avatar
luopl committed
217
                image = Image.open(image)
luopl's avatar
luopl committed
218
219
            elif isinstance(image, bytes):
                image = Image.open(BytesIO(image))
luopl's avatar
luopl committed
220
221
222
223
224
225
226
            elif isinstance(image, dict):
                if image["bytes"] is not None:
                    image = Image.open(BytesIO(image["bytes"]))
                else:
                    image = Image.open(image["path"])

            if not isinstance(image, ImageObject):
chenych's avatar
chenych committed
227
                raise ValueError(f"Expect input is a list of images, but got {type(image)}.")
luopl's avatar
luopl committed
228
229
230

            results.append(self._preprocess_image(image, **kwargs))

chenych's avatar
chenych committed
231
        return {"images": results}
luopl's avatar
luopl committed
232

chenych's avatar
chenych committed
233
234
    def _regularize_videos(self, videos: list["VideoInput"], **kwargs) -> dict[str, list[list["ImageObject"]]]:
        r"""Regularizes videos to avoid error. Including reading, resizing and converting."""
luopl's avatar
luopl committed
235
236
237
238
        results = []
        for video in videos:
            container = av.open(video, "r")
            video_stream = next(stream for stream in container.streams if stream.type == "video")
chenych's avatar
chenych committed
239
            sample_indices = self._get_video_sample_indices(video_stream, **kwargs)
chenych's avatar
chenych committed
240
            frames: list[ImageObject] = []
luopl's avatar
luopl committed
241
242
243
244
245
            container.seek(0)
            for frame_idx, frame in enumerate(container.decode(video_stream)):
                if frame_idx in sample_indices:
                    frames.append(frame.to_image())

chenych's avatar
chenych committed
246
            frames = self._regularize_images(frames, **kwargs)["images"]
luopl's avatar
luopl committed
247
248
            results.append(frames)

chenych's avatar
chenych committed
249
        return {"videos": results}
luopl's avatar
luopl committed
250

chenych's avatar
chenych committed
251
252
253
254
255
    def _regularize_audios(
        self, audios: list["AudioInput"], sampling_rate: float, **kwargs
    ) -> dict[str, Union[list["NDArray"], list[float]]]:
        r"""Regularizes audios to avoid error. Including reading and resampling."""
        results, sampling_rates = [], []
chenych's avatar
chenych committed
256
        for audio in audios:
chenych's avatar
chenych committed
257
258
            if isinstance(audio, (str, BinaryIO)):
                audio, sampling_rate = librosa.load(audio, sr=sampling_rate)
chenych's avatar
chenych committed
259
260
261
262
263

            if not isinstance(audio, np.ndarray):
                raise ValueError(f"Expect input is a list of audios, but got {type(audio)}.")

            results.append(audio)
chenych's avatar
chenych committed
264
            sampling_rates.append(sampling_rate)
chenych's avatar
chenych committed
265

chenych's avatar
chenych committed
266
        return {"audios": results, "sampling_rates": sampling_rates}
chenych's avatar
chenych committed
267

luopl's avatar
luopl committed
268
269
    def _get_mm_inputs(
        self,
chenych's avatar
chenych committed
270
271
272
273
274
275
276
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: "MMProcessor",
        imglens: Optional[list[int]] = None,
    ) -> dict[str, "torch.Tensor"]:
        r"""Process visual inputs.
luopl's avatar
luopl committed
277
278
279
280
281
282
283

        Returns: (llava and paligemma)
            pixel_values: tensor with shape (B, C, H, W)

        Returns: (qwen2-vl)
            pixel_values: tensor with shape (num_patches, patch_dim)
            image_grid_thw: tensor with shape (num_images, 3), where the three numbers are time, width, height
chenych's avatar
chenych committed
284
285
286
287
288
289
290
291
292
                            where num_patches == torch.prod(image_grid_thw)

        Returns: (mllama)
            pixel_values: tensor with shape
                          (batch_size, max_num_images, max_image_tiles, channels, tile_height, tile_width)
                          For example, (2, 1, 4, 3, 560, 560).
            aspect_ratio_ids: tensor with shape (batch_size, max_num_images). For example, (2, 1).
            aspect_ratio_mask: tensor with shape (batch_size, max_num_images, max_image_tiles). For example, (2, 1, 4).
            num_tiles: List[List[int]] with shape (batch_size, num_images_in_batch). For example, (2, 1).
luopl's avatar
luopl committed
293
294

        """
chenych's avatar
chenych committed
295
        mm_inputs = {}
luopl's avatar
luopl committed
296
        if len(images) != 0:
chenych's avatar
chenych committed
297
            image_processor: BaseImageProcessor = getattr(processor, "image_processor", None)
luopl's avatar
luopl committed
298
299
            images = self._regularize_images(
                images,
chenych's avatar
chenych committed
300
301
                image_max_pixels=getattr(processor, "image_max_pixels", 768 * 768),
                image_min_pixels=getattr(processor, "image_min_pixels", 32 * 32),
chenych's avatar
chenych committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
            )["images"]
            if imglens is not None:  # if imglens are provided, make batched images
                images = _make_batched_images(images, imglens)

            image_processor_kwargs = {}
            if getattr(processor, "image_do_pan_and_scan", False):  # gemma3 image processor
                image_processor_kwargs.update(
                    {
                        "do_pan_and_scan": True,
                        "pan_and_scan_min_crop_size": 256,
                        "pan_and_scan_max_num_crops": 4,
                        "pan_and_scan_min_ratio_to_activate": 1.2,
                    }
                )

            mm_inputs.update(image_processor(images, return_tensors="pt", **image_processor_kwargs))
luopl's avatar
luopl committed
318
319

        if len(videos) != 0:
chenych's avatar
chenych committed
320
321
322
            video_processor: BaseImageProcessor = getattr(
                processor, "video_processor", getattr(processor, "image_processor", None)
            )
luopl's avatar
luopl committed
323
324
            videos = self._regularize_videos(
                videos,
chenych's avatar
chenych committed
325
326
                image_max_pixels=getattr(processor, "video_max_pixels", 256 * 256),
                image_min_pixels=getattr(processor, "video_min_pixels", 16 * 16),
luopl's avatar
luopl committed
327
                video_fps=getattr(processor, "video_fps", 2.0),
chenych's avatar
chenych committed
328
                video_maxlen=getattr(processor, "video_maxlen", 128),
chenych's avatar
chenych committed
329
            )["videos"]
chenych's avatar
chenych committed
330
331
332
333
334
335
            if "videos" in inspect.signature(video_processor.preprocess).parameters:  # for qwen2_vl and video_llava
                mm_inputs.update(video_processor(images=None, videos=videos, return_tensors="pt"))
            else:  # for llava_next_video
                mm_inputs.update(video_processor(videos, return_tensors="pt"))

        if len(audios) != 0:
chenych's avatar
chenych committed
336
            feature_extractor: SequenceFeatureExtractor = getattr(processor, "feature_extractor", None)
chenych's avatar
chenych committed
337
338
            audios = self._regularize_audios(
                audios,
chenych's avatar
chenych committed
339
340
                sampling_rate=getattr(processor, "audio_sampling_rate", 16000),
            )["audios"]
chenych's avatar
chenych committed
341
342
343
            mm_inputs.update(
                feature_extractor(
                    audios,
chenych's avatar
chenych committed
344
                    sampling_rate=getattr(processor, "audio_sampling_rate", 16000),
chenych's avatar
chenych committed
345
346
347
348
349
350
                    return_attention_mask=True,
                    padding="max_length",
                    return_tensors="pt",
                )
            )
            mm_inputs["feature_attention_mask"] = mm_inputs.pop("attention_mask")  # prevent conflicts
luopl's avatar
luopl committed
351
352
353

        return mm_inputs

chenych's avatar
chenych committed
354
355
356

@dataclass
class BasePlugin(MMPluginMixin):
luopl's avatar
luopl committed
357
358
    def process_messages(
        self,
chenych's avatar
chenych committed
359
360
361
362
363
364
365
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
        r"""Pre-process input messages before tokenization for VLMs."""
chenych's avatar
chenych committed
366
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
367
368
369
370
        return messages

    def process_token_ids(
        self,
chenych's avatar
chenych committed
371
372
373
374
375
        input_ids: list[int],
        labels: Optional[list[int]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
luopl's avatar
luopl committed
376
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
377
378
379
        processor: Optional["MMProcessor"],
    ) -> tuple[list[int], Optional[list[int]]]:
        r"""Pre-process token ids after tokenization for VLMs."""
chenych's avatar
chenych committed
380
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
381
382
383
384
        return input_ids, labels

    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
385
386
387
388
389
390
391
392
393
394
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
        r"""Build batched multimodal inputs for VLMs.
luopl's avatar
luopl committed
395
396
397
398

        Arguments:
            images: a list of image inputs, shape (num_images,)
            videos: a list of video inputs, shape (num_videos,)
chenych's avatar
chenych committed
399
            audios: a list of audio inputs, shape (num_audios,)
luopl's avatar
luopl committed
400
401
            imglens: number of images in each sample, shape (batch_size,)
            vidlens: number of videos in each sample, shape (batch_size,)
chenych's avatar
chenych committed
402
            audlens: number of audios in each sample, shape (batch_size,)
luopl's avatar
luopl committed
403
            batch_ids: token ids of input samples, shape (batch_size, seq_len)
luopl's avatar
luopl committed
404
            processor: a processor for pre-processing images and videos
chenych's avatar
chenych committed
405

luopl's avatar
luopl committed
406
        """
chenych's avatar
chenych committed
407
        self._validate_input(processor, images, videos, audios)
chenych's avatar
chenych committed
408
        return self._get_mm_inputs(images, videos, audios, processor)
luopl's avatar
luopl committed
409
410


chenych's avatar
chenych committed
411
@dataclass
chenych's avatar
chenych committed
412
class Gemma3Plugin(BasePlugin):
luopl's avatar
luopl committed
413
414
415
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
416
417
418
419
420
421
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
422
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
423
424
        num_image_tokens = 0
        messages = deepcopy(messages)
chenych's avatar
chenych committed
425
426
427
428
429
430
431
432
        boi_token: str = getattr(processor, "boi_token")
        full_image_sequence: str = getattr(processor, "full_image_sequence")
        image_str = full_image_sequence if self.expand_mm_tokens else boi_token

        do_pan_and_scan: bool = getattr(processor, "image_do_pan_and_scan", False)
        if do_pan_and_scan:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)

luopl's avatar
luopl committed
433
434
435
        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
436
437
438
439
440
441
442
443
444
                if do_pan_and_scan:
                    image_placeholder_str = (
                        "Here is the original image {{image}} and here are some crops to help you see better "
                        + " ".join(["{{image}}"] * mm_inputs["num_crops"][0][num_image_tokens])
                    )
                else:
                    image_placeholder_str = "{{image}}"

                content = content.replace(IMAGE_PLACEHOLDER, image_placeholder_str, 1)
luopl's avatar
luopl committed
445
                num_image_tokens += 1
luopl's avatar
luopl committed
446

chenych's avatar
chenych committed
447
            message["content"] = content.replace("{{image}}", image_str)
luopl's avatar
luopl committed
448
449

        if len(images) != num_image_tokens:
luopl's avatar
luopl committed
450
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
451
452
453
454
455
456

        return messages

    @override
    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
457
458
459
460
461
462
463
464
465
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
chenych's avatar
chenych committed
466
        self._validate_input(processor, images, videos, audios)
chenych's avatar
chenych committed
467
468
469
470
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
        mm_inputs.pop("num_crops", None)
        mm_inputs["token_type_ids"] = _get_gemma3_token_type_ids(batch_ids, processor)
        return mm_inputs
luopl's avatar
luopl committed
471
472


chenych's avatar
chenych committed
473
@dataclass
chenych's avatar
chenych committed
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
class InternVLPlugin(BasePlugin):
    @override
    def _get_mm_inputs(
        self,
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: "ProcessorMixin",
        **kwargs,
    ) -> dict[str, "torch.Tensor"]:
        image_processor: BaseImageProcessor = getattr(processor, "image_processor")
        image_processor_kwargs = {}
        if getattr(processor, "crop_to_patches", False):
            image_processor_kwargs.update(
                {
                    "crop_to_patches": True,
                    "max_patches": 12,
                    "min_patches": 1,
                }
            )

        mm_inputs = {}
        image_video_patches = []

        if len(images) != 0 and isinstance(images[0], str):
            images = self._regularize_images(
                images,
                image_max_pixels=getattr(processor, "image_max_pixels", 1024 * 1024),
                image_min_pixels=getattr(processor, "image_min_pixels", 32 * 32),
            )["images"]

        if len(videos) != 0 and isinstance(videos[0], str):
            videos = self._regularize_videos(
                videos,
                image_max_pixels=getattr(processor, "video_max_pixels", 256 * 256),
                image_min_pixels=getattr(processor, "video_min_pixels", 16 * 16),
                video_fps=getattr(processor, "video_fps", 2.0),
                video_maxlen=getattr(processor, "video_maxlen", 128),
            )["videos"]

        if len(images) != 0:
            images = make_flat_list_of_images(images)
            image_inputs = image_processor(images=images, return_tensors="pt", **image_processor_kwargs)
            image_num_patches = image_inputs.pop("num_patches")
            image_pixel_values = image_inputs.pop("pixel_values")
            image_num_patches_indices = np.cumsum(image_num_patches)

        if len(videos) != 0:
            videos = make_batched_videos(videos)
            num_frames_per_video = [len(video) for video in videos]
            patch_indices = np.cumsum(num_frames_per_video)
            image_processor_kwargs["crop_to_patches"] = False
            video_inputs = image_processor(images=videos, return_tensors="pt", **image_processor_kwargs)
            video_num_patches = video_inputs.pop("num_patches")
            video_pixel_values = video_inputs.pop("pixel_values")
            video_num_patches_indices = np.cumsum(video_num_patches)

        # NOT SUPPORT IMAGE VIDEO INTERLEAVED
        if len(images) != 0 and image_pixel_values is not None:
            for i in range(len(images)):
                start_index = image_num_patches_indices[i - 1] if i > 0 else 0
                end_index = image_num_patches_indices[i]
                image_video_patches.append(image_pixel_values[start_index:end_index])

        if len(videos) != 0 and video_pixel_values is not None:
            patch_indices_with_prefix = [0] + list(patch_indices)
            for i in range(len(videos)):
                current_patch_index = patch_indices_with_prefix[i]
                end_patch_index = patch_indices_with_prefix[i + 1]
                start_index = video_num_patches_indices[current_patch_index - 1] if i > 0 else 0
                end_index = video_num_patches_indices[end_patch_index - 1]
                image_video_patches.append(video_pixel_values[start_index:end_index])

        if len(images) != 0 or len(videos) != 0:
            mm_inputs["pixel_values"] = torch.cat(image_video_patches, dim=0)

        if len(images) != 0:
            mm_inputs.update({"image_num_patches": image_num_patches})

        if len(videos) != 0:
            mm_inputs.update({"video_patch_indices": patch_indices})
            mm_inputs.update({"video_num_patches": video_num_patches})

        return mm_inputs

    @override
    def process_messages(
        self,
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["ProcessorMixin"],
    ) -> list[dict[str, str]]:
        self._validate_input(processor, images, videos, audios)
        num_image_tokens = 0
        num_video_tokens = 0
        image_seqlen = getattr(processor, "image_seq_length") if self.expand_mm_tokens else 1
        messages = deepcopy(messages)
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor)

        image_pixel_patch_list = mm_inputs.get("image_num_patches")  # pathes of images
        video_num_patches = mm_inputs.get("video_num_patches")  # all patches for frames of videos
        video_patch_indices = mm_inputs.get("video_patch_indices")  # num frames of per video

        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

                content = content.replace(
                    IMAGE_PLACEHOLDER,
                    f"<img>{'<IMG_CONTEXT>' * image_seqlen * image_pixel_patch_list[num_image_tokens]}</img>",
                    1,
                )
                num_image_tokens += 1

            while VIDEO_PLACEHOLDER in content:
                if num_video_tokens >= len(videos):
                    raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")

                current_patch_index = video_patch_indices[num_video_tokens - 1] if num_video_tokens > 0 else 0
                end_patch_index = video_patch_indices[num_video_tokens]
                num_patches = list(video_num_patches[current_patch_index:end_patch_index])
                video_replaced_prompt = "\n".join(
                    f"Frame{i + 1}: <img>{'<IMG_CONTEXT>' * image_seqlen * num_patches[i]}</img>"
                    for i in range(len(num_patches))
                )
                content = content.replace(VIDEO_PLACEHOLDER, video_replaced_prompt, 1)
                num_video_tokens += 1

            message["content"] = content

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        if len(videos) != num_video_tokens:
            raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.")

        return messages

    @override
    def get_mm_inputs(
        self,
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["ProcessorMixin"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
        self._validate_input(processor, images, videos, audios)
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
        mm_inputs.pop("image_num_patches", None)
        mm_inputs.pop("video_patch_indices", None)
        mm_inputs.pop("video_num_patches", None)
        return mm_inputs


chenych's avatar
chenych committed
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
class KimiVLPlugin(BasePlugin):
    @override
    def process_messages(self, messages, images, videos, audios, processor):
        self._validate_input(processor, images, videos, audios)
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)

        image_grid_hws = mm_inputs.get("image_grid_hws", [])
        num_image_tokens = 0
        image_processor: BaseImageProcessor = getattr(processor, "image_processor")
        merge_length = math.prod(image_processor.merge_kernel_size)
        messages = deepcopy(messages)
        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
651
                if num_image_tokens >= len(images):
chenych's avatar
chenych committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

                image_seqlen = image_grid_hws[num_image_tokens].prod() // merge_length if self.expand_mm_tokens else 1
                content = content.replace(
                    IMAGE_PLACEHOLDER,
                    f"<|media_start|>image<|media_content|>{self.image_token * image_seqlen}<|media_end|>",
                    1,
                )
                num_image_tokens += 1

            message["content"] = content

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        return messages


chenych's avatar
chenych committed
670
@dataclass
chenych's avatar
chenych committed
671
class Llama4Plugin(BasePlugin):
luopl's avatar
luopl committed
672
673
674
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
675
676
677
678
679
680
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
681
        self._validate_input(processor, images, videos, audios)
chenych's avatar
chenych committed
682
683
684
685
686
687
688
689
690
691
692
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            if "pixel_values" in mm_inputs:
                image_height, image_width = mm_inputs["pixel_values"][0].shape[-2:]
                num_patches_per_chunk = int(
                    (image_height // processor.patch_size)
                    * (image_width // processor.patch_size)
                    // processor.downsample_ratio
                )
                aspect_ratios = mm_inputs.pop("aspect_ratios")

luopl's avatar
luopl committed
693
694
        num_image_tokens = 0
        messages = deepcopy(messages)
chenych's avatar
chenych committed
695
696
697
        for message in messages:
            content = message["content"]
            if self.expand_mm_tokens:
chenych's avatar
chenych committed
698
                placeholder_count = content.count(IMAGE_PLACEHOLDER)
chenych's avatar
chenych committed
699
700
701
702
703
                prompt_splits = content.split(IMAGE_PLACEHOLDER)
                new_content = []
                for local_image_index, split_part in enumerate(prompt_splits):
                    new_content.append(split_part)
                    if local_image_index < placeholder_count:
chenych's avatar
chenych committed
704
705
706
                        if num_image_tokens >= len(images):
                            raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
707
708
709
710
711
712
713
                        tokens_for_this_image = processor._prompt_split_image(
                            aspect_ratios[num_image_tokens], num_patches_per_chunk
                        )
                        num_image_tokens += 1
                        new_content.append(tokens_for_this_image)

                content = "".join(new_content)
chenych's avatar
chenych committed
714
715
            else:
                content = content.replace(IMAGE_PLACEHOLDER, self.image_token)
chenych's avatar
chenych committed
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

            message["content"] = content

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        return messages

    @override
    def get_mm_inputs(
        self,
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
        self._validate_input(processor, images, videos, audios)
chenych's avatar
chenych committed
737
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
chenych's avatar
chenych committed
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
        mm_inputs.pop("aspect_ratios", None)
        return mm_inputs


@dataclass
class LlavaPlugin(BasePlugin):
    @override
    def process_messages(
        self,
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
        self._validate_input(processor, images, videos, audios)
        num_image_tokens = 0
        messages = deepcopy(messages)
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            if "pixel_values" in mm_inputs:
                height, width = get_image_size(to_numpy_array(mm_inputs["pixel_values"][0]))
                image_seqlen = (height // processor.patch_size) * (
                    width // processor.patch_size
                ) + processor.num_additional_image_tokens
                if processor.vision_feature_select_strategy == "default":
                    image_seqlen -= 1
        else:
            image_seqlen = 1

        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
771
772
773
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
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
                content = content.replace(IMAGE_PLACEHOLDER, "{{image}}" * image_seqlen, 1)
                num_image_tokens += 1

            message["content"] = content.replace("{{image}}", self.image_token)

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        return messages


@dataclass
class LlavaNextPlugin(BasePlugin):
    @override
    def process_messages(
        self,
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
        self._validate_input(processor, images, videos, audios)
        num_image_tokens = 0
        messages = deepcopy(messages)
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            if "pixel_values" in mm_inputs:
                image_sizes = iter(mm_inputs["image_sizes"].tolist())
                height, width = get_image_size(to_numpy_array(mm_inputs["pixel_values"][0][0]))
luopl's avatar
luopl committed
804

luopl's avatar
luopl committed
805
806
        for message in messages:
            content = message["content"]
luopl's avatar
luopl committed
807
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
808
809
810
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

luopl's avatar
luopl committed
811
812
813
                if self.expand_mm_tokens:
                    orig_height, orig_width = next(image_sizes)
                    image_seqlen = processor._get_number_of_features(orig_height, orig_width, height, width)
chenych's avatar
chenych committed
814
                    if processor.vision_feature_select_strategy == "default":
luopl's avatar
luopl committed
815
816
817
                        image_seqlen -= 1
                else:
                    image_seqlen = 1
luopl's avatar
luopl committed
818
819

                content = content.replace(IMAGE_PLACEHOLDER, "{{image}}" * image_seqlen, 1)
luopl's avatar
luopl committed
820
                num_image_tokens += 1
luopl's avatar
luopl committed
821
822
823
824

            message["content"] = content.replace("{{image}}", self.image_token)

        if len(images) != num_image_tokens:
luopl's avatar
luopl committed
825
826
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

luopl's avatar
luopl committed
827
828
829
        return messages


chenych's avatar
chenych committed
830
@dataclass
luopl's avatar
luopl committed
831
832
833
834
class LlavaNextVideoPlugin(BasePlugin):
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
835
836
837
838
839
840
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
841
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
842
        num_image_tokens, num_video_tokens = 0, 0
luopl's avatar
luopl committed
843
        messages = deepcopy(messages)
chenych's avatar
chenych committed
844
845
846
847
848
849
850
851
852
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            if "pixel_values" in mm_inputs:
                image_sizes = iter(mm_inputs["image_sizes"].tolist())
                height, width = get_image_size(to_numpy_array(mm_inputs["pixel_values"][0][0]))

        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
853
854
855
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
                if self.expand_mm_tokens:
                    orig_height, orig_width = next(image_sizes)
                    image_seqlen = processor._get_number_of_features(orig_height, orig_width, height, width)
                    if processor.vision_feature_select_strategy == "default":
                        image_seqlen -= 1
                else:
                    image_seqlen = 1

                content = content.replace(IMAGE_PLACEHOLDER, "{{image}}" * image_seqlen, 1)
                num_image_tokens += 1

            message["content"] = content.replace("{{image}}", self.image_token)

        if self.expand_mm_tokens:
            if "pixel_values_videos" in mm_inputs:
                one_video = to_numpy_array(mm_inputs.get("pixel_values_videos")[0])
                height, width = get_image_size(one_video[0])
                num_frames = one_video.shape[0]  # frame dim is always after batch dim
chenych's avatar
chenych committed
874
875
                image_seqlen = (height // processor.patch_size) * (width // processor.patch_size)
                video_seqlen = image_seqlen // 4 * num_frames  # divide by 4 needed for avg pooling layer
chenych's avatar
chenych committed
876
877
        else:
            video_seqlen = 1
chenych's avatar
chenych committed
878

chenych's avatar
chenych committed
879
880
881
        for message in messages:
            content = message["content"]
            while VIDEO_PLACEHOLDER in content:
chenych's avatar
chenych committed
882
883
884
                if num_video_tokens >= len(videos):
                    raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
885
886
                content = content.replace(VIDEO_PLACEHOLDER, "{{video}}" * video_seqlen, 1)
                num_video_tokens += 1
luopl's avatar
luopl committed
887

chenych's avatar
chenych committed
888
            message["content"] = content.replace("{{video}}", self.video_token)
luopl's avatar
luopl committed
889
890

        if len(images) != num_image_tokens:
luopl's avatar
luopl committed
891
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
892
893

        if len(videos) != num_video_tokens:
luopl's avatar
luopl committed
894
            raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
895
896
897
898

        return messages


chenych's avatar
chenych committed
899
@dataclass
luopl's avatar
luopl committed
900
class MiniCPMVPlugin(BasePlugin):
chenych's avatar
chenych committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
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
943
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
    @override
    def _get_mm_inputs(
        self,
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: "MMProcessor",
        **kwargs,
    ) -> dict[str, "torch.Tensor"]:
        image_processor: BaseImageProcessor = getattr(processor, "image_processor")
        mm_inputs = {}
        if len(images) != 0:
            images = self._regularize_images(
                images,
                image_max_pixels=getattr(processor, "image_max_pixels", 768 * 768),
                image_min_pixels=getattr(processor, "image_min_pixels", 32 * 32),
            )["images"]
            if "valid_image_nums_ls" in kwargs:
                valid_image_nums_ls = kwargs["valid_image_nums_ls"]
                new_images = []
                idx = 0
                for valid_image_nums in valid_image_nums_ls:
                    new_images.append(images[idx : idx + valid_image_nums])
                    idx += valid_image_nums

                images = new_images

            image_inputs = image_processor(
                images, do_pad=True, max_slice_nums=image_processor.max_slice_nums, return_tensors="pt"
            )
            mm_inputs.update(image_inputs)

        if len(videos) != 0:
            videos = self._regularize_videos(
                videos,
                image_max_pixels=getattr(processor, "video_max_pixels", 256 * 256),
                image_min_pixels=getattr(processor, "video_min_pixels", 16 * 16),
                video_fps=getattr(processor, "video_fps", 2.0),
                video_maxlen=getattr(processor, "video_maxlen", 128),
            )["videos"]
            video_inputs = image_processor(videos, do_pad=True, max_slice_nums=2, return_tensors="pt")
            mm_inputs.update(video_inputs)

        if len(audios) != 0:
            audios = self._regularize_audios(
                audios,
                sampling_rate=getattr(processor, "audio_sampling_rate", 16000),
            )["audios"]
            if "valid_audio_nums_ls" in kwargs:
                valid_audio_nums_ls = kwargs["valid_audio_nums_ls"]
                audios_ls = []
                idx = 0
                for valid_audio_nums in valid_audio_nums_ls:
                    audios_ls.append(audios[idx : idx + valid_audio_nums])
                    idx += valid_audio_nums
            else:
                audios_ls = [audios]

            audio_features, audio_feature_lens, audio_phs = processor.audio_feature_extract(
                audios_ls,
                chunk_input=True,
                sampling_rate=getattr(processor, "audio_sampling_rate", 16000),
            )
            audio_feature_lens = [torch.tensor(audio_feature_len) for audio_feature_len in audio_feature_lens]
            mm_inputs.update({"audio_features": audio_features, "audio_feature_lens": audio_feature_lens})
            if kwargs.get("ret_phs", False):
                mm_inputs.update({"audio_phs": audio_phs})

        return mm_inputs

luopl's avatar
luopl committed
971
972
973
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
974
975
976
977
978
979
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
980
981
        self._validate_input(processor, images, videos, audios)
        num_image_tokens, num_video_tokens, num_audio_tokens = 0, 0, 0
luopl's avatar
luopl committed
982
        messages = deepcopy(messages)
chenych's avatar
chenych committed
983
        image_processor: BaseImageProcessor = getattr(processor, "image_processor")
chenych's avatar
chenych committed
984
        mm_inputs, audio_inputs = {}, {}
luopl's avatar
luopl committed
985
986
987
988
989
990
        if len(images) != 0 and len(videos) != 0:
            raise ValueError("MiniCPM-V model does not support input images and videos at the same time.")

        if len(videos) != 0:
            max_slice_nums = 2
            use_image_id = False
chenych's avatar
chenych committed
991
            mm_inputs = self._get_mm_inputs([], videos, [], processor)
luopl's avatar
luopl committed
992
993
994
995
        else:
            max_slice_nums = image_processor.max_slice_nums
            use_image_id = image_processor.use_image_id

chenych's avatar
chenych committed
996
        for i, message in enumerate(messages):
luopl's avatar
luopl committed
997
998
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
999
1000
1001
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

luopl's avatar
luopl committed
1002
                content = content.replace(IMAGE_PLACEHOLDER, "{{image}}", 1)
luopl's avatar
luopl committed
1003
                num_image_tokens += 1
luopl's avatar
luopl committed
1004
1005

            while VIDEO_PLACEHOLDER in content:
chenych's avatar
chenych committed
1006
1007
1008
                if num_video_tokens >= len(videos):
                    raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")

luopl's avatar
luopl committed
1009
1010
1011
1012
                video_seqlen = len(mm_inputs["pixel_values"][num_video_tokens]) if self.expand_mm_tokens else 1
                content = content.replace(VIDEO_PLACEHOLDER, "{{image}}" * video_seqlen, 1)
                num_video_tokens += 1

chenych's avatar
chenych committed
1013
            while AUDIO_PLACEHOLDER in content:
chenych's avatar
chenych committed
1014
1015
1016
                if num_audio_tokens >= len(audios):
                    raise ValueError(f"`len(audios)` is less than the number of {AUDIO_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
1017
1018
1019
1020
1021
1022
                content = content.replace(AUDIO_PLACEHOLDER, "{{audio}}", 1)
                num_audio_tokens += 1

            message["content"] = content.replace("{{image}}", "(<image>./</image>)").replace(
                "{{audio}}", "(<audio>./</audio>)"
            )
luopl's avatar
luopl committed
1023

chenych's avatar
chenych committed
1024
        if len(images):
chenych's avatar
chenych committed
1025
1026
            mm_inputs = self._get_mm_inputs(images, [], [], processor)

chenych's avatar
chenych committed
1027
        if len(audios):
chenych's avatar
chenych committed
1028
            audio_inputs = self._get_mm_inputs([], [], audios, processor, ret_phs=True)
luopl's avatar
luopl committed
1029

chenych's avatar
chenych committed
1030
        if self.expand_mm_tokens and mm_inputs:
luopl's avatar
luopl committed
1031
1032
            pattern = "(<image>./</image>)"
            image_sizes = mm_inputs["image_sizes"]
chenych's avatar
chenych committed
1033
            idx = 0
luopl's avatar
luopl committed
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
            for index, message in enumerate(messages):
                text = message["content"]
                image_tags = re.findall(pattern, text)
                text_chunks = text.split(pattern)
                final_text = ""
                for i in range(len(image_tags)):
                    final_text = (
                        final_text
                        + text_chunks[i]
                        + image_processor.get_slice_image_placeholder(
chenych's avatar
chenych committed
1044
                            image_sizes[0][idx], idx, max_slice_nums, use_image_id
luopl's avatar
luopl committed
1045
1046
                        )
                    )
chenych's avatar
chenych committed
1047
1048
1049
1050
1051
                    idx += 1

                final_text += text_chunks[-1]
                messages[index]["content"] = final_text

chenych's avatar
chenych committed
1052
        if self.expand_mm_tokens and audio_inputs:
chenych's avatar
chenych committed
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
            pattern = "(<audio>./</audio>)"
            idx = 0
            for index, message in enumerate(messages):
                text = message["content"]
                audio_tags = re.findall(pattern, text)
                text_chunks = text.split(pattern)
                final_text = ""
                for i in range(len(audio_tags)):
                    audio_placeholder = audio_inputs["audio_phs"][0][idx]
                    final_text = final_text + text_chunks[i] + audio_placeholder
                    idx += 1
luopl's avatar
luopl committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073

                final_text += text_chunks[-1]
                messages[index]["content"] = final_text

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        if len(videos) != num_video_tokens:
            raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
1074
1075
1076
        if len(audios) != num_audio_tokens:
            raise ValueError(f"The number of audios does not match the number of {AUDIO_PLACEHOLDER} tokens.")

luopl's avatar
luopl committed
1077
1078
1079
1080
1081
        return messages

    @override
    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
1082
1083
1084
1085
1086
1087
1088
1089
1090
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
chenych's avatar
chenych committed
1091
1092
        self._validate_input(processor, images, videos, audios)
        # image bound
luopl's avatar
luopl committed
1093
1094
        image_bounds_list = []
        valid_image_nums_ls = []
chenych's avatar
chenych committed
1095
        for i, input_ids in enumerate(batch_ids):
luopl's avatar
luopl committed
1096
1097
1098
1099
1100
1101
1102
1103
            input_ids_ = torch.tensor(input_ids)
            start_cond = (input_ids_ == processor.tokenizer.im_start_id) | (
                input_ids_ == processor.tokenizer.slice_start_id
            )
            end_cond = (input_ids_ == processor.tokenizer.im_end_id) | (input_ids_ == processor.tokenizer.slice_end_id)
            image_start_tokens = torch.where(start_cond)[0]
            image_start_tokens += 1
            image_end_tokens = torch.where(end_cond)[0]
chenych's avatar
chenych committed
1104
            valid_image_nums_ls.append(imglens[i])
luopl's avatar
luopl committed
1105
1106
            image_bounds = torch.hstack(
                [
chenych's avatar
chenych committed
1107
1108
                    image_start_tokens.unsqueeze(-1),
                    image_end_tokens.unsqueeze(-1),
luopl's avatar
luopl committed
1109
1110
1111
1112
                ]
            )
            image_bounds_list.append(image_bounds)

chenych's avatar
chenych committed
1113
1114
1115
1116
1117
        mm_inputs = self._get_mm_inputs(images, videos, [], processor, valid_image_nums_ls=valid_image_nums_ls)
        if "tgt_sizes" not in mm_inputs:
            dummy_data = [torch.empty(0) for _ in range(len(batch_ids))]
            mm_inputs.update({"tgt_sizes": dummy_data, "pixel_values": dummy_data, "image_sizes": dummy_data})

luopl's avatar
luopl committed
1118
        mm_inputs.update({"image_bound": image_bounds_list})
chenych's avatar
chenych committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144

        if len(audios) > 0:
            # audio bound
            audio_bounds_ls = []
            spk_bounds_ls = []
            valid_audio_nums_ls = []

            for input_ids, audiolen in zip(batch_ids, audlens):
                input_ids_ = torch.tensor(input_ids)
                audio_start_idx = torch.where(input_ids_ == processor.tokenizer.audio_start_id)[0]
                audio_end_idx = torch.where(input_ids_ == processor.tokenizer.audio_end_id)[0]
                assert len(audio_start_idx) == len(audio_end_idx)
                audio_bounds = torch.hstack([(audio_start_idx + 1).unsqueeze(-1), audio_end_idx.unsqueeze(-1)])
                audio_bounds_ls.append(audio_bounds)
                valid_audio_nums_ls.append(audiolen)

                spk_start_idx = torch.where(input_ids_ == processor.tokenizer.spk_start_id)[0]
                spk_end_idx = torch.where(input_ids_ == processor.tokenizer.spk_end_id)[0]
                assert len(spk_start_idx) == len(spk_end_idx)
                spk_bounds = torch.hstack([(spk_start_idx + 1).unsqueeze(-1), spk_end_idx.unsqueeze(-1)])
                spk_bounds_ls.append(spk_bounds)

            audio_inputs = self._get_mm_inputs([], [], audios, processor, valid_audio_nums_ls=valid_audio_nums_ls)
            mm_inputs.update(audio_inputs)
            mm_inputs.update({"audio_bounds": audio_bounds_ls, "spk_bounds": spk_bounds_ls})

luopl's avatar
luopl committed
1145
1146
1147
        return mm_inputs


chenych's avatar
chenych committed
1148
@dataclass
luopl's avatar
luopl committed
1149
1150
1151
1152
class MllamaPlugin(BasePlugin):
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
1153
1154
1155
1156
1157
1158
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1159
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
        num_image_tokens = 0
        messages = deepcopy(messages)
        for message in messages:
            content = message["content"]
            num_image_tokens += content.count(IMAGE_PLACEHOLDER)
            message["content"] = content.replace(IMAGE_PLACEHOLDER, self.image_token)

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        return messages

chenych's avatar
chenych committed
1172
    @override
luopl's avatar
luopl committed
1173
1174
    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
1175
1176
1177
1178
1179
1180
1181
1182
1183
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
chenych's avatar
chenych committed
1184
1185
1186
1187
        self._validate_input(processor, images, videos, audios)
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor, imglens)
        if mm_inputs:
            num_tiles = mm_inputs.pop("num_tiles")
chenych's avatar
chenych committed
1188
1189
            image_token_id: int = getattr(processor, "image_token_id")
            max_image_tiles: int = getattr(processor.image_processor, "max_image_tiles")
chenych's avatar
chenych committed
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
            cross_attention_token_mask = [
                get_cross_attention_token_mask(input_ids, image_token_id) for input_ids in batch_ids
            ]
            mm_inputs["cross_attention_mask"] = torch.from_numpy(
                convert_sparse_cross_attention_mask_to_dense(
                    cross_attention_token_mask,
                    num_tiles=num_tiles,
                    max_num_tiles=max_image_tiles,
                    length=max(len(input_ids) for input_ids in batch_ids),
                )
            )  # shape: (batch_size, length, max_num_images, max_num_tiles)

luopl's avatar
luopl committed
1202
1203
1204
        return mm_inputs


chenych's avatar
chenych committed
1205
@dataclass
luopl's avatar
luopl committed
1206
1207
1208
1209
class PaliGemmaPlugin(BasePlugin):
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
1210
1211
1212
1213
1214
1215
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1216
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
1217
1218
1219
1220
1221
        num_image_tokens = 0
        messages = deepcopy(messages)
        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
1222
                content = content.replace(IMAGE_PLACEHOLDER, "", 1)
luopl's avatar
luopl committed
1223
                num_image_tokens += 1
luopl's avatar
luopl committed
1224

chenych's avatar
chenych committed
1225
            message["content"] = content
luopl's avatar
luopl committed
1226
1227

        if len(images) != num_image_tokens:
luopl's avatar
luopl committed
1228
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1229
1230
1231
1232
1233
1234

        return messages

    @override
    def process_token_ids(
        self,
chenych's avatar
chenych committed
1235
1236
1237
1238
1239
        input_ids: list[int],
        labels: Optional[list[int]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
luopl's avatar
luopl committed
1240
        tokenizer: "PreTrainedTokenizer",
chenych's avatar
chenych committed
1241
1242
        processor: Optional["MMProcessor"],
    ) -> tuple[list[int], Optional[list[int]]]:
chenych's avatar
chenych committed
1243
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
1244
        num_images = len(images)
chenych's avatar
chenych committed
1245
        image_seqlen = processor.image_seq_length if self.expand_mm_tokens else 0  # skip mm token
luopl's avatar
luopl committed
1246
        image_token_id = tokenizer.convert_tokens_to_ids(self.image_token)
chenych's avatar
chenych committed
1247
        input_ids = [image_token_id] * num_images * image_seqlen + input_ids
luopl's avatar
luopl committed
1248
        if labels is not None:
chenych's avatar
chenych committed
1249
            labels = [IGNORE_INDEX] * num_images * image_seqlen + labels
luopl's avatar
luopl committed
1250
1251
1252
1253
1254
1255

        return input_ids, labels

    @override
    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
1256
1257
1258
1259
1260
1261
1262
1263
1264
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
chenych's avatar
chenych committed
1265
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
1266
        seqlens = [len(input_ids) for input_ids in batch_ids]
chenych's avatar
chenych committed
1267
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
luopl's avatar
luopl committed
1268
1269
1270
1271
        mm_inputs["token_type_ids"] = _get_paligemma_token_type_ids(imglens, seqlens, processor)
        return mm_inputs


chenych's avatar
chenych committed
1272
@dataclass
luopl's avatar
luopl committed
1273
1274
1275
1276
class PixtralPlugin(BasePlugin):
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
1277
1278
1279
1280
1281
1282
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1283
        self._validate_input(processor, images, videos, audios)
luopl's avatar
luopl committed
1284
1285
        num_image_tokens = 0
        messages = deepcopy(messages)
chenych's avatar
chenych committed
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            if "pixel_values" in mm_inputs:
                # BC for transformers < 4.49.0
                if isinstance(mm_inputs["image_sizes"], list):
                    image_sizes = iter(mm_inputs["image_sizes"][0])
                else:
                    image_sizes = iter(mm_inputs["image_sizes"].tolist())
                image_break_token: str = getattr(processor, "image_break_token")
                image_end_token: str = getattr(processor, "image_end_token")
chenych's avatar
chenych committed
1296

luopl's avatar
luopl committed
1297
1298
1299
        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
1300
1301
1302
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

luopl's avatar
luopl committed
1303
                if self.expand_mm_tokens:
chenych's avatar
chenych committed
1304
                    height, width = next(image_sizes)
chenych's avatar
chenych committed
1305
1306
1307
                    num_height_tokens = height // processor.patch_size
                    num_width_tokens = width // processor.patch_size
                    replace_tokens = [[self.image_token] * num_width_tokens + [image_break_token]] * num_height_tokens
luopl's avatar
luopl committed
1308
1309
1310
1311
                    replace_tokens = [item for sublist in replace_tokens for item in sublist]  # flatten list
                    replace_tokens[-1] = image_end_token
                    replace_str = "".join(replace_tokens)
                else:
chenych's avatar
chenych committed
1312
                    replace_str = self.image_token
luopl's avatar
luopl committed
1313

luopl's avatar
luopl committed
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
                content = content.replace(IMAGE_PLACEHOLDER, replace_str, 1)
                num_image_tokens += 1

            message["content"] = content

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        return messages

    @override
    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
1327
1328
1329
1330
1331
1332
1333
1334
1335
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
chenych's avatar
chenych committed
1336
1337
        self._validate_input(processor, images, videos, audios)
        mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
chenych's avatar
chenych committed
1338
1339
1340
1341
1342
        # ref to this commit https://github.com/huggingface/transformers/pull/35122
        # after transformers 4.49.0, the `image_sizes` is mandatory as an input parameter for Pixtral VisionEncoder forwarding.
        # it can be passed into `LlavaConditionalGeneration` as a parameter.
        if not is_transformers_version_greater_than("4.49.0"):
            mm_inputs.pop("image_sizes", None)
luopl's avatar
luopl committed
1343
1344
1345
        return mm_inputs


chenych's avatar
chenych committed
1346
1347
1348
1349
1350
@dataclass
class Qwen2AudioPlugin(BasePlugin):
    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
1351
1352
1353
1354
1355
1356
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1357
1358
1359
        self._validate_input(processor, images, videos, audios)
        bos_token: str = getattr(processor, "audio_bos_token")
        eos_token: str = getattr(processor, "audio_eos_token")
chenych's avatar
chenych committed
1360
        num_audio_tokens = 0
chenych's avatar
chenych committed
1361
        messages = deepcopy(messages)
chenych's avatar
chenych committed
1362
1363
1364
1365
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs([], [], audios, processor)
            if "feature_attention_mask" in mm_inputs:
                audio_lengths = mm_inputs["feature_attention_mask"].sum(-1).tolist()
chenych's avatar
chenych committed
1366
1367
1368
1369

        for message in messages:
            content = message["content"]
            while AUDIO_PLACEHOLDER in content:
chenych's avatar
chenych committed
1370
1371
1372
                if num_audio_tokens >= len(audios):
                    raise ValueError(f"`len(audios)` is less than the number of {AUDIO_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
                if self.expand_mm_tokens:
                    audio_length = audio_lengths.pop(0)
                    input_length = (audio_length - 1) // 2 + 1
                    audio_seqlen = (input_length - 2) // 2 + 1
                else:
                    audio_seqlen = 1

                content = content.replace(
                    AUDIO_PLACEHOLDER, f"{bos_token}{self.audio_token * audio_seqlen}{eos_token}", 1
                )
                num_audio_tokens += 1

            message["content"] = content

        if len(audios) != num_audio_tokens:
            raise ValueError(f"The number of audios does not match the number of {AUDIO_PLACEHOLDER} tokens.")

        return messages

    @override
    def get_mm_inputs(
        self,
chenych's avatar
chenych committed
1395
1396
1397
1398
1399
1400
1401
1402
1403
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        imglens: list[int],
        vidlens: list[int],
        audlens: list[int],
        batch_ids: list[list[int]],
        processor: Optional["MMProcessor"],
    ) -> dict[str, Union[list[int], "torch.Tensor"]]:
chenych's avatar
chenych committed
1404
1405
1406
1407
1408
1409
        self._validate_input(processor, images, videos, audios)
        return self._get_mm_inputs(images, videos, audios, processor)


@dataclass
class Qwen2VLPlugin(BasePlugin):
luopl's avatar
luopl committed
1410
1411
1412
1413
1414
    @override
    def _preprocess_image(self, image: "ImageObject", **kwargs) -> "ImageObject":
        image = super()._preprocess_image(image, **kwargs)
        if min(image.width, image.height) < 28:
            width, height = max(image.width, 28), max(image.height, 28)
chenych's avatar
chenych committed
1415
            image = image.resize((width, height))
luopl's avatar
luopl committed
1416
1417
1418

        if image.width / image.height > 200:
            width, height = image.height * 180, image.height
chenych's avatar
chenych committed
1419
            image = image.resize((width, height))
luopl's avatar
luopl committed
1420
1421
1422

        if image.height / image.width > 200:
            width, height = image.width, image.width * 180
chenych's avatar
chenych committed
1423
            image = image.resize((width, height))
luopl's avatar
luopl committed
1424
1425
1426
1427

        return image

    @override
chenych's avatar
chenych committed
1428
    def _regularize_videos(
chenych's avatar
chenych committed
1429
1430
        self, videos: list["VideoInput"], **kwargs
    ) -> dict[str, Union[list[list["ImageObject"]], list[float]]]:
chenych's avatar
chenych committed
1431
        results, fps_per_video = [], []
luopl's avatar
luopl committed
1432
1433
1434
        for video in videos:
            container = av.open(video, "r")
            video_stream = next(stream for stream in container.streams if stream.type == "video")
chenych's avatar
chenych committed
1435
            sample_indices = self._get_video_sample_indices(video_stream, **kwargs)
chenych's avatar
chenych committed
1436
            frames: list[ImageObject] = []
luopl's avatar
luopl committed
1437
1438
1439
1440
1441
1442
1443
1444
            container.seek(0)
            for frame_idx, frame in enumerate(container.decode(video_stream)):
                if frame_idx in sample_indices:
                    frames.append(frame.to_image())

            if len(frames) % 2 != 0:  # qwen2-vl requires even number of frames
                frames.append(frames[-1])

chenych's avatar
chenych committed
1445
            frames = self._regularize_images(frames, **kwargs)["images"]
luopl's avatar
luopl committed
1446
            results.append(frames)
chenych's avatar
chenych committed
1447
1448
1449
1450
            if video_stream.duration is None:
                fps_per_video.append(2.0)
            else:
                fps_per_video.append(len(sample_indices) / float(video_stream.duration * video_stream.time_base))
luopl's avatar
luopl committed
1451

chenych's avatar
chenych committed
1452
        return {"videos": results, "fps_per_video": fps_per_video}
chenych's avatar
chenych committed
1453
1454
1455
1456

    @override
    def _get_mm_inputs(
        self,
chenych's avatar
chenych committed
1457
1458
1459
1460
1461
1462
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: "MMProcessor",
    ) -> dict[str, "torch.Tensor"]:
        image_processor: BaseImageProcessor = getattr(processor, "image_processor", None)
chenych's avatar
chenych committed
1463
1464
1465
1466
1467
1468
        mm_inputs = {}
        if len(images) != 0:
            images = self._regularize_images(
                images,
                image_max_pixels=getattr(processor, "image_max_pixels", 768 * 768),
                image_min_pixels=getattr(processor, "image_min_pixels", 32 * 32),
chenych's avatar
chenych committed
1469
            )["images"]
chenych's avatar
chenych committed
1470
1471
1472
            mm_inputs.update(image_processor(images, return_tensors="pt"))

        if len(videos) != 0:
chenych's avatar
chenych committed
1473
            video_data = self._regularize_videos(
chenych's avatar
chenych committed
1474
1475
1476
1477
1478
1479
                videos,
                image_max_pixels=getattr(processor, "video_max_pixels", 256 * 256),
                image_min_pixels=getattr(processor, "video_min_pixels", 16 * 16),
                video_fps=getattr(processor, "video_fps", 2.0),
                video_maxlen=getattr(processor, "video_maxlen", 128),
            )
chenych's avatar
chenych committed
1480
1481
1482
1483
            mm_inputs.update(image_processor(images=None, videos=video_data["videos"], return_tensors="pt"))
            temporal_patch_size: int = getattr(image_processor, "temporal_patch_size", 2)
            if "second_per_grid_ts" in processor.model_input_names:
                mm_inputs["second_per_grid_ts"] = [temporal_patch_size / fps for fps in video_data["fps_per_video"]]
chenych's avatar
chenych committed
1484
1485

        return mm_inputs
luopl's avatar
luopl committed
1486
1487
1488
1489

    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
1490
1491
1492
1493
1494
1495
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1496
1497
1498
        self._validate_input(processor, images, videos, audios)
        num_image_tokens, num_video_tokens = 0, 0
        messages = deepcopy(messages)
chenych's avatar
chenych committed
1499
        image_processor: BaseImageProcessor = getattr(processor, "image_processor")
chenych's avatar
chenych committed
1500

luopl's avatar
luopl committed
1501
        merge_length: int = getattr(image_processor, "merge_size") ** 2
chenych's avatar
chenych committed
1502
1503
1504
1505
1506
1507
1508
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            image_grid_thw = mm_inputs.get("image_grid_thw", [])
            video_grid_thw = mm_inputs.get("video_grid_thw", [])
        else:
            image_grid_thw = [None] * len(images)
            video_grid_thw = [None] * len(videos)
luopl's avatar
luopl committed
1509
1510
1511
1512

        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
1513
                if num_image_tokens >= len(images):
luopl's avatar
luopl committed
1514
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1515

luopl's avatar
luopl committed
1516
                image_seqlen = image_grid_thw[num_image_tokens].prod() // merge_length if self.expand_mm_tokens else 1
luopl's avatar
luopl committed
1517
                content = content.replace(
luopl's avatar
luopl committed
1518
                    IMAGE_PLACEHOLDER, f"<|vision_start|>{self.image_token * image_seqlen}<|vision_end|>", 1
luopl's avatar
luopl committed
1519
1520
1521
1522
                )
                num_image_tokens += 1

            while VIDEO_PLACEHOLDER in content:
chenych's avatar
chenych committed
1523
                if num_video_tokens >= len(videos):
luopl's avatar
luopl committed
1524
                    raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1525

luopl's avatar
luopl committed
1526
                video_seqlen = video_grid_thw[num_video_tokens].prod() // merge_length if self.expand_mm_tokens else 1
luopl's avatar
luopl committed
1527
                content = content.replace(
luopl's avatar
luopl committed
1528
                    VIDEO_PLACEHOLDER, f"<|vision_start|>{self.video_token * video_seqlen}<|vision_end|>", 1
luopl's avatar
luopl committed
1529
1530
1531
1532
1533
1534
                )
                num_video_tokens += 1

            message["content"] = content

        if len(images) != num_image_tokens:
luopl's avatar
luopl committed
1535
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1536
1537

        if len(videos) != num_video_tokens:
luopl's avatar
luopl committed
1538
            raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1539
1540
1541

        return messages

chenych's avatar
chenych committed
1542
1543

class Qwen2OmniPlugin(Qwen2VLPlugin):
luopl's avatar
luopl committed
1544
    @override
chenych's avatar
chenych committed
1545
    def _get_mm_inputs(
luopl's avatar
luopl committed
1546
        self,
chenych's avatar
chenych committed
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: "MMProcessor",
    ) -> dict[str, "torch.Tensor"]:
        image_processor: BaseImageProcessor = getattr(processor, "image_processor", None)
        feature_extractor: SequenceFeatureExtractor = getattr(processor, "feature_extractor", None)
        mm_inputs = {}
        if len(images) != 0:
            images = self._regularize_images(
                images,
                image_max_pixels=getattr(processor, "image_max_pixels", 768 * 768),
                image_min_pixels=getattr(processor, "image_min_pixels", 32 * 32),
            )["images"]
            mm_inputs.update(image_processor(images, return_tensors="pt"))
chenych's avatar
chenych committed
1562

chenych's avatar
chenych committed
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
        if len(videos) != 0:
            video_dict = self._regularize_videos(
                videos,
                image_max_pixels=getattr(processor, "video_max_pixels", 256 * 256),
                image_min_pixels=getattr(processor, "video_min_pixels", 16 * 16),
                video_fps=getattr(processor, "video_fps", 2.0),
                video_maxlen=getattr(processor, "video_maxlen", 128),
            )
            mm_inputs.update(image_processor(images=None, videos=video_dict["videos"], return_tensors="pt"))
            temporal_patch_size: int = getattr(image_processor, "temporal_patch_size", 2)
            mm_inputs["video_second_per_grid"] = torch.tensor(
                [temporal_patch_size / fps for fps in video_dict["fps_per_video"]]
            )

        if len(audios) != 0:
            audios = self._regularize_audios(
                audios,
                sampling_rate=getattr(processor, "audio_sampling_rate", 16000),
            )["audios"]
            mm_inputs.update(
                feature_extractor(
                    audios,
                    sampling_rate=getattr(processor, "audio_sampling_rate", 16000),
                    return_attention_mask=True,
                    padding="max_length",
                    return_tensors="pt",
                )
            )
            mm_inputs["feature_attention_mask"] = mm_inputs.pop("attention_mask")  # prevent conflicts
luopl's avatar
luopl committed
1592

chenych's avatar
chenych committed
1593
        return mm_inputs
luopl's avatar
luopl committed
1594
1595
1596
1597

    @override
    def process_messages(
        self,
chenych's avatar
chenych committed
1598
1599
1600
1601
1602
1603
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1604
        self._validate_input(processor, images, videos, audios)
chenych's avatar
chenych committed
1605
        num_image_tokens, num_video_tokens, num_audio_tokens = 0, 0, 0
luopl's avatar
luopl committed
1606
        messages = deepcopy(messages)
chenych's avatar
chenych committed
1607
1608
1609
1610
        image_processor: BaseImageProcessor = getattr(processor, "image_processor", None)

        merge_length = processor.image_processor.merge_size**2
        use_audio_in_video = getattr(processor, "use_audio_in_video", False)
chenych's avatar
chenych committed
1611
1612
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
chenych's avatar
chenych committed
1613
1614
1615
1616
1617
            image_grid_thw = mm_inputs.get("image_grid_thw", [])
            video_grid_thw = mm_inputs.get("video_grid_thw", [])
            if "feature_attention_mask" in mm_inputs:
                input_lengths = (mm_inputs["feature_attention_mask"].sum(-1).numpy() - 1) // 2 + 1
                audio_lengths = (input_lengths - 2) // 2 + 1
chenych's avatar
chenych committed
1618
1619
        else:
            mm_inputs = {}
chenych's avatar
chenych committed
1620
1621
1622
            image_grid_thw = [None] * len(images)
            video_grid_thw = [None] * len(videos)
            audio_lengths = [None] * len(audios)
chenych's avatar
chenych committed
1623
1624
1625
1626

        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
1627
                if num_image_tokens >= len(images):
chenych's avatar
chenych committed
1628
1629
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
1630
                image_seqlen = image_grid_thw[num_image_tokens].prod() // merge_length if self.expand_mm_tokens else 1
chenych's avatar
chenych committed
1631
                content = content.replace(
chenych's avatar
chenych committed
1632
                    IMAGE_PLACEHOLDER, f"<|vision_bos|>{self.image_token * image_seqlen}<|vision_eos|>", 1
chenych's avatar
chenych committed
1633
1634
                )
                num_image_tokens += 1
luopl's avatar
luopl committed
1635

chenych's avatar
chenych committed
1636
1637
1638
1639
1640
1641
            if (
                use_audio_in_video and len(audios) and len(videos)
            ):  # if use the audio of video # deal video token and audio token togather
                if len(videos) != len(audios):
                    raise ValueError(
                        f"Number of videos ({len(videos)}) must match number of audios ({len(audios)}) when using audio in video."
chenych's avatar
chenych committed
1642
                    )
luopl's avatar
luopl committed
1643
1644

                while VIDEO_PLACEHOLDER in content:
chenych's avatar
chenych committed
1645
                    if num_video_tokens >= len(videos):
chenych's avatar
chenych committed
1646
                        raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")
chenych's avatar
chenych committed
1647
1648
                    if num_audio_tokens >= len(audios):
                        raise ValueError(f"`len(audios)` is less than the number of {AUDIO_PLACEHOLDER} tokens.")
chenych's avatar
chenych committed
1649

chenych's avatar
chenych committed
1650
1651
1652
1653
1654
1655
                    video_pos = content.find(VIDEO_PLACEHOLDER)
                    audio_pos = content.find(AUDIO_PLACEHOLDER, video_pos)
                    if audio_pos == -1 or audio_pos < video_pos:
                        raise ValueError(
                            f"Each {VIDEO_PLACEHOLDER} must be followed by an {AUDIO_PLACEHOLDER} when using audio in video."
                        )
chenych's avatar
chenych committed
1656

chenych's avatar
chenych committed
1657
1658
1659
1660
1661
1662
                    audio_t_index = torch.arange(audio_lengths[num_audio_tokens])
                    video_t_index = (
                        torch.arange(video_grid_thw[num_video_tokens][0])
                        .view(-1, 1, 1)
                        .expand(
                            -1,
chenych's avatar
chenych committed
1663
1664
                            video_grid_thw[num_video_tokens][1] // image_processor.merge_size,
                            video_grid_thw[num_video_tokens][2] // image_processor.merge_size,
chenych's avatar
chenych committed
1665
1666
1667
1668
1669
1670
1671
                        )
                        .flatten()
                        * mm_inputs["video_second_per_grid"][num_video_tokens]
                        * 25  # FIXME hardcode of position_id_per_seconds=25
                    ).long()
                    t_ntoken_per_chunk = 50  # FIXME hardcode: [25 * 2]
                    video_chunk_indices = processor.get_chunked_index(video_t_index, t_ntoken_per_chunk)
chenych's avatar
chenych committed
1672
                    audio_chunk_indices = processor.get_chunked_index(audio_t_index, t_ntoken_per_chunk)
chenych's avatar
chenych committed
1673
                    placeholder_string = ""
chenych's avatar
chenych committed
1674
                    placeholder_string += "<|vision_bos|>" + "<|audio_bos|>"
chenych's avatar
chenych committed
1675
1676
1677
1678
1679
                    for j in range(max(len(video_chunk_indices), len(audio_chunk_indices))):
                        video_chunk_index = video_chunk_indices[j] if j < len(video_chunk_indices) else None
                        audio_chunk_index = audio_chunk_indices[j] if j < len(audio_chunk_indices) else None
                        if video_chunk_index is not None:
                            placeholder_string += self.video_token * (video_chunk_index[1] - video_chunk_index[0])
chenych's avatar
chenych committed
1680

chenych's avatar
chenych committed
1681
1682
1683
                        if audio_chunk_index is not None:
                            placeholder_string += self.audio_token * (audio_chunk_index[1] - audio_chunk_index[0])

chenych's avatar
chenych committed
1684
                    placeholder_string += "<|audio_eos|>" + "<|vision_eos|>"
chenych's avatar
chenych committed
1685
1686
1687
1688
                    content = content.replace(VIDEO_PLACEHOLDER, placeholder_string, 1)
                    content = content.replace(AUDIO_PLACEHOLDER, "", 1)
                    num_audio_tokens += 1
                    num_video_tokens += 1
chenych's avatar
chenych committed
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
            else:
                while AUDIO_PLACEHOLDER in content:
                    if num_audio_tokens >= len(audios):
                        raise ValueError(f"`len(audios)` is less than the number of {AUDIO_PLACEHOLDER} tokens.")

                    audio_seqlen = audio_lengths[num_audio_tokens] if self.expand_mm_tokens else 1
                    content = content.replace(
                        AUDIO_PLACEHOLDER, f"<|audio_bos|>{self.audio_token * audio_seqlen}<|audio_eos|>", 1
                    )
                    num_audio_tokens += 1

                while VIDEO_PLACEHOLDER in content:
                    if num_video_tokens >= len(videos):
                        raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")

                    video_seqlen = (
                        video_grid_thw[num_video_tokens].prod() // merge_length if self.expand_mm_tokens else 1
                    )
                    content = content.replace(
                        VIDEO_PLACEHOLDER, f"<|vision_bos|>{self.video_token * video_seqlen}<|vision_eos|>", 1
                    )
                    num_video_tokens += 1
chenych's avatar
chenych committed
1711
1712
1713
1714
1715

            message["content"] = content

        if len(audios) != num_audio_tokens:
            raise ValueError(f"The number of audios does not match the number of {AUDIO_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1716
1717

        if len(images) != num_image_tokens:
luopl's avatar
luopl committed
1718
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1719
1720

        if len(videos) != num_video_tokens:
luopl's avatar
luopl committed
1721
            raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.")
luopl's avatar
luopl committed
1722
1723
1724

        return messages

chenych's avatar
chenych committed
1725
1726
1727

@dataclass
class VideoLlavaPlugin(BasePlugin):
luopl's avatar
luopl committed
1728
    @override
chenych's avatar
chenych committed
1729
    def process_messages(
luopl's avatar
luopl committed
1730
        self,
chenych's avatar
chenych committed
1731
1732
1733
1734
1735
1736
        messages: list[dict[str, str]],
        images: list["ImageInput"],
        videos: list["VideoInput"],
        audios: list["AudioInput"],
        processor: Optional["MMProcessor"],
    ) -> list[dict[str, str]]:
chenych's avatar
chenych committed
1737
        self._validate_input(processor, images, videos, audios)
chenych's avatar
chenych committed
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
        num_image_tokens, num_video_tokens = 0, 0
        messages = deepcopy(messages)
        num_frames = 0
        if self.expand_mm_tokens:
            mm_inputs = self._get_mm_inputs(images, videos, audios, processor)
            if "pixel_values_images" in mm_inputs:
                height, width = get_image_size(to_numpy_array(mm_inputs["pixel_values_images"][0]))
                num_frames = 1

            if "pixel_values_videos" in mm_inputs:
                one_video = to_numpy_array(mm_inputs["pixel_values_videos"][0])
                height, width = get_image_size(one_video[0])
                num_frames = one_video.shape[0]  # frame dim is always after batch dim

            if "pixel_values_images" in mm_inputs or "pixel_values_videos" in mm_inputs:
                image_seqlen = (height // processor.patch_size) * (
                    width // processor.patch_size
                ) + processor.num_additional_image_tokens
                video_seqlen = image_seqlen * num_frames
                if processor.vision_feature_select_strategy == "default":
                    image_seqlen -= 1
        else:
            image_seqlen, video_seqlen = 1, 1

        for message in messages:
            content = message["content"]
            while IMAGE_PLACEHOLDER in content:
chenych's avatar
chenych committed
1765
1766
1767
                if num_image_tokens >= len(images):
                    raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
1768
1769
1770
1771
                content = content.replace(IMAGE_PLACEHOLDER, "{{image}}" * image_seqlen, 1)
                num_image_tokens += 1

            while VIDEO_PLACEHOLDER in content:
chenych's avatar
chenych committed
1772
1773
1774
                if num_video_tokens >= len(videos):
                    raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.")

chenych's avatar
chenych committed
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
                content = content.replace(VIDEO_PLACEHOLDER, "{{video}}" * video_seqlen, 1)
                num_video_tokens += 1

            content = content.replace("{{image}}", self.image_token)
            message["content"] = content.replace("{{video}}", self.video_token)

        if len(images) != num_image_tokens:
            raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens.")

        if len(videos) != num_video_tokens:
            raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens.")

        return messages
luopl's avatar
luopl committed
1788
1789
1790
1791


PLUGINS = {
    "base": BasePlugin,
chenych's avatar
chenych committed
1792
    "gemma3": Gemma3Plugin,
chenych's avatar
chenych committed
1793
    "intern_vl": InternVLPlugin,
chenych's avatar
chenych committed
1794
    "kimi_vl": KimiVLPlugin,
chenych's avatar
chenych committed
1795
    "llama4": Llama4Plugin,
luopl's avatar
luopl committed
1796
1797
1798
    "llava": LlavaPlugin,
    "llava_next": LlavaNextPlugin,
    "llava_next_video": LlavaNextVideoPlugin,
luopl's avatar
luopl committed
1799
1800
    "minicpm_v": MiniCPMVPlugin,
    "mllama": MllamaPlugin,
luopl's avatar
luopl committed
1801
    "paligemma": PaliGemmaPlugin,
luopl's avatar
luopl committed
1802
    "pixtral": PixtralPlugin,
chenych's avatar
chenych committed
1803
    "qwen2_audio": Qwen2AudioPlugin,
chenych's avatar
chenych committed
1804
    "qwen2_omni": Qwen2OmniPlugin,
chenych's avatar
chenych committed
1805
    "qwen2_vl": Qwen2VLPlugin,
luopl's avatar
luopl committed
1806
1807
1808
1809
    "video_llava": VideoLlavaPlugin,
}


chenych's avatar
chenych committed
1810
1811
def register_mm_plugin(name: str, plugin_class: type["BasePlugin"]) -> None:
    r"""Register a multimodal plugin."""
chenych's avatar
chenych committed
1812
1813
1814
1815
1816
1817
    if name in PLUGINS:
        raise ValueError(f"Multimodal plugin {name} already exists.")

    PLUGINS[name] = plugin_class


luopl's avatar
luopl committed
1818
1819
1820
1821
def get_mm_plugin(
    name: str,
    image_token: Optional[str] = None,
    video_token: Optional[str] = None,
chenych's avatar
chenych committed
1822
    audio_token: Optional[str] = None,
luopl's avatar
luopl committed
1823
) -> "BasePlugin":
chenych's avatar
chenych committed
1824
    r"""Get plugin for multimodal inputs."""
chenych's avatar
chenych committed
1825
    if name not in PLUGINS:
luopl's avatar
luopl committed
1826
        raise ValueError(f"Multimodal plugin `{name}` not found.")
luopl's avatar
luopl committed
1827

chenych's avatar
chenych committed
1828
    return PLUGINS[name](image_token, video_token, audio_token)