"tests/kernels/attention/test_blocksparse_attention.py" did not exist on "6e650f56a16618db87147d97f699fa407ed1205d"
utils.py 15.7 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
import asyncio
import atexit
6
from collections.abc import Iterable
7
from concurrent.futures import ThreadPoolExecutor
8
from itertools import groupby
9
from pathlib import Path
10
from typing import TYPE_CHECKING, Any, TypeVar
11
from urllib.parse import ParseResult, urlparse
12
from urllib.request import url2pathname
13

14
import numpy as np
15
import numpy.typing as npt
16
import torch
17
from PIL import Image, UnidentifiedImageError
18

19
import vllm.envs as envs
20
from vllm.connections import HTTPConnection, global_http_connection
21
from vllm.logger import init_logger
22
from vllm.utils.jsontree import json_map_leaves
23

24
25
from .audio import AudioMediaIO
from .base import MediaIO
26
from .image import ImageEmbeddingMediaIO, ImageMediaIO
27
from .video import VideoMediaIO
28

29
if TYPE_CHECKING:
30
31
32
33
34
    from .inputs import (
        BatchedTensorInputs,
        MultiModalKwargsItem,
        MultiModalPlaceholderDict,
    )
35
else:
36
37
    BatchedTensorInputs = Any
    MultiModalKwargsItem = Any
38
    MultiModalPlaceholderDict = Any
39

40
41
logger = init_logger(__name__)

42
global_thread_pool = ThreadPoolExecutor(
43
44
    max_workers=envs.VLLM_MEDIA_LOADING_THREAD_COUNT
)
45
46
atexit.register(global_thread_pool.shutdown)

47
48
_M = TypeVar("_M")

49

50
51
52
class MediaConnector:
    def __init__(
        self,
53
        media_io_kwargs: dict[str, dict[str, Any]] | None = None,
54
55
56
        connection: HTTPConnection = global_http_connection,
        *,
        allowed_local_media_path: str = "",
57
        allowed_media_domains: list[str] | None = None,
58
    ) -> None:
59
60
        """
        Args:
61
62
63
            media_io_kwargs: Additional args passed to process media
                             inputs, keyed by modalities. For example,
                             to set num_frames for video, set
64
                             `--media-io-kwargs '{"video":{"num_frames":40}}'`
65
            connection: HTTP connection client to download media contents.
66
67
            allowed_local_media_path: A local directory to load media files
                                      from.
68
        """
69
70
        super().__init__()

71
72
73
        self.media_io_kwargs: dict[str, dict[str, Any]] = (
            media_io_kwargs if media_io_kwargs else {}
        )
74
75
76
77
78
79
80
81
        self.connection = connection

        if allowed_local_media_path:
            allowed_local_media_path_ = Path(allowed_local_media_path)

            if not allowed_local_media_path_.exists():
                raise ValueError(
                    "Invalid `--allowed-local-media-path`: The path "
82
83
                    f"{allowed_local_media_path_} does not exist."
                )
84
85
86
            if not allowed_local_media_path_.is_dir():
                raise ValueError(
                    "Invalid `--allowed-local-media-path`: The path "
87
88
                    f"{allowed_local_media_path_} must be a directory."
                )
89
90
91
92
        else:
            allowed_local_media_path_ = None

        self.allowed_local_media_path = allowed_local_media_path_
93
94
95
        if allowed_media_domains is None:
            allowed_media_domains = []
        self.allowed_media_domains = allowed_media_domains
96
97
98
99
100

    def _load_data_url(
        self,
        url_spec: ParseResult,
        media_io: MediaIO[_M],
101
    ) -> _M:  # type: ignore[type-var]
102
103
104
105
106
107
108
109
110
111
112
113
114
        data_spec, data = url_spec.path.split(",", 1)
        media_type, data_type = data_spec.split(";", 1)

        if data_type != "base64":
            msg = "Only base64 data URLs are supported for now."
            raise NotImplementedError(msg)

        return media_io.load_base64(media_type, data)

    def _load_file_url(
        self,
        url_spec: ParseResult,
        media_io: MediaIO[_M],
115
    ) -> _M:  # type: ignore[type-var]
116
117
        allowed_local_media_path = self.allowed_local_media_path
        if allowed_local_media_path is None:
118
119
120
            raise RuntimeError(
                "Cannot load local files without `--allowed-local-media-path`."
            )
121

122
        filepath = Path(url2pathname(url_spec.path))
123
        if allowed_local_media_path not in filepath.resolve().parents:
