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

4
5
6
from abc import ABC, abstractmethod
from collections import UserDict
from collections.abc import Callable, Iterator, Mapping, Sequence
7
8
9
10
11
12
from typing import (
    TYPE_CHECKING,
    Any,
    Generic,
    Literal,
    NamedTuple,
13
14
    TypeAlias,
    TypeGuard,
15
16
    TypeVar,
)
17
18
19

import numpy as np
import torch
20
from typing_extensions import assert_never
21

22
from vllm.utils.collection_utils import is_list_of
23
from vllm.utils.import_utils import LazyLoader
24

25
from .audio import AudioResampler
26
27
28
29
30
31
32
33
34
35
36
37
from .inputs import (
    AudioItem,
    HfAudioItem,
    HfImageItem,
    HfVideoItem,
    ImageItem,
    ModalityData,
    MultiModalDataDict,
    MultiModalFieldConfig,
    MultiModalKwargsItems,
    VideoItem,
)
38
39
40
41

_T = TypeVar("_T")
_I = TypeVar("_I")

42
43
44
45
46
if TYPE_CHECKING:
    import PIL.Image as PILImage
else:
    PILImage = LazyLoader("PILImage", globals(), "PIL.Image")

47
48

class ModalityDataItems(ABC, Generic[_T, _I]):
49
    """
50
51
    Represents data items for a modality in
    [`MultiModalDataItems`][vllm.multimodal.parse.MultiModalDataItems].
52
    """
53

54
    def __init__(self, data: _T, modality: str) -> None:
55
56
        super().__init__()

57
        self.data: _T = data
58
59
60
        self.modality = modality

    def __repr__(self) -> str:
61
        return f"{type(self).__name__}(modality={self.modality!r}, len={len(self)})"
62
63
64
65
66
67
68
69
70

    def __len__(self) -> int:
        return self.get_count()

    def __getitem__(self, index: int) -> _I:
        return self.get(index)

    if TYPE_CHECKING:
        # Auto-generated
71
        def __iter__(self) -> Iterator[_I]: ...
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

    @abstractmethod
    def get_count(self) -> int:
        """Get the number of data items."""
        raise NotImplementedError

    @abstractmethod
    def get(self, index: int) -> _I:
        """Get a data item by its index."""
        raise NotImplementedError

    def get_all(self) -> list[_I]:
        """Get all data items."""
        return [self.get(idx) for idx in range(self.get_count())]

    @abstractmethod
    def get_processor_data(self) -> Mapping[str, object]:
        """Get the data to pass to the HF processor."""
        raise NotImplementedError

    @abstractmethod
    def get_passthrough_data(self) -> Mapping[str, object]:
        """Get the data to pass directly to the model."""
        raise NotImplementedError


class ProcessorBatchItems(ModalityDataItems[Sequence[_T], _T]):
99
    """Base class for data items that are arranged in a list."""
100
101
102
103
104
105
106
107
108
109
110
111
112
113

    def get_count(self) -> int:
        return len(self.data)

    def get(self, index: int) -> _T:
        return self.data[index]

    def get_processor_data(self) -> Mapping[str, object]:
        return {f"{self.modality}s": self.data}

    def get_passthrough_data(self) -> Mapping[str, object]:
        return {}


114
class EmbeddingItems(
115
    ModalityDataItems[torch.Tensor | list[torch.Tensor], torch.Tensor]
116
):
117
118
119
120
    """
    Base class for data items that are expressed as a batched embedding tensor,
    or a list of embedding tensors (one per item).
    """
121
122
123
124

    def get_count(self) -> int:
        return len(self.data)

125
    def get(self, index: int) -> torch.Tensor:
126
127
128
129
130
131
132
133
        return self.data[index]

    def get_processor_data(self) -> Mapping[str, object]:
        return {}

    def get_passthrough_data(self) -> Mapping[str, object]:
        return {f"{self.modality}_embeds": self.data}

134
135
136
    def get_feature_size(self, item_idx: int) -> int:
        return len(self.get(item_idx))

137

138
139
140
class DictEmbeddingItems(
    ModalityDataItems[Mapping[str, torch.Tensor], Mapping[str, torch.Tensor]]
):
141
142
143
144
145
146
147
148
149
150
151
    """
    Base class for data items that are expressed as a dictionary of tensors.

    Usually, the dictionary keys correspond to the outputs of HF processor.
    """

    def __init__(
        self,
        data: Mapping[str, torch.Tensor],
        modality: str,
        required_fields: set[str],
152
153
154
155
        fields_factory: Callable[
            [Mapping[str, torch.Tensor]],
            Mapping[str, MultiModalFieldConfig],
        ],
156
    ) -> None:
