registry.py 12 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, Generic, Protocol, TypeVar, cast
6

7
from vllm.config.multimodal import BaseDummyOptions
8
from vllm.logger import init_logger
9
10
from vllm.tokenizers import TokenizerLike
from vllm.transformers_utils.tokenizer import cached_tokenizer_from_config
11

12
from .cache import BaseMultiModalProcessorCache
13
14
15
16
17
18
19
20
21
22
23
from .processing import (
    BaseMultiModalProcessor,
    BaseProcessingInfo,
    InputProcessingContext,
)
from .profiling import (
    BaseDummyInputsBuilder,
    DummyDecoderData,
    DummyEncoderData,
    MultiModalProfiler,
)
24

25
26
if TYPE_CHECKING:
    from vllm.config import ModelConfig
27
    from vllm.model_executor.models.interfaces import SupportsMultiModal
28

29
30
logger = init_logger(__name__)

31
N = TypeVar("N", bound=type["SupportsMultiModal"])
32
33
_I = TypeVar("_I", bound=BaseProcessingInfo)
_I_co = TypeVar("_I_co", bound=BaseProcessingInfo, covariant=True)
34
35


36
class ProcessingInfoFactory(Protocol[_I_co]):
37
38
39
40
41
    """
    Constructs a
    [`BaseMultiModalProcessor`][vllm.multimodal.processing.BaseMultiModalProcessor]
    instance from the context.
    """
42
43
44
45

    def __call__(
        self,
        ctx: InputProcessingContext,
46
    ) -> _I_co: ...
47
48


49
class DummyInputsBuilderFactory(Protocol[_I]):  # type: ignore[misc]
50
    """
51
52
53
    Constructs a
    [`BaseDummyInputsBuilder`][vllm.multimodal.profiling.BaseDummyInputsBuilder]
    instance from the context.
54
55
    """

56
    def __call__(self, info: _I) -> BaseDummyInputsBuilder[_I]: ...
57
58


59
class MultiModalProcessorFactory(Protocol[_I]):  # type: ignore[misc]
60
61
62
63
64
    """
    Constructs a
    [`BaseMultiModalProcessor`][vllm.multimodal.processing.BaseMultiModalProcessor]
    instance from the context.
    """
65
66
67
68
69

    def __call__(
        self,
        info: _I,
        dummy_inputs: BaseDummyInputsBuilder[_I],
70
        *,
71
        cache: BaseMultiModalProcessorCache | None = None,
72
    ) -> BaseMultiModalProcessor[_I]: ...
73

74

75
76
77
78
79
80
81
82
83
84
@dataclass(frozen=True)
class _ProcessorFactories(Generic[_I]):
    info: ProcessingInfoFactory[_I]
    processor: MultiModalProcessorFactory[_I]
    dummy_inputs: DummyInputsBuilderFactory[_I]

    def build_processor(
        self,
        ctx: InputProcessingContext,
        *,
85
        cache: BaseMultiModalProcessorCache | None = None,
86
87
88
89
90
91
    ):
        info = self.info(ctx)
        dummy_inputs_builder = self.dummy_inputs(info)
        return self.processor(info, dummy_inputs_builder, cache=cache)


92
93
class MultiModalRegistry:
    """
94
    A registry that dispatches data processing according to the model.
95
96
    """

97
98
99
    def _extract_mm_options(
        self,
        model_config: "ModelConfig",
100
    ) -> Mapping[str, BaseDummyOptions] | None:
101
102
103
104
105
106
107
108
109
110
111
112
        """
        Extract multimodal dummy options from model config.

        Returns None if no configurable options are found, otherwise returns
        a mapping of modality names to their dummy options.
        """
        if not model_config.multimodal_config:
            return None

        mm_options = {
            m: opt
            for m in model_config.multimodal_config.limit_per_prompt
113
            if (opt := model_config.multimodal_config.get_dummy_options(m)) is not None
114
115
116
117
        }

        return mm_options if len(mm_options) > 0 else None

118
119
120
    def supports_multimodal_inputs(self, model_config: "ModelConfig") -> bool:
        """
        Checks if the model supports multimodal inputs.
121
122
        Returns True if the model is multimodal with any non-zero supported
        modalities, otherwise returns False, effectively running in
123
124
125
126
127
        text-only mode.
        """
        if not model_config.is_multimodal_model:
            return False