124
            raise ValueError(
125
                f"The file path {filepath} must be a subpath "
126
127
                f"of `--allowed-local-media-path` {allowed_local_media_path}."
            )
128

129
        return media_io.load_file(filepath)
130

131
    def _assert_url_in_allowed_media_domains(self, url_spec) -> None:
132
133
134
135
        if (
            self.allowed_media_domains
            and url_spec.hostname not in self.allowed_media_domains
        ):
136
137
138
            raise ValueError(
                f"The URL must be from one of the allowed domains: "
                f"{self.allowed_media_domains}. Input URL domain: "
139
140
                f"{url_spec.hostname}"
            )
141

142
143
144
145
146
    def load_from_url(
        self,
        url: str,
        media_io: MediaIO[_M],
        *,
147
        fetch_timeout: int | None = None,
148
    ) -> _M:  # type: ignore[type-var]
149
        url_spec = urlparse(url)
150

151
        if url_spec.scheme.startswith("http"):
152
153
            self._assert_url_in_allowed_media_domains(url_spec)

154
            connection = self.connection
155
156
157
158
159
            data = connection.get_bytes(
                url,
                timeout=fetch_timeout,
                allow_redirects=envs.VLLM_MEDIA_URL_ALLOW_REDIRECTS,
            )
160

161
            return media_io.load_bytes(data)
162

163
164
        if url_spec.scheme == "data":
            return self._load_data_url(url_spec, media_io)
165

166
167
        if url_spec.scheme == "file":
            return self._load_file_url(url_spec, media_io)
168

169
170
        msg = "The URL must be either a HTTP, data or file URL."
        raise ValueError(msg)
171

172
173
174
175
176
    async def load_from_url_async(
        self,
        url: str,
        media_io: MediaIO[_M],
        *,
177
        fetch_timeout: int | None = None,
178
179
    ) -> _M:
        url_spec = urlparse(url)
180
        loop = asyncio.get_running_loop()
181

182
        if url_spec.scheme.startswith("http"):
183
184
            self._assert_url_in_allowed_media_domains(url_spec)

185
            connection = self.connection
186
187
188
189
190
            data = await connection.async_get_bytes(
                url,
                timeout=fetch_timeout,
                allow_redirects=envs.VLLM_MEDIA_URL_ALLOW_REDIRECTS,
            )
191
            future = loop.run_in_executor(global_thread_pool, media_io.load_bytes, data)
192
            return await future
193

194
        if url_spec.scheme == "data":
195
196
197
            future = loop.run_in_executor(
                global_thread_pool, self._load_data_url, url_spec, media_io
            )
198
            return await future
199

200
        if url_spec.scheme == "file":
201
202
203
            future = loop.run_in_executor(
                global_thread_pool, self._load_file_url, url_spec, media_io
            )
204
            return await future
205
206
        msg = "The URL must be either a HTTP, data or file URL."
        raise ValueError(msg)
207

208
209
210
    def fetch_audio(
        self,
        audio_url: str,
211
    ) -> tuple[np.ndarray, int | float]:
212
213
214
        """
        Load audio from a URL.
        """
215
        audio_io = AudioMediaIO(**self.media_io_kwargs.get("audio", {}))
216

217
        return self.load_from_url(
218
            audio_url,
219
220
            audio_io,
            fetch_timeout=envs.VLLM_AUDIO_FETCH_TIMEOUT,
221
        )
222

223
224
225
    async def fetch_audio_async(
        self,
        audio_url: str,
226
    ) -> tuple[np.ndarray, int | float]:
227
228
229
        """
        Asynchronously fetch audio from a URL.
        """
230
        audio_io = AudioMediaIO(**self.media_io_kwargs.get("audio", {}))
231

232
        return await self.load_from_url_async(
233
            audio_url,
234
235
            audio_io,
            fetch_timeout=envs.VLLM_AUDIO_FETCH_TIMEOUT,
236
        )
237

238
239
240
241
242
243
244
    def fetch_image(
        self,
        image_url: str,
        *,
        image_mode: str = "RGB",
    ) -> Image.Image:
        """
245
        Load a PIL image from an HTTP or base64 data URL.
246

247
248
        By default, the image is converted into RGB format.
        """
249
250
251
        image_io = ImageMediaIO(
            image_mode=image_mode, **self.media_io_kwargs.get("image", {})
        )
252