157
158
        from transformers.feature_extraction_utils import BatchFeature

159
160
161
162
163
        super().__init__(data, modality)

        missing_required_data_keys = required_fields - data.keys()
        if missing_required_data_keys:
            data_keys = set(data.keys())
164
165
166
167
            msg = (
                f"The data should contain the fields: {required_fields}, "
                f"but only found the following keys: {data_keys}"
            )
168
169
            raise ValueError(msg)

170
171
172
173
174
175
176
        fields_config = fields_factory(data)
        missing_required_fields = required_fields - fields_config.keys()
        if missing_required_fields:
            fields = set(fields_config.keys())
            msg = f"{required_fields=} should be a subset of {fields=}"
            raise ValueError(msg)

177
178
179
        self.fields_config = fields_config
        self.required_fields = required_fields

180
        self._kwargs = MultiModalKwargsItems.from_hf_inputs(
181
182
183
184
185
            BatchFeature(dict(data)),
            fields_config,
        )

    def get_count(self) -> int:
186
        return len(self._kwargs[self.modality])
187
188

    def get(self, index: int) -> Mapping[str, torch.Tensor]:
189
        return self._kwargs[self.modality][index].get_data()
190
191
192
193
194
195
196
197

    def get_processor_data(self) -> Mapping[str, object]:
        return {}

    def get_passthrough_data(self) -> Mapping[str, object]:
        return self.data


198
class AudioProcessorItems(ProcessorBatchItems[HfAudioItem]):
199
    def __init__(self, data: Sequence[HfAudioItem] | None) -> None:
200
201
        if data is None:
            data = [None]
202
203
        super().__init__(data, "audio")

204
205
206
207
    def get_audio_length(self, item_idx: int) -> int:
        audio = self.get(item_idx)
        return len(audio)

208
209

class AudioEmbeddingItems(EmbeddingItems):
210
    def __init__(self, data: torch.Tensor | list[torch.Tensor]) -> None:
211
212
213
214
215
216
217
218
219
        super().__init__(data, "audio")


class ImageSize(NamedTuple):
    width: int
    height: int


class ImageProcessorItems(ProcessorBatchItems[HfImageItem]):
220
    def __init__(self, data: Sequence[HfImageItem] | None) -> None:
221
222
        if data is None:
            data = [None]
223
224
225
226
227
        super().__init__(data, "image")

    def get_image_size(self, item_idx: int) -> ImageSize:
        image = self.get(item_idx)

228
        if isinstance(image, PILImage.Image):
229
230
231
232
233
234
235
236
237
            return ImageSize(*image.size)
        if isinstance(image, (np.ndarray, torch.Tensor)):
            _, h, w = image.shape
            return ImageSize(w, h)

        assert_never(image)


class ImageEmbeddingItems(EmbeddingItems):
238
    def __init__(self, data: torch.Tensor | list[torch.Tensor]) -> None:
239
240
241
242
        super().__init__(data, "image")


class VideoProcessorItems(ProcessorBatchItems[HfVideoItem]):
243
244
    def __init__(
        self,
245
246
        data: Sequence[HfVideoItem] | None,
        metadata: dict[str, Any] | list[dict[str, Any] | None] | None = None,
247
    ) -> None:
248
249
        if data is None:
            data = [None]
250
        super().__init__(data, "video")
251
        self.metadata = metadata
252

253
254
255
256
257
258
    def get_num_frames(self, item_idx: int) -> int:
        return len(self.get(item_idx))

    def get_frame_size(self, item_idx: int) -> ImageSize:
        image = self.get(item_idx)[0]  # Assume that the video isn't empty

259
        if isinstance(image, PILImage.Image):
260
261
262
263
264
265
266
            return ImageSize(*image.size)
        if isinstance(image, (np.ndarray, torch.Tensor)):
            _, h, w = image.shape
            return ImageSize(w, h)

        assert_never(image)

267
268

class VideoEmbeddingItems(EmbeddingItems):
269
    def __init__(self, data: torch.Tensor | list[torch.Tensor]) -> None:
270
271
272
273
274
275
276
277
        super().__init__(data, "video")


_D = TypeVar("_D", bound=ModalityDataItems[Any, Any])


