image.py 2.22 KB
Newer Older
1
from functools import lru_cache
2
3
4
5

import torch
from PIL import Image

6
7
from vllm.config import ModelConfig
from vllm.inputs.registry import InputContext
8
from vllm.logger import init_logger
9
from vllm.transformers_utils.processor import get_image_processor
10
from vllm.utils import is_list_of
11

12
from .base import MultiModalData, MultiModalInputs, MultiModalPlugin
13
14
15

logger = init_logger(__name__)

16
cached_get_image_processor = lru_cache(get_image_processor)
17
18


19
class ImagePlugin(MultiModalPlugin):
20
    """Plugin for image data."""
21

22
23
    def get_data_key(self) -> str:
        return "image"
24

25
    def _get_hf_image_processor(self, model_config: ModelConfig):
26
27
28
29
        mm_processor_kwargs = ({} if model_config.mm_processor_kwargs is None
                               else model_config.mm_processor_kwargs)
        # We don't explicitly check kwarg overrides to the HF class
        # since the automodel just takes kwargs, so we can't inspect it
30
        return cached_get_image_processor(
31
            model_config.model,
32
33
            trust_remote_code=model_config.trust_remote_code,
            **mm_processor_kwargs)
34

35
36
37
38
39
    def _default_input_mapper(
        self,
        ctx: InputContext,
        data: MultiModalData[object],
    ) -> MultiModalInputs:
40
        model_config = ctx.model_config
41

42
        # PIL image
43
        if isinstance(data, Image.Image) or is_list_of(data, Image.Image):
44
            image_processor = self._get_hf_image_processor(model_config)
45

46
            if image_processor is None:
47
                raise RuntimeError("No HuggingFace processor is available "
48
49
                                   "to process the image object")
            try:
50
51
52
                batch_data = image_processor \
                    .preprocess(data, return_tensors="pt") \
                    .data
53
            except Exception:
54
                logger.error("Failed to process image (%s)", data)
55
56
                raise

57
            return MultiModalInputs(batch_data)
58
59

        # Image embedding
60
        elif isinstance(data, torch.Tensor) or is_list_of(data, torch.Tensor):
61
            return MultiModalInputs({"image_embeds": data})
62
63

        raise TypeError(f"Invalid image type: {type(data)}")
64
65
66

    def _default_max_multimodal_tokens(self, ctx: InputContext) -> int:
        return 3000