registry.py 10.4 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 functools import lru_cache
6
from typing import TYPE_CHECKING, Generic, Optional, Protocol, TypeVar
7

8
9
10
import torch.nn as nn

from vllm.inputs import InputProcessingContext
11
from vllm.logger import init_logger
12
13
from vllm.transformers_utils.tokenizer import (AnyTokenizer,
                                               cached_tokenizer_from_config)
14
from vllm.utils import ClassRegistry
15

16
17
from .processing import (BaseMultiModalProcessor, BaseProcessingInfo,
                         ProcessingCache)
18
19
from .profiling import (BaseDummyInputsBuilder, DummyDecoderData,
                        DummyEncoderData, MultiModalProfiler)
20

21
22
23
if TYPE_CHECKING:
    from vllm.config import ModelConfig

24
25
logger = init_logger(__name__)

26
N = TypeVar("N", bound=type[nn.Module])
27
28
_I = TypeVar("_I", bound=BaseProcessingInfo)
_I_co = TypeVar("_I_co", bound=BaseProcessingInfo, covariant=True)
29
30


31
class ProcessingInfoFactory(Protocol[_I_co]):
32
33
34
35
36
    """
    Constructs a
    [`BaseMultiModalProcessor`][vllm.multimodal.processing.BaseMultiModalProcessor]
    instance from the context.
    """
37
38
39
40

    def __call__(
        self,
        ctx: InputProcessingContext,
41
42
43
44
45
46
    ) -> _I_co:
        ...


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

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


class MultiModalProcessorFactory(Protocol[_I]):
57
58
59
60
61
    """
    Constructs a
    [`BaseMultiModalProcessor`][vllm.multimodal.processing.BaseMultiModalProcessor]
    instance from the context.
    """
62
63
64
65
66

    def __call__(
        self,
        info: _I,
        dummy_inputs: BaseDummyInputsBuilder[_I],
67
68
        *,
        cache: Optional[ProcessingCache] = None,
69
    ) -> BaseMultiModalProcessor[_I]:
70
        ...
71

72

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

    def build_processor(
        self,
        ctx: InputProcessingContext,
        *,
        cache: Optional[ProcessingCache] = None,
    ):
        info = self.info(ctx)
        dummy_inputs_builder = self.dummy_inputs(info)
        return self.processor(info, dummy_inputs_builder, cache=cache)


90
91
92
93
94
95
96
# Make sure a different cache is used for each model config
# NOTE: ModelConfig is not hashable so it cannot be passed directly
@lru_cache(maxsize=1)
def _get_processor_cache(model_id: str, capacity_gb: int):
    return ProcessingCache(capacity_gb) if capacity_gb > 0 else None


97
98
class MultiModalRegistry:
    """
99
    A registry that dispatches data processing according to the model.
100
101
    """

102
    def __init__(self) -> None:
103
        self._processor_factories = ClassRegistry[nn.Module,
104
                                                  _ProcessorFactories]()
105

106
    def _get_processor_cache(self, model_config: "ModelConfig"):
107
        model_id = model_config.model
108
        capacity_gb = model_config.mm_processor_cache_gb
109
        return _get_processor_cache(model_id, capacity_gb)
110

111
    def reset_processor_cache(self, model_config: "ModelConfig") -> bool:
112
        """Reset the multi-modal processing cache."""
113
114
        if processor_cache := self._get_processor_cache(model_config):
            processor_cache.reset()
115
116
117

        return True  # Success

118
119
120
121
122
    def get_max_tokens_per_item_by_modality(
        self,
        model_config: "ModelConfig",
    ) -> Mapping[str, int]:
        """
123
        Get the maximum number of tokens per data item from each modality based
124
        on underlying model configuration.
125
        """
126
127
        if not model_config.is_multimodal_model:
            return {}
128

129
        processor = self.create_processor(model_config, disable_cache=False)
130
131
132
133
134
        profiler = MultiModalProfiler(processor)

        seq_len = model_config.max_model_len
        mm_limits = self.get_mm_limits_per_prompt(model_config)

135
        return profiler.get_mm_max_contiguous_tokens(
136
137
138
139
140
141
            seq_len,
            {
                modality: 1
                for modality, limit in mm_limits.items() if limit > 0
            },
        )
142

143
144
145
146
147
148
    def get_max_tokens_per_item_by_nonzero_modality(
        self,
        model_config: "ModelConfig",
    ) -> Mapping[str, int]:
        """
        Get the maximum number of tokens per data item from each modality based
149
        on underlying model configuration, excluding modalities that user
150
151
152
        explicitly disabled via `limit_mm_per_prompt`.

        Note:
153
            This is currently directly used only in V1 for profiling the memory
154
155
            usage of a model.
        """
156
        mm_limits = self.get_mm_limits_per_prompt(model_config)
157
158
159
160
161

        return {
            key: max_tokens_per_mm_item
            for key, max_tokens_per_mm_item in
            self.get_max_tokens_per_item_by_modality(model_config).items()
162
            if mm_limits[key] > 0
163
164
        }