class MultiModalDataItems(UserDict[str, ModalityDataItems[Any, Any]]):
    """
278
279
    As [`MultiModalDataDict`][vllm.multimodal.inputs.MultiModalDataDict], but
    normalized such that each entry corresponds to a list.
280
281
282
283
284
    """

    def get_count(self, modality: str, *, strict: bool = True) -> int:
        """
        Get the number of data items belonging to a modality.
285

286
        If `strict=False`, return `0` instead of raising [`KeyError`][]
287
288
289
290
291
        even if the modality is not found.
        """
        if modality not in self:
            if strict:
                available_modalities = set(self.keys())
292
293
294
295
                raise KeyError(
                    f"Modality {modality!r} not found. "
                    f"Available modalities: {available_modalities}"
                )
296
297
298
299
300
301
302
303
304
305
306
307

            return 0

        return self[modality].get_count()

    def get_all_counts(self) -> Mapping[str, int]:
        """Get the number of items belonging to each modality."""
        return {m: items.get_count() for m, items in self.items()}

    def get_items(
        self,
        modality: str,
308
        typ: type[_D] | tuple[type[_D], ...],
309
310
311
312
313
314
315
    ) -> _D:
        """
        Get the data items belonging to a modality,
        requiring that they belong to a certain type.
        """
        if modality not in self:
            available_modalities = set(self.keys())
316
317
318
319
            raise KeyError(
                f"Modality {modality!r} not found. "
                f"Available modalities: {available_modalities}"
            )
320
321
322

        items = self[modality]
        if not isinstance(items, typ):
323
324
325
326
327
            raise TypeError(
                f"Invalid type of data items for {modality=}. "
                f"Expected type: {typ}, but "
                f"found type: {type(items)}"
            )
328

329
        return items  # type: ignore[return-value]
330
331


332
ModalityDataParser: TypeAlias = Callable[
333
    [ModalityData[Any]], ModalityDataItems[Any, Any] | None
334
]
335
336
337
338


class MultiModalDataParser:
    """
339
340
    Parses [`MultiModalDataDict`][vllm.multimodal.inputs.MultiModalDataDict]
    into [`MultiModalDataItems`][vllm.multimodal.parse.MultiModalDataItems].
341
342
343
344

    Args:
        target_sr (float, optional): Enables automatic resampling of audio
            items to the model's expected sampling rate.
345
346
    """

347
348
349
    def __init__(
        self,
        *,
350
        target_sr: float | None = None,
351
        audio_resample_method: Literal["librosa", "scipy"] = "librosa",
352
        video_needs_metadata: bool = False,
353
    ) -> None:
354
355
        super().__init__()

356
357
358
359
        self.audio_resampler = AudioResampler(
            target_sr=target_sr,
            method=audio_resample_method,
        )
360
        self.video_needs_metadata = video_needs_metadata
361

362
363
364
    @classmethod
    def is_embeddings(
        cls, data: object
365
    ) -> TypeGuard[torch.Tensor | list[torch.Tensor]]:
366
367
368
        if isinstance(data, torch.Tensor):
            return data.ndim == 3
        if is_list_of(data, torch.Tensor):
369
            return data[0].ndim == 2  # type: ignore[index]
370
371
372
373
374
375
376
377

        return False

    def _is_empty(self, data: object) -> TypeGuard[None]:
        if isinstance(data, list):
            return len(data) == 0
        if isinstance(data, (np.ndarray, torch.Tensor)):
            return data.size == 0
378
379
380
381
382
383

        return False

    def _get_audio_with_sr(
        self,
        audio: AudioItem,
384
    ) -> tuple[np.ndarray, float | None]:
385
386
387
388
389
390
391
392
393
394
395
        if isinstance(audio, tuple):
            return audio
        if isinstance(audio, list):
            return np.array(audio), None
        if isinstance(audio, np.ndarray):
            return audio, None
        if isinstance(audio, torch.Tensor):
            return audio.numpy(), None

        assert_never(audio)

396
397
398
    def _get_video_with_metadata(
        self,
        video: VideoItem,
399
    ) -> tuple[np.ndarray, dict[str, Any] | None]:
400
401
402
403
404
405
406
407
408
409
410
        if isinstance(video, tuple):
            return video
        if isinstance(video, list):
            return np.array(video), None
        if isinstance(video, np.ndarray):
            return video, None
        if isinstance(video, torch.Tensor):
            return video.numpy(), None

        assert_never(video)

411
412
413
    def _parse_audio_data(
        self,
        data: ModalityData[AudioItem],
414
    ) -> ModalityDataItems[Any, Any] | None:
