registry.py 10.9 KB
Newer Older
1
import functools
2
from collections import UserDict
3
from dataclasses import dataclass
4
5
from typing import (TYPE_CHECKING, Any, Callable, Dict, Mapping, Optional,
                    Protocol, Tuple, Type)
6
7
8

from torch import nn
from transformers import PretrainedConfig
9
from typing_extensions import TypeVar
10
11

from vllm.logger import init_logger
12
13
from vllm.utils import (get_allowed_kwarg_only_overrides, print_warning_once,
                        resolve_mm_processor_kwargs)
14

15
from .data import DecoderOnlyInputs
16
17

if TYPE_CHECKING:
18
    from vllm.config import ModelConfig
19
    from vllm.multimodal import MultiModalDataDict, MultiModalRegistry
20
21
22
23
    from vllm.sequence import SequenceData

logger = init_logger(__name__)

24
C = TypeVar("C", bound=PretrainedConfig, default=PretrainedConfig)
25
26
27
28
29
30
31
32
33
34
35
36


@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."""

37
    def get_hf_config(self, hf_config_type: Type[C] = PretrainedConfig) -> C:
38
39
40
41
42
43
        """
        Get the HuggingFace configuration
        (:class:`transformers.PretrainedConfig`) of the model,
        additionally checking its type.

        Raises:
44
            TypeError: If the model is not of the specified type.
45
46
47
48
49
50
51
52
53
54
        """

        hf_config = self.model_config.hf_config
        if not isinstance(hf_config, hf_config_type):
            raise TypeError("Invalid type of HuggingFace config. "
                            f"Expected type: {hf_config_type}, but "
                            f"found type: {type(hf_config)}")

        return hf_config

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

        return self.model_config.hf_image_processor_config

62
63
64
65

N = TypeVar("N", bound=Type[nn.Module])


66
67
68
69
70
71
72
class DummyDataFactory(Protocol):

    def __call__(
        self,
        ctx: InputContext,
        seq_len: int,
        mm_counts: Mapping[str, int],
73
        **mm_processor_kwargs: Any,
74
75
76
77
78
79
    ) -> Tuple["SequenceData", Optional["MultiModalDataDict"]]:
        """
        Create dummy data to be inputted into the model.

        Note:
            :data:`InputProcessor` is not applied to the dummy data.
80
81
82
83

            The :code:`mm_processor_kwargs` are overrides provided at
            initialization time to values in the config whose values
            may affect the number of tokens per instance.
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
        """
        ...


class _MultiModalCounts(UserDict):
    """
    Wraps `mm_counts` for a more informative error message
    when attempting to access a plugin that does not exist.
    """

    def __getitem__(self, key: str) -> int:
        try:
            return super().__getitem__(key)
        except KeyError as exc:
            msg = (f"There is no multi-modal plugin with the key: {key}. "
                   f"Available keys: {set(self.keys())}")
            raise KeyError(msg) from exc

102

103
InputProcessor = Callable[[InputContext, DecoderOnlyInputs], DecoderOnlyInputs]
104
105
106
107
108
109
110
111
112
113
114
115
"""Preprocess the inputs to the model."""


class InputRegistry:
    """
    A registry to dispatch data processing
    according to the target model.
    """

    def __init__(self) -> None:
        self._dummy_factories_by_model_type: Dict[Type[nn.Module],
                                                  DummyDataFactory] = {}
116
117
        self._dummy_encoder_factories_by_model_type: Dict[
            Type[nn.Module], DummyDataFactory] = {}
118
119
120
121
122
123
124
        self._input_processors_by_model_type: Dict[Type[nn.Module],
                                                   InputProcessor] = {}

    def _default_dummy_data_factory(
        self,
        ctx: InputContext,
        seq_len: int,
125
        mm_counts: Mapping[str, int],
126
    ) -> Tuple["SequenceData", Optional["MultiModalDataDict"]]:
127
128
129
130
131
132
133
134
135
136
        """
        The default dummy data factory represents the longest possible text
        that can be inputted to the model.

        Note:
            :data:`InputProcessor` is not applied to the dummy data.
        """
        # Avoid circular import
        from vllm.sequence import SequenceData

137
        dummy_seq_data = SequenceData.from_prompt_token_counts((0, seq_len))
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
        dummy_multi_modal_data = None

        return dummy_seq_data, dummy_multi_modal_data

    def register_dummy_data(self, factory: DummyDataFactory):
        """
        Register a dummy data factory to a model class.

        During memory profiling, the provided function is invoked to create
        dummy data to be inputted into the model. The resulting memory usage
        should be an upper bound of what the model would use at inference time.
        """

        def wrapper(model_cls: N) -> N:
            if model_cls in self._dummy_factories_by_model_type:
                logger.warning(
                    "Model class %s already has dummy data "
                    "registered to %s. It is overwritten by the new one.",
                    model_cls, self)

            self._dummy_factories_by_model_type[model_cls] = factory

            return model_cls

        return wrapper

164
165
166
167
    def _get_dummy_data_factory(self, model_cls: Type[nn.Module]):
        return self._dummy_factories_by_model_type \
            .get(model_cls, self._default_dummy_data_factory)

168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    def register_dummy_encoder_data(self, factory: DummyDataFactory):
        """
        Register a dummy encoder data factory to a model class

        This is similar to :meth:`~register_dummy_data`, but for encoder input.
        """

        def wrapper(model_cls: N) -> N:
            if model_cls in self._dummy_encoder_factories_by_model_type:
                logger.warning(
                    "Model class %s already has dummy encoder data "
                    "registered to %s. It is overwritten by the new one.",
                    model_cls, self)

            self._dummy_encoder_factories_by_model_type[model_cls] = factory

            return model_cls

        return wrapper

    def _get_dummy_encoder_data_factory(self, model_cls: Type[nn.Module]):
189
190
        return self._dummy_encoder_factories_by_model_type \
            .get(model_cls, self._default_dummy_data_factory)
191

192
193
194
195
196
    def dummy_data_for_profiling(
        self,
        model_config: "ModelConfig",
        seq_len: int,
        mm_registry: "MultiModalRegistry",
197
        is_encoder_data: bool = False,
198
    ) -> Tuple["SequenceData", Optional["MultiModalDataDict"]]:
199
200
201
202
203
        """
        Create dummy data for profiling the memory usage of a model.

        The model is identified by ``model_config``.