165
166
167
168
    def get_max_tokens_by_modality(
        self,
        model_config: "ModelConfig",
    ) -> Mapping[str, int]:
169
        """
170
        Get the maximum number of tokens from each modality
171
        for profiling the memory usage of a model.
172
        """
173
        mm_limits = self.get_mm_limits_per_prompt(model_config)
174

175
        return {
176
            key: mm_limits[key] * max_tokens_per_mm_item
177
178
            for key, max_tokens_per_mm_item in
            self.get_max_tokens_per_item_by_modality(model_config).items()
179
180
181
182
183
184
185
186
        }

    def get_max_multimodal_tokens(self, model_config: "ModelConfig") -> int:
        """
        Get the maximum number of multi-modal tokens
        for profiling the memory usage of a model.
        """
        return sum(self.get_max_tokens_by_modality(model_config).values())
187
188
189

    def get_mm_limits_per_prompt(
        self,
190
        model_config: "ModelConfig",
191
192
193
194
    ) -> Mapping[str, int]:
        """
        Get the maximum number of multi-modal input instances for each modality
        that are allowed per prompt for a model class.
195
        """
196
197
        if not model_config.is_multimodal_model:
            return {}
198

199
        processor = self.create_processor(model_config, disable_cache=False)
200
201
        profiler = MultiModalProfiler(processor)
        return profiler.get_mm_limits()
202
203
204

    def register_processor(
        self,
205
206
207
208
        processor: MultiModalProcessorFactory[_I],
        *,
        info: ProcessingInfoFactory[_I],
        dummy_inputs: DummyInputsBuilderFactory[_I],
209
210
    ):
        """
211
212
        Register a multi-modal processor to a model class. The processor
        is constructed lazily, hence a factory method should be passed.
213
214
215
216
217
218

        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:
219
            if self._processor_factories.contains(model_cls, strict=True):
220
                logger.warning(
221
                    "Model class %s already has a multi-modal processor "
222
223
224
                    "registered to %s. It is overwritten by the new one.",
                    model_cls, self)

225
226
227
228
229
            self._processor_factories[model_cls] = _ProcessorFactories(
                info=info,
                dummy_inputs=dummy_inputs,
                processor=processor,
            )
230
231
232
233
234

            return model_cls

        return wrapper

235
    def _get_model_cls(self, model_config: "ModelConfig"):
236
237
238
239
        # Avoid circular import
        from vllm.model_executor.model_loader import get_model_architecture

        model_cls, _ = get_model_architecture(model_config)
240
241
        return model_cls

242
243
244
    def create_processor(
        self,
        model_config: "ModelConfig",
245
        *,
246
        tokenizer: Optional[AnyTokenizer] = None,
247
        disable_cache: Optional[bool] = None,
248
    ) -> BaseMultiModalProcessor[BaseProcessingInfo]:
249
250
251
        """
        Create a multi-modal processor for a specific model and tokenizer.
        """
252
253
254
        if not model_config.is_multimodal_model:
            raise ValueError(f"{model_config.model} is not a multimodal model")

255
        if tokenizer is None and not model_config.skip_tokenizer_init:
256
            tokenizer = cached_tokenizer_from_config(model_config)
257
        if disable_cache is None:
258
            disable_cache = not model_config.enable_mm_processor_cache
259

260
        model_cls = self._get_model_cls(model_config)
261
        factories = self._processor_factories[model_cls]
262
263

        ctx = InputProcessingContext(model_config, tokenizer)
264
265
        cache = None if disable_cache else self._get_processor_cache(
            model_config)
266

267
        return factories.build_processor(ctx, cache=cache)
268
269
270
271
272

    def get_decoder_dummy_data(
        self,
        model_config: "ModelConfig",
        seq_len: int,
273
        mm_counts: Optional[Mapping[str, int]] = None,
274
275
276
277
278
279
    ) -> DummyDecoderData:
        """
        Create dummy data for profiling the memory usage of a model.

        The model is identified by ``model_config``.
        """
280
        processor = self.create_processor(model_config, disable_cache=False)
281
        profiler = MultiModalProfiler(processor)
282
        dummy_data = profiler.get_decoder_dummy_data(seq_len, mm_counts)
283
284
285
286
287
288
289
290
291
292
293
294
295
296

        # 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, "
                f"but found {len(token_ids)} tokens instead.")

        return dummy_data

    def get_encoder_dummy_data(
        self,
        model_config: "ModelConfig",
        seq_len: int,
297
        mm_counts: Optional[Mapping[str, int]] = None,
298
299
300
301
302
303
    ) -> DummyEncoderData:
        """
        Create dummy data for profiling the memory usage of a model.

        The model is identified by ``model_config``.
        """
304
        processor = self.create_processor(model_config, disable_cache=False)
305
        profiler = MultiModalProfiler(processor)
306
        dummy_data = profiler.get_encoder_dummy_data(seq_len, mm_counts)
307
308
309
310
311

        # 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(
312
313
314
315
                "Expected at least %d dummy encoder tokens for profiling, but found %d tokens instead.",  # noqa: E501
                seq_len,
                len(token_ids),
            )
316
317

        return dummy_data