415
416
417
        if data is None:
            return AudioProcessorItems(None)

418
        # also check single audio item with sampling rate
419
420
421
        if self._is_empty(data) or (
            isinstance(data, tuple) and self._is_empty(data[0])
        ):
422
423
            return None

424
        if self.is_embeddings(data):
425
426
            return AudioEmbeddingItems(data)

427
        data_items: list[AudioItem]
428
429
430
431
432
433
        if (
            is_list_of(data, float)
            or isinstance(data, (np.ndarray, torch.Tensor))
            and data.ndim == 1
            or isinstance(data, tuple)
        ):
434
435
436
437
            data_items = [data]
        elif isinstance(data, (np.ndarray, torch.Tensor)):
            data_items = [elem for elem in data]
        else:
438
            data_items = data  # type: ignore[assignment]
439
440
441
442
443
444
445

        new_audios = list[np.ndarray]()
        for data_item in data_items:
            audio, orig_sr = self._get_audio_with_sr(data_item)
            if orig_sr is None:
                new_audio = audio
            else:
446
                new_audio = self.audio_resampler.resample(audio, orig_sr=orig_sr)
447
448
449
450
451
452
453
454

            new_audios.append(new_audio)

        return AudioProcessorItems(new_audios)

    def _parse_image_data(
        self,
        data: ModalityData[ImageItem],
455
    ) -> ModalityDataItems[Any, Any] | None:
456
457
458
        if data is None:
            return ImageProcessorItems(None)

459
460
461
        if self._is_empty(data):
            return None

462
        if self.is_embeddings(data):
463
464
            return ImageEmbeddingItems(data)

465
466
467
468
469
        if (
            isinstance(data, PILImage.Image)
            or isinstance(data, (np.ndarray, torch.Tensor))
            and data.ndim == 3
        ):
470
471
472
473
474
475
476
477
478
479
480
            data_items = [data]
        elif isinstance(data, (np.ndarray, torch.Tensor)):
            data_items = [elem for elem in data]
        else:
            data_items = data

        return ImageProcessorItems(data_items)

    def _parse_video_data(
        self,
        data: ModalityData[VideoItem],
481
    ) -> ModalityDataItems[Any, Any] | None:
482
483
484
        if data is None:
            return VideoProcessorItems(None)

485
486
487
        if self._is_empty(data):
            return None

488
        if self.is_embeddings(data):
489
490
            return VideoEmbeddingItems(data)

491
        data_items: list[VideoItem]
492
493
494
495
496
        if (
            is_list_of(data, PILImage.Image)
            or isinstance(data, (np.ndarray, torch.Tensor))
            and data.ndim == 4
        ):
497
498
499
            data_items = [data]
        elif isinstance(data, (np.ndarray, torch.Tensor)):
            data_items = [elem for elem in data]
500
501
        elif isinstance(data, tuple) and len(data) == 2:
            data_items = [data]
502
        else:
503
            data_items = data  # type: ignore[assignment]
504

505
506
        new_videos = list[tuple[np.ndarray, dict[str, Any] | None]]()
        metadata_lst: list[dict[str, Any] | None] = []
507
508
509
        for data_item in data_items:
            video, metadata = self._get_video_with_metadata(data_item)
            if self.video_needs_metadata:
510
511
512
513
514
                if metadata is None:
                    raise ValueError(
                        "Video metadata is required but not found in mm input. "
                        "Please check your video input in `multi_modal_data`"
                    )
515
516
517
518
519
520
521
522
523
                new_videos.append((video, metadata))
                metadata_lst.append(metadata)
            else:
                new_videos.append(video)

        if not self.video_needs_metadata:
            metadata = None

        return VideoProcessorItems(new_videos, metadata=metadata_lst)
524
525
526
527
528
529
530
531

    def _get_subparsers(self) -> Mapping[str, ModalityDataParser]:
        return {
            "audio": self._parse_audio_data,
            "image": self._parse_image_data,
            "video": self._parse_video_data,
        }

532
    def parse_mm_data(self, mm_data: MultiModalDataDict) -> MultiModalDataItems:
533
534
535
536
537
538
539
        subparsers = self._get_subparsers()

        mm_items = MultiModalDataItems()
        for k, v in mm_data.items():
            if k not in subparsers:
                raise ValueError(f"Unsupported modality: {k}")

540
541
542
            # ignore empty embedding data
            if (parsed_data := subparsers[k](v)) is not None:
                mm_items[k] = parsed_data
543
544

        return mm_items