253
254
255
256
257
258
259
260
261
        try:
            return self.load_from_url(
                image_url,
                image_io,
                fetch_timeout=envs.VLLM_IMAGE_FETCH_TIMEOUT,
            )
        except UnidentifiedImageError as e:
            # convert to ValueError to be properly caught upstream
            raise ValueError(str(e)) from e
262

263
264
    async def fetch_image_async(
        self,
265
266
        image_url: str,
        *,
267
268
269
        image_mode: str = "RGB",
    ) -> Image.Image:
        """
270
        Asynchronously load a PIL image from an HTTP or base64 data URL.
271

272
273
        By default, the image is converted into RGB format.
        """
274
275
276
        image_io = ImageMediaIO(
            image_mode=image_mode, **self.media_io_kwargs.get("image", {})
        )
277

278
279
280
281
282
283
284
285
286
        try:
            return await self.load_from_url_async(
                image_url,
                image_io,
                fetch_timeout=envs.VLLM_IMAGE_FETCH_TIMEOUT,
            )
        except UnidentifiedImageError as e:
            # convert to ValueError to be properly caught upstream
            raise ValueError(str(e)) from e
287

288
289
290
291
292
    def fetch_video(
        self,
        video_url: str,
        *,
        image_mode: str = "RGB",
293
    ) -> tuple[npt.NDArray, dict[str, Any]]:
294
        """
295
        Load video from an HTTP or base64 data URL.
296
        """
297
298
299
300
        image_io = ImageMediaIO(
            image_mode=image_mode, **self.media_io_kwargs.get("image", {})
        )
        video_io = VideoMediaIO(image_io, **self.media_io_kwargs.get("video", {}))
301
302
303
304
305
306

        return self.load_from_url(
            video_url,
            video_io,
            fetch_timeout=envs.VLLM_VIDEO_FETCH_TIMEOUT,
        )
307

308
309
310
    async def fetch_video_async(
        self,
        video_url: str,
311
        *,
312
        image_mode: str = "RGB",
313
    ) -> tuple[npt.NDArray, dict[str, Any]]:
314
        """
315
        Asynchronously load video from an HTTP or base64 data URL.
316
317
318

        By default, the image is converted into RGB format.
        """
319
320
321
322
        image_io = ImageMediaIO(
            image_mode=image_mode, **self.media_io_kwargs.get("image", {})
        )
        video_io = VideoMediaIO(image_io, **self.media_io_kwargs.get("video", {}))
323
324
325
326
327
328

        return await self.load_from_url_async(
            video_url,
            video_io,
            fetch_timeout=envs.VLLM_VIDEO_FETCH_TIMEOUT,
        )
329

330
331
332
333
334
335
336
337
338
339
340
    def fetch_image_embedding(
        self,
        data: str,
    ) -> torch.Tensor:
        """
        Load image embedding from a URL.
        """
        image_embedding_io = ImageEmbeddingMediaIO()

        return image_embedding_io.load_base64("", data)

341

342
343
def encode_audio_base64(
    audio: np.ndarray,
344
    sampling_rate: int,
345
346
) -> str:
    """Encode audio as base64."""
347
348
    audio_io = AudioMediaIO()
    return audio_io.encode_base64((audio, sampling_rate))
349
350


351
352
353
354
355
356
357
358
def encode_image_base64(
    image: Image.Image,
    *,
    image_mode: str = "RGB",
    format: str = "JPEG",
) -> str:
    """
    Encode a pillow image to base64 format.
359

360
361
    By default, the image is converted into RGB format before being encoded.
    """
362
363
    image_io = ImageMediaIO(image_mode=image_mode)
    return image_io.encode_base64(image, image_format=format)
364
365


366
def encode_video_base64(frames: npt.NDArray) -> str:
367
368
369
    image_io = ImageMediaIO()
    video_io = VideoMediaIO(image_io)
    return video_io.encode_base64(frames)
370
371


372
def argsort_mm_positions(
373
374
    mm_positions: MultiModalPlaceholderDict,
) -> list[tuple[str, int]]:
375
376
377
378
    """
    Given a `MultiModalPlaceholderDict`, output a sequence of keys to
    sort the dictionary by `offset` (starting index in the input sequence)
    in ascending order.
379
380

    Returns:
381
382
        A list of `(modality, idx)`, which can be used to access an item
        by `mm_positions[modality][idx]`.
383
    """
384
385
386
387
388
    flat_items = (
        (modality, idx, item)
        for modality, items in mm_positions.items()
        for idx, item in enumerate(items)
    )
389

390
    sorted_flat_items = sorted(flat_items, key=lambda x: x[2].offset)
391

