"vllm/vscode:/vscode.git/clone" did not exist on "3a45ab97bf2ae6f755b428b0298f5b98279d4378"
image.py 3.05 KB
Newer Older
1
from functools import lru_cache
2
from typing import TYPE_CHECKING, Any, Dict, Optional
3
4
5

import torch
from PIL import Image
6
from transformers.image_processing_base import BatchFeature
7

8
from vllm.inputs.registry import InputContext
9
from vllm.logger import init_logger
10
from vllm.transformers_utils.processor import get_image_processor
11
from vllm.utils import is_list_of
12

13
from .base import MultiModalData, MultiModalInputs, MultiModalPlugin
14

15
16
17
if TYPE_CHECKING:
    from vllm.config import ModelConfig

18
19
logger = init_logger(__name__)

20
cached_get_image_processor = lru_cache(get_image_processor)
21
22


23
class ImagePlugin(MultiModalPlugin):
24
    """Plugin for image data."""
25

26
27
    def get_data_key(self) -> str:
        return "image"
28

29
30
    def _get_hf_image_processor(
        self,
31
        model_config: "ModelConfig",
32
33
34
35
        mm_processor_kwargs: Optional[Dict[str, Any]] = None,
    ):
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}
36
        return cached_get_image_processor(
37
            model_config.model,
38
39
            trust_remote_code=model_config.trust_remote_code,
            **mm_processor_kwargs)
40

41
42
43
44
    def _default_input_mapper(
        self,
        ctx: InputContext,
        data: MultiModalData[object],
45
        **mm_processor_kwargs,
46
    ) -> MultiModalInputs:
47
        model_config = ctx.model_config
48

49
50
51
52
        # Processed by input processor
        if isinstance(data, BatchFeature):
            return MultiModalInputs(data.data)

53
        # PIL image
54
        if isinstance(data, Image.Image) or is_list_of(data, Image.Image):
55
56
57
58
            image_processor = self._get_hf_image_processor(
                model_config,
                mm_processor_kwargs,
            )
59

60
            if image_processor is None:
61
                raise RuntimeError("No HuggingFace processor is available "
62
63
                                   "to process the image object")
            try:
64
65
66
67
68
                # NOTE: It may make sense to forward the mm_processor_kwargs
                # here too. For now, to keep it simple, we only allow it be
                # used for the initialization call though, just in case the
                # signatures of the preprocessor initializer don't match
                # preprocess()
69
70
71
                batch_data = image_processor \
                    .preprocess(data, return_tensors="pt") \
                    .data
72
            except Exception:
73
74
75
76
77
78
                logger.error(
                    "Failed to process image (%s) with the default mapper. "
                    "This is most likely an edge-case with this model's image "
                    "processor in transformers (type: %s), and not vLLM.",
                    data,
                    type(image_processor).__name__)
79
80
                raise

81
            return MultiModalInputs(batch_data)
82
83

        # Image embedding
84
        elif isinstance(data, torch.Tensor) or is_list_of(data, torch.Tensor):
85
            return MultiModalInputs({"image_embeds": data})
86
87

        raise TypeError(f"Invalid image type: {type(data)}")
88
89
90

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