image.py 1.47 KB
Newer Older
1
from functools import lru_cache
2
from typing import Dict
3
4
5
6

import torch
from PIL import Image

7
8
from vllm.config import ModelConfig
from vllm.inputs.registry import InputContext
9
from vllm.logger import init_logger
10
from vllm.transformers_utils.image_processor import get_image_processor
11

12
from .base import 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

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

24
    def _get_hf_image_processor(self, model_config: ModelConfig):
25
        return cached_get_image_processor(
26
27
            model_config.model,
            trust_remote_code=model_config.trust_remote_code)
28

29
    def _default_input_mapper(self, ctx: InputContext,
30
                              data: object) -> Dict[str, torch.Tensor]:
31
        model_config = ctx.model_config
32
        if isinstance(data, Image.Image):
33
            image_processor = self._get_hf_image_processor(model_config)
34
35
36
37
            if image_processor is None:
                raise RuntimeError("No HuggingFace processor is available"
                                   "to process the image object")
            try:
38
                return image_processor.preprocess(data, return_tensors="pt") \
39
40
                    .to(model_config.dtype).data
            except Exception:
41
                logger.error("Failed to process image (%s)", data)
42
43
                raise

44
        raise TypeError(f"Invalid type for 'image': {type(data)}")