204
        See also:
205
            :ref:`enabling_multimodal_inputs`
206
207
208
209

        Note:
            This should be called after
            :meth:`~MultiModalRegistry.init_mm_limits_per_prompt`.
210
211
212
213
214
        """
        # Avoid circular import
        from vllm.model_executor.model_loader import get_model_architecture

        model_cls, _ = get_model_architecture(model_config)
215
216
217
218
        if is_encoder_data:
            dummy_factory = self._get_dummy_encoder_data_factory(model_cls)
        else:
            dummy_factory = self._get_dummy_data_factory(model_cls)
219
        mm_counts = mm_registry.get_mm_limits_per_prompt(model_config)
220
221
        mm_processor_kwargs = get_allowed_kwarg_only_overrides(
            dummy_factory, overrides=model_config.mm_processor_kwargs)
222

223
224
225
        seq_data, mm_data = dummy_factory(InputContext(model_config), seq_len,
                                          _MultiModalCounts(mm_counts),
                                          **mm_processor_kwargs)
226
227
228

        # Having more tokens is over-conservative but otherwise fine
        num_tokens = seq_data.prompt_token_ids
229
230
        if len(num_tokens) < seq_len:
            if is_encoder_data:
231
232
233
                print_warning_once(
                    f"Expected at least {seq_len} dummy encoder tokens for "
                    f"profiling, but found {len(num_tokens)} tokens instead.")
234
235
236
237
            else:
                raise AssertionError(
                    f"Expected at least {seq_len} dummy tokens for profiling, "
                    f"but found {len(num_tokens)} tokens instead.")
238
239
240
241
242
243
244
245
246
        if mm_data is not None:
            for k, v in mm_data.items():
                num_items = len(v) if isinstance(v, list) else 1
                num_expected = mm_counts[k]
                assert num_items >= num_expected, (
                    f"Expected at least {num_expected} dummy '{k}' instances "
                    f"for profiling, but found {num_items} instances instead.")

        return seq_data, mm_data
247

248
249
250
251
252
    def _default_input_processor(
        self,
        ctx: InputContext,
        inputs: DecoderOnlyInputs,
    ) -> DecoderOnlyInputs:
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        """The default input processor is a no-op."""
        return inputs

    def register_input_processor(self, processor: InputProcessor):
        """
        Register an input processor to a model class.

        The provided function is invoked on each input to the model. This
        happens before :meth:`~vllm.multimodal.MultiModalRegistry.map_input`.

        See also:
            :ref:`input_processing_pipeline`
        """

        def wrapper(model_cls: N) -> N:
            if model_cls in self._input_processors_by_model_type:
                logger.warning(
                    "Model class %s already has input processor "
                    "registered to %s. It is overwritten by the new one.",
                    model_cls, self)

            self._input_processors_by_model_type[model_cls] = processor

            return model_cls

        return wrapper

280
281
282
283
    def _get_model_input_processor(self, model_cls: Type[nn.Module]):
        return self._input_processors_by_model_type \
            .get(model_cls, self._default_input_processor)

284
    def process_input(self, model_config: "ModelConfig",
285
                      inputs: DecoderOnlyInputs) -> DecoderOnlyInputs:
286
287
288
289
290
291
292
293
294
295
296
297
        """
        Apply an input processor to an instance of model inputs.

        The model is identified by ``model_config``.

        See also:
            :ref:`input_processing_pipeline`
        """
        # Avoid circular import
        from vllm.model_executor.model_loader import get_model_architecture

        model_cls, _ = get_model_architecture(model_config)
298
        processor = self._get_model_input_processor(model_cls)
299

300
301
302
303
304
305
306
307
        # Handle multimodal processor kwargs with priority:
        #     Inference kwargs -> Init kwargs -> {}
        # If it's empty, it'll fall back to the default kwarg values
        mm_processor_kwargs = resolve_mm_processor_kwargs(
            model_config.mm_processor_kwargs,
            inputs.get("mm_processor_kwargs"),
            processor,
        )
308

309
310
        return processor(InputContext(model_config), inputs,
                         **mm_processor_kwargs)
311
312
313

    def create_input_processor(self, model_config: "ModelConfig"):
        """
314
        Create an input processor (see :meth:`_process_input`) for a
315
316
317
        specific model.
        """
        return functools.partial(self.process_input, model_config)