392
    return [(modality, idx) for modality, idx, _ in sorted_flat_items]
393
394


395
396
397
398
399
def group_mm_kwargs_by_modality(
    mm_kwargs: list[MultiModalKwargsItem],
    *,
    device: torch.types.Device = None,
    pin_memory: bool = False,
400
    merge_by_field_config: bool | None = None,
401
402
403
404
405
) -> Iterable[tuple[str, int, BatchedTensorInputs]]:
    """Group consecutive `MultiModalKwargsItem`s from `mm_kwargs` with the same
    modality together into the same `MultiModalKwargs` instance.

    Args:
406
407
408
        mm_kwargs: List of `MultiModalKwargsItem`.
        device: The device to place the grouped tensors on.
        pin_memory: Whether to pin memory for faster host-to-device transfer.
409
410
411
412

    Yields:
        A tuple `(modality, num_items, grouped_kwargs)`.
    """
413
414
415
416
    if merge_by_field_config is None:
        raise RuntimeError(
            "`group_mm_kwargs_by_modality` now requires "
            "`merge_by_field_config` arg, please update your model runner "
417
418
            "according to https://github.com/vllm-project/vllm/pull/25676."
        )
419
420
421
422
423
424
425
426
427
    if merge_by_field_config is False:
        logger.warning_once(
            "The legacy code for batching multi-modal kwargs is deprecated and "
            "will be removed in v0.12. Please update your model with "
            "`merge_by_field_config=True` to use the new code defined by "
            "`MultiModalFieldConfig`. You can refer to "
            "https://github.com/vllm-project/vllm/issues/26149 "
            "for some examples on how to do this."
        )
428

429
    from vllm.multimodal.inputs import MultiModalKwargs, MultiModalKwargsItems
430
431
432
433

    for modality, items in groupby(mm_kwargs, key=lambda item: item.modality):
        items_lst = list(items)

434
435
436
        if merge_by_field_config:
            mm_kwargs_group: BatchedTensorInputs = dict(
                MultiModalKwargsItems.from_seq(items_lst).get_data(
437
438
439
                    pin_memory=pin_memory
                )
            )
440
441
442

            if device is not None:
                mm_kwargs_group = json_map_leaves(
443
                    lambda x: x.to(device=device) if isinstance(x, torch.Tensor) else x,
444
445
446
447
448
449
450
451
452
453
454
455
456
                    mm_kwargs_group,
                )
        else:
            mm_kwargs_group = MultiModalKwargs.as_kwargs(
                MultiModalKwargs.batch(
                    [
                        MultiModalKwargsItems.from_seq([item]).get_data()
                        for item in items_lst
                    ],
                    pin_memory=pin_memory,
                ),
                device=device,
            )
457
458
459
460

        yield modality, len(items_lst), mm_kwargs_group


461
462
def fetch_audio(
    audio_url: str,
463
464
    audio_io_kwargs: dict[str, Any] | None = None,
) -> tuple[np.ndarray, int | float]:
465
466
467
468
469
    """
    Args:
        audio_url: URL of the audio file to fetch.
        audio_io_kwargs: Additional kwargs passed to handle audio IO.
    """
470
    media_io_kwargs = None if not audio_io_kwargs else {"audio": audio_io_kwargs}
471
472
473
474
475
476
    media_connector = MediaConnector(media_io_kwargs=media_io_kwargs)
    return media_connector.fetch_audio(audio_url)


def fetch_image(
    image_url: str,
477
    image_io_kwargs: dict[str, Any] | None = None,
478
479
480
481
482
483
) -> Image.Image:
    """
    Args:
        image_url: URL of the image file to fetch.
        image_io_kwargs: Additional kwargs passed to handle image IO.
    """
484
    media_io_kwargs = None if not image_io_kwargs else {"image": image_io_kwargs}
485
486
487
488
489
490
    media_connector = MediaConnector(media_io_kwargs=media_io_kwargs)
    return media_connector.fetch_image(image_url)


def fetch_video(
    video_url: str,
491
    video_io_kwargs: dict[str, Any] | None = None,
492
493
494
495
496
497
) -> tuple[npt.NDArray, dict[str, Any]]:
    """
    Args:
        video_url: URL of the video file to fetch.
        video_io_kwargs: Additional kwargs passed to handle video IO.
    """
498
    media_io_kwargs = None if not video_io_kwargs else {"video": video_io_kwargs}
499
    media_connector = MediaConnector(media_io_kwargs=media_io_kwargs)
500
    return media_connector.fetch_video(video_url)