registry.py 6.41 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
from collections.abc import Mapping
4
from dataclasses import dataclass
5
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, Union
6

7
from transformers import BatchFeature, PretrainedConfig, ProcessorMixin
8
from typing_extensions import TypeVar
9

10
from vllm.transformers_utils.processor import cached_processor_from_config
11
from vllm.transformers_utils.tokenizer import AnyTokenizer
12
from vllm.utils import resolve_mm_processor_kwargs
13
14

if TYPE_CHECKING:
15
    from vllm.config import ModelConfig
16
17
    from vllm.multimodal import (MultiModalDataDict, MultiModalPlaceholderDict,
                                 MultiModalRegistry)
18
19
    from vllm.sequence import SequenceData

20
21
22
_T = TypeVar("_T")
_C = TypeVar("_C", bound=PretrainedConfig, default=PretrainedConfig)
_P = TypeVar("_P", bound=ProcessorMixin, default=ProcessorMixin)
23
24


25
26
27
28
29
30
31
32
33
34
@dataclass(frozen=True)
class InputContext:
    """
    Contains information about the model which may be used to
    modify the inputs.
    """

    model_config: "ModelConfig"
    """The configuration of the model."""

35
36
    def get_hf_config(
        self,
37
        typ: Union[type[_C], tuple[type[_C], ...]] = PretrainedConfig,
38
        /,
39
    ) -> _C:
40
41
        """
        Get the HuggingFace configuration
42
        (`transformers.PretrainedConfig`) of the model,
43
44
45
        additionally checking its type.

        Raises:
46
            TypeError: If the configuration is not of the specified type.
47
48
        """
        hf_config = self.model_config.hf_config
49
        if not isinstance(hf_config, typ):
50
            raise TypeError("Invalid type of HuggingFace config. "
51
                            f"Expected type: {typ}, but "
52
53
54
55
                            f"found type: {type(hf_config)}")

        return hf_config

56
    def get_hf_image_processor_config(self) -> dict[str, Any]:
57
58
59
60
61
        """
        Get the HuggingFace image processor configuration of the model.
        """
        return self.model_config.hf_image_processor_config

62
63
64
65
66
67
68
69
70
71
72
73
74
    def get_mm_config(self):
        """
        Get the multimodal config of the model.

        Raises:
            RuntimeError: If the model is not a multimodal model.
        """
        mm_config = self.model_config.multimodal_config
        if mm_config is None:
            raise RuntimeError("Not a multimodal model")

        return mm_config

75
76
    def get_hf_processor(
        self,
77
        typ: Union[type[_P], tuple[type[_P], ...]] = ProcessorMixin,
78
79
        /,
        **kwargs: object,
80
    ) -> _P:
81
82
        """
        Get the HuggingFace processor
83
        (`transformers.ProcessorMixin`) of the model,
84
85
86
87
88
        additionally checking its type.

        Raises:
            TypeError: If the processor is not of the specified type.
        """
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
        return cached_processor_from_config(
            self.model_config,
            processor_cls=typ,
            **kwargs,
        )

    def init_processor(
        self,
        typ: type[_T],
        /,
        **kwargs: object,
    ) -> _T:
        """
        Initialize a HuggingFace-like processor class, merging the
        keyword arguments with those in the model's configuration.
        """
105
106
        mm_config = self.model_config.get_multimodal_config()
        base_kwargs = mm_config.mm_processor_kwargs
107
108
109
110
111
        if base_kwargs is None:
            base_kwargs = {}

        merged_kwargs = {**base_kwargs, **kwargs}

112
        return typ(**merged_kwargs)
113

114

115
116
117
118
119
@dataclass(frozen=True)
class InputProcessingContext(InputContext):
    tokenizer: AnyTokenizer
    """The tokenizer used to tokenize the inputs."""

120
121
    def get_hf_processor(
        self,
122
        typ: Union[type[_P], tuple[type[_P], ...]] = ProcessorMixin,
123
124
        /,
        **kwargs: object,
125
    ) -> _P:
126
127
128
129
        return super().get_hf_processor(
            typ,
            tokenizer=self.tokenizer,
            **kwargs,
130
131
        )

132
    def call_hf_processor(
133
134
        self,
        hf_processor: ProcessorMixin,
135
136
        data: Mapping[str, object],
        kwargs: Mapping[str, object] = {},
137
    ) -> BatchFeature:
138
        """
139
140
        Call `hf_processor` on the prompt `data`
        (text, image, audio...) with configurable options `kwargs`.
141
        """
142
143
        assert callable(hf_processor)

144
145
        mm_config = self.model_config.get_multimodal_config()
        base_kwargs = mm_config.mm_processor_kwargs
146
147
148
        if base_kwargs is None:
            base_kwargs = {}

149
        merged_kwargs = resolve_mm_processor_kwargs(
150
            base_kwargs,
151
            kwargs,
152
            hf_processor,
153
154
            requires_kw_only=False,
            allow_var_kwargs=True,
155
        )
156

157
        try:
158
            return hf_processor(**data, **merged_kwargs, return_tensors="pt")
159
160
161
162
        except Exception as exc:
            msg = (f"Failed to apply {type(hf_processor).__name__} "
                   f"on data={data} with kwargs={merged_kwargs}")

163
            raise ValueError(msg) from exc
164

165

166
class DummyData(NamedTuple):
167
168
169
170
171
    """
    Dummy data used for profiling.

    Note: This is only used in V0.
    """
172
173
174
175
176
177

    seq_data: "SequenceData"
    multi_modal_data: Optional["MultiModalDataDict"] = None
    multi_modal_placeholders: Optional["MultiModalPlaceholderDict"] = None


178
179
class InputRegistry:
    """
180
    Note: This is only used in V0.
181
182
    """

183
184
185
186
187
    def dummy_data_for_profiling(
        self,
        model_config: "ModelConfig",
        seq_len: int,
        mm_registry: "MultiModalRegistry",
188
        is_encoder_data: bool = False,
189
    ) -> DummyData:
190
191
192
193
194
195
        """
        Create dummy data for profiling the memory usage of a model.

        The model is identified by ``model_config``.
        """
        # Avoid circular import
196
        from vllm.sequence import SequenceData
197

198
199
200
        if not model_config.is_multimodal_model:
            seq_data = SequenceData.from_prompt_token_counts((0, seq_len))
            return DummyData(seq_data=seq_data)
201

202
203
204
205
206
207
        # Encoder dummy data does not contain multi-modal data
        if is_encoder_data:
            enc_data = mm_registry.get_encoder_dummy_data(
                model_config, seq_len)
            seq_data = SequenceData.from_seqs(enc_data.prompt_token_ids)
            return DummyData(seq_data=seq_data)
208

209
        dec_data = mm_registry.get_decoder_dummy_data(model_config, seq_len)
210

211
212
213
214
        return DummyData(
            seq_data=SequenceData.from_seqs(dec_data.prompt_token_ids),
            multi_modal_data=dec_data.multi_modal_data,
            multi_modal_placeholders=dec_data.multi_modal_placeholders,
215
        )