"tests/kernels/attention/test_flash_attn.py" did not exist on "bf33700ecd6db472c4aeb489c5d42aa47a735198"
video.py 3.9 KB
Newer Older
1
from functools import lru_cache
2
from typing import TYPE_CHECKING, Any, Dict, Optional
3
4

import numpy as np
5
import numpy.typing as npt
6
7
8

from vllm.inputs.registry import InputContext
from vllm.logger import init_logger
9
from vllm.transformers_utils.processor import get_video_processor
10
from vllm.transformers_utils.tokenizer import get_tokenizer
11
from vllm.utils import is_list_of
12

13
from .base import MultiModalData
14
from .image import ImagePlugin
15
from .inputs import MultiModalKwargs, VideoItem
16

17
18
19
if TYPE_CHECKING:
    from vllm.config import ModelConfig

20
21
22
23
24
25
26
27
28
29
30
31
logger = init_logger(__name__)

cached_get_video_processor = lru_cache(get_video_processor)
cached_get_tokenizer = lru_cache(get_tokenizer)


class VideoPlugin(ImagePlugin):
    """Plugin for video data."""

    def get_data_key(self) -> str:
        return "video"

32
33
    def _get_hf_video_processor(
        self,
34
        model_config: "ModelConfig",
35
36
37
38
        mm_processor_kwargs: Optional[Dict[str, Any]] = None,
    ):
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}
39
40
        return cached_get_video_processor(
            model_config.model,
41
42
            trust_remote_code=model_config.trust_remote_code,
            **mm_processor_kwargs)
43
44
45
46

    def _default_input_mapper(
        self,
        ctx: InputContext,
47
        data: MultiModalData[VideoItem],
48
        **mm_processor_kwargs,
49
    ) -> MultiModalKwargs:
50
51
        model_config = ctx.model_config

52
        if isinstance(data, list) and len(data) == 1:
53
            data = data[0]  # type: ignore
54

55
        if isinstance(data, np.ndarray) or is_list_of(data, np.ndarray):
56
57
58
59
            video_processor = self._get_hf_video_processor(
                model_config,
                mm_processor_kwargs,
            )
60
61
            if video_processor is None:
                raise RuntimeError("No HuggingFace processor is available "
62
                                   "to process the video object")
63
            try:
64
65
66
67
                # NOTE: Similar to image; it may be a good idea to filter and
                # pass mm_processor_kwargs here too, but for now we don't to
                # avoid extra complexity if the initializer and preprocess
                # signatures of the processor don't align
68
69
                batch_data = video_processor(data, return_tensors="pt").data
            except Exception:
70
                logger.error("Failed to process video (%s)", data)
71
72
                raise

73
            return MultiModalKwargs(batch_data)
74
75
76
77
78

        raise TypeError(f"Invalid video type: {type(data)}")

    def _default_max_multimodal_tokens(self, ctx: InputContext) -> int:
        return 4096
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120


def try_import_video_packages() -> tuple[Any, Any]:
    try:
        import cv2
        import decord
    except ImportError as exc:
        raise ImportError(
            "Please install vllm[video] for video support.") from exc
    return cv2, decord


def resize_video(frames: npt.NDArray, size: tuple[int, int]) -> npt.NDArray:
    cv2, _ = try_import_video_packages()

    num_frames, _, _, channels = frames.shape
    new_height, new_width = size
    resized_frames = np.empty((num_frames, new_height, new_width, channels),
                              dtype=frames.dtype)
    for i, frame in enumerate(frames):
        resized_frame = cv2.resize(frame, (new_width, new_height))
        resized_frames[i] = resized_frame
    return resized_frames


def rescale_video_size(frames: npt.NDArray, size_factor: float) -> npt.NDArray:
    _, height, width, _ = frames.shape
    new_height = int(height * size_factor)
    new_width = int(width * size_factor)

    return resize_video(frames, (new_height, new_width))


def sample_frames_from_video(frames: npt.NDArray,
                             num_frames: int) -> npt.NDArray:
    total_frames = frames.shape[0]
    if num_frames == -1:
        return frames

    frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
    sampled_frames = frames[frame_indices, ...]
    return sampled_frames