128
129
        info = self._create_processing_info(model_config, tokenizer=None)
        supported_modalities = info.get_supported_mm_limits()
130
131
132
133
134

        mm_config = model_config.get_multimodal_config()

        # Check if all supported modalities have limit == 0
        if all(
135
136
137
            mm_config.get_limit_per_prompt(modality) == 0
            for modality in supported_modalities
        ):
138
139
            logger.info_once(
                "All limits of multimodal modalities supported by the model "
140
141
                "are set to 0, running in text-only mode."
            )
142
143
144
145
            return False

        return True

146
147
148
    def get_max_tokens_per_item_by_modality(
        self,
        model_config: "ModelConfig",
149
        *,
150
        cache: BaseMultiModalProcessorCache | None = None,
151
        profiler_limits: Mapping[str, int] | None = None,
152
153
    ) -> Mapping[str, int]:
        """
154
        Get the maximum number of tokens per data item from each modality based
155
        on underlying model configuration.
156
        """
157
158
        if not model_config.is_multimodal_model:
            return {}
159

160
        processor = self.create_processor(model_config, cache=cache)
161
        profiler: MultiModalProfiler = MultiModalProfiler(processor)
162
163

        seq_len = model_config.max_model_len
164
165
166
        profiler_limits = (
            profiler.get_mm_limits() if profiler_limits is None else profiler_limits
        )
167

168
        return profiler.get_mm_max_contiguous_tokens(
169
            seq_len,
170
            {modality: 1 for modality, limit in profiler_limits.items() if limit > 0},
171
        )
172

173
174
    def get_mm_limits_per_prompt(
        self,
175
        model_config: "ModelConfig",
176
        *,
177
        cache: BaseMultiModalProcessorCache | None = None,
178
179
180
181
    ) -> Mapping[str, int]:
        """
        Get the maximum number of multi-modal input instances for each modality
        that are allowed per prompt for a model class.
182
        """
183
184
        if not model_config.is_multimodal_model:
            return {}
185

186
        processor = self.create_processor(model_config, cache=cache)
187
        profiler: MultiModalProfiler = MultiModalProfiler(processor)
188
        return profiler.get_mm_limits()
189
190
191

    def register_processor(
        self,
192
193
194
195
        processor: MultiModalProcessorFactory[_I],
        *,
        info: ProcessingInfoFactory[_I],
        dummy_inputs: DummyInputsBuilderFactory[_I],
196
197
    ):
        """
198
199
        Register a multi-modal processor to a model class. The processor
        is constructed lazily, hence a factory method should be passed.
200
201
202
203
204
205

        When the model receives multi-modal data, the provided function is
        invoked to transform the data into a dictionary of model inputs.
        """

        def wrapper(model_cls: N) -> N:
206
            if "_processor_factory" in model_cls.__dict__:
207
                logger.warning(
208
                    "Model class %s already has a multi-modal processor "
209
                    "registered to %s. It is overwritten by the new one.",
210
211
212
                    model_cls,
                    self,
                )
213

214
            model_cls._processor_factory = _ProcessorFactories(
215
216
217
218
                info=info,
                dummy_inputs=dummy_inputs,
                processor=processor,
            )
219
220
221
222
223

            return model_cls

        return wrapper

224
    def _get_model_cls(self, model_config: "ModelConfig") -> "SupportsMultiModal":
225
226
227
228
        # Avoid circular import
        from vllm.model_executor.model_loader import get_model_architecture

        model_cls, _ = get_model_architecture(model_config)
229
230
        assert hasattr(model_cls, "_processor_factory")
        return cast("SupportsMultiModal", model_cls)
231

232
233
234
    def _create_processing_ctx(
        self,
        model_config: "ModelConfig",
235
        tokenizer: TokenizerLike | None = None,
236
    ) -> InputProcessingContext:
237
238
239
        if model_config.skip_tokenizer_init:
            tokenizer = cast(TokenizerLike, object())
        elif tokenizer is None:
240
            tokenizer = cached_tokenizer_from_config(model_config)
241

242
243
244
245
246
247
        return InputProcessingContext(model_config, tokenizer)

    def _create_processing_info(
        self,
        model_config: "ModelConfig",
        *,
248
        tokenizer: TokenizerLike | None = None,
249
250
    ) -> BaseProcessingInfo:
        model_cls = self._get_model_cls(model_config)
251
        factories = model_cls._processor_factory
252
253
254
        ctx = self._create_processing_ctx(model_config, tokenizer)
        return factories.info(ctx)

255
256
257
    def create_processor(
        self,
        model_config: "ModelConfig",
258
        *,
259
        tokenizer: TokenizerLike | None = None,
260
        cache: BaseMultiModalProcessorCache | None = None,
261
    ) -> BaseMultiModalProcessor[BaseProcessingInfo]:
262
263
264
        """
        Create a multi-modal processor for a specific model and tokenizer.
        """
265
266
267
        if not model_config.is_multimodal_model:
            raise ValueError(f"{model_config.model} is not a multimodal model")

268
        model_cls = self._get_model_cls(model_config)
269
        factories = model_cls._processor_factory
270

271
        ctx = self._create_processing_ctx(model_config, tokenizer)
272

273
        return factories.build_processor(ctx, cache=cache)
274
275
276
277
278

    def get_decoder_dummy_data(
        self,
        model_config: "ModelConfig",
        seq_len: int,
279
        mm_counts: Mapping[str, int] | None = None,
280
        *,
281
        cache: BaseMultiModalProcessorCache | None = None,
282
283
284
285
    ) -> DummyDecoderData:
        """
        Create dummy data for profiling the memory usage of a model.

286
        The model is identified by `model_config`.
287
        """
288
        processor = self.create_processor(model_config, cache=cache)
289
290
291
292
293
294
295
        profiler: MultiModalProfiler = MultiModalProfiler(processor)

        # Extract configurable options from multimodal config.
        # Only include modalities that use advanced option types so legacy
        # count-only behavior remains unchanged.
        mm_options = self._extract_mm_options(model_config)

296
        dummy_data = profiler.get_decoder_dummy_data(seq_len, mm_counts, mm_options)
297
298
299
300
301
302

        # Having more tokens is over-conservative but otherwise fine
        token_ids = dummy_data.prompt_token_ids
        if len(token_ids) < seq_len:
            raise AssertionError(
                f"Expected at least {seq_len} dummy tokens for profiling, "
303
304
                f"but found {len(token_ids)} tokens instead."
            )
305
306
307
308
309
310
311

        return dummy_data

    def get_encoder_dummy_data(
        self,
        model_config: "ModelConfig",
        seq_len: int,
312
        mm_counts: Mapping[str, int] | None = None,
313
        *,
314
        cache: BaseMultiModalProcessorCache | None = None,
315
316
317
318
    ) -> DummyEncoderData:
        """
        Create dummy data for profiling the memory usage of a model.

319
        The model is identified by `model_config`.
320
        """
321
        processor = self.create_processor(model_config, cache=cache)
322
323
324
325
326
327
328
        profiler: MultiModalProfiler = MultiModalProfiler(processor)

        # Extract configurable options from multimodal config.
        # Only include modalities that use advanced option types so legacy
        # count-only behavior remains unchanged.
        mm_options = self._extract_mm_options(model_config)

329
        dummy_data = profiler.get_encoder_dummy_data(seq_len, mm_counts, mm_options)
330
331
332
333
334

        # Having more tokens is over-conservative but otherwise fine
        token_ids = dummy_data.prompt_token_ids
        if len(token_ids) < seq_len:
            logger.warning_once(
335
336
337
338
                "Expected at least %d dummy encoder tokens for profiling, but found %d tokens instead.",  # noqa: E501
                seq_len,
                len(token_ids),
            )
339
340

        return dummy_data
341
342
343
344
345
346
347

    def get_encdec_max_encoder_len(self, model_config: "ModelConfig") -> int:
        """
        Get the maximum length of the encoder input for encoder-decoder models.
        """
        if not model_config.is_encoder_decoder:
            return 0
348
        max_tokens = self.get_max_tokens_per_item_by_modality(model_config)
349
350
351
352
353
        if not max_tokens:
            # TODO - this function assumes encoder-decoder models are
            # multimodal. This will need to change when adding support for more
            # than whisper.
            return 0
354
355
        assert len(max_tokens) == 1, (
            "Encoder-decoder models are expected \
356
            to implement the multimodal interface with at most one modality."
357
        )
358
359
360

        first_modality = next(iter(max_tokens))
        return max_tokens[first_modality]