profiling.py 8.38 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
from abc import ABC, abstractmethod
3
4
from collections.abc import Mapping
from dataclasses import dataclass, field
5
from typing import Generic, NamedTuple, Optional, TypeVar, Union, cast
6
7
8
9
10

import numpy as np
import numpy.typing as npt
from PIL import Image

11
import vllm.envs as envs
12
13
from vllm.logger import init_logger

14
from .inputs import (MultiModalDataDict, MultiModalEncDecInputs,
15
16
                     MultiModalInputs, MultiModalKwargs,
                     MultiModalPlaceholderDict)
17
18
from .processing import (BaseMultiModalProcessor, BaseProcessingInfo,
                         EncDecMultiModalProcessor)
19
20
21
22
23
24

logger = init_logger(__name__)


@dataclass
class ProcessorInputs:
25
26
    """
    Represents the keyword arguments to
27
    [`vllm.multimodal.processing.BaseMultiModalProcessor.apply`][].
28
    """
29
    prompt: Union[str, list[int]]
30
31
32
33
    mm_data: MultiModalDataDict
    hf_processor_mm_kwargs: Mapping[str, object] = field(default_factory=dict)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
class DummyEncoderData(NamedTuple):
    """Dummy data used for profiling."""

    prompt_token_ids: list[int]


class DummyDecoderData(NamedTuple):
    """Dummy data used for profiling."""

    prompt_token_ids: list[int]
    multi_modal_data: MultiModalKwargs
    multi_modal_placeholders: MultiModalPlaceholderDict


48
49
50
51
_I = TypeVar("_I", bound=BaseProcessingInfo)


class BaseDummyInputsBuilder(ABC, Generic[_I]):
52
    """
53
    Abstract base class that constructs the dummy data to profile
54
55
56
    multi-modal models.
    """

57
    def __init__(self, info: _I) -> None:
58
59
        super().__init__()

60
        self.info = info
61

62
    @abstractmethod
63
64
    def get_dummy_text(self, mm_counts: Mapping[str, int]) -> str:
        """
65
        Build the text input corresponding to `mm_counts`.
66
        """
67
        raise NotImplementedError
68

69
    @abstractmethod
70
71
72
73
74
75
76
77
78
79
80
    def get_dummy_mm_data(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> MultiModalDataDict:
        """
        Build the multimodal input which, after processing, results in
        the maximum possible number of placeholder tokens.
        """
        raise NotImplementedError

81
82
83
84
85
86
    def get_dummy_processor_inputs(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> ProcessorInputs:
        """
87
        Build the input which, after processing, results in
88
        the maximum possible number of placeholder tokens.
89
        """
90
91
92
        dummy_text = self.get_dummy_text(mm_counts)
        dummy_mm_data = self.get_dummy_mm_data(seq_len, mm_counts)

93
        return ProcessorInputs(prompt=dummy_text, mm_data=dummy_mm_data)
94
95
96
97
98
99
100

    def _get_dummy_audios(
        self,
        *,
        length: int,
        num_audios: int,
    ) -> list[npt.NDArray]:
101
102
        if num_audios == 0:
            return []
103
104
105
106
107
108
109
110
111
112
        audio = np.zeros((length, ))
        return [audio] * num_audios

    def _get_dummy_images(
        self,
        *,
        width: int,
        height: int,
        num_images: int,
    ) -> list[Image.Image]:
113
114
        if num_images == 0:
            return []
115
        image = Image.new("RGB", (width, height), color=255)
116
117
118
119
120
121
122
123
124
125
        return [image] * num_images

    def _get_dummy_videos(
        self,
        *,
        width: int,
        height: int,
        num_frames: int,
        num_videos: int,
    ) -> list[npt.NDArray]:
126
127
        if num_videos == 0:
            return []
128
        video = np.full((num_frames, width, height, 3), 255)
129
130
        return [video] * num_videos

131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

class MultiModalProfiler(Generic[_I]):
    """
    Contains code for running memory profiling for multi-modal models.
    """

    def __init__(
        self,
        processor: BaseMultiModalProcessor[_I],
    ) -> None:
        super().__init__()

        self.processor = processor

    @property
    def processing_info(self) -> BaseProcessingInfo:
        return self.processor.info

    @property
    def dummy_inputs(self) -> BaseDummyInputsBuilder[_I]:
        return self.processor.dummy_inputs

153
    def get_mm_limits(self) -> Mapping[str, int]:
154
        return self.processing_info.get_allowed_mm_limits()
155
156
157
158

    def _get_dummy_mm_inputs(
        self,
        seq_len: int,
159
        mm_counts: Optional[Mapping[str, int]] = None,
160
    ) -> MultiModalInputs:
161
162
163
        if mm_counts is None:
            mm_counts = self.get_mm_limits()

164
165
166
167
168
        factory = self.dummy_inputs
        processor_inputs = factory.get_dummy_processor_inputs(
            seq_len, mm_counts)

        return self.processor.apply(
169
            prompt=processor_inputs.prompt,
170
171
172
173
            mm_data=processor_inputs.mm_data,
            hf_processor_mm_kwargs=processor_inputs.hf_processor_mm_kwargs,
        )

174
    def _get_mm_num_tokens(
175
        self,
176
177
        mm_inputs: MultiModalInputs,
    ) -> Mapping[str, int]:
178
179
        placeholders_by_modality = mm_inputs["mm_placeholders"]

180
        return {
181
            modality: sum(item.get_num_embeds() for item in placeholders)
182
183
            for modality, placeholders in placeholders_by_modality.items()
        }
184

185
186
187
188
189
    def get_encoder_dummy_data(
        self,
        seq_len: int,
        mm_counts: Optional[Mapping[str, int]] = None,
    ) -> DummyEncoderData:
190
        mm_inputs = self._get_dummy_mm_inputs(seq_len, mm_counts)
191
192
193
194
195
196
197
        mm_inputs = cast(MultiModalEncDecInputs, mm_inputs)

        # For encoder-decoder models, use encoder prompt token ids instead of
        # decoder prompt to construct dummy seq_data for encoder profiling.
        encoder_prompt_token_ids = mm_inputs["encoder_prompt_token_ids"]

        total_len = len(encoder_prompt_token_ids)
198

199
200
201
202
203
204
        processor = cast(EncDecMultiModalProcessor, self.processor)
        if processor.pad_dummy_encoder_prompt:
            num_tokens_to_pad = max(total_len, seq_len) - total_len
            encoder_prompt_token_ids.extend([0] * num_tokens_to_pad)
        # NOTE: Whisper allows total_len > seq_len.
        elif total_len > seq_len and not envs.VLLM_USE_V1:
205
            # `max_num_batched_tokens` is defined by `SchedulerConfig`
206
            logger.warning_once(
207
208
209
210
211
212
213
214
                "The encoder sequence length used for profiling (max_num_batched_tokens / max_num_seqs = %d) "  # noqa: E501
                "is too short to hold the multi-modal embeddings in the worst case (%d tokens in total, out of which %s are reserved for multi-modal embeddings). "  # noqa: E501
                "This may cause certain multi-modal inputs to fail during inference, even when the input text is short. "  # noqa: E501
                "To avoid this, you should increase `max_model_len`, reduce `max_num_seqs`, and/or reduce `mm_counts`.",  # noqa: E501
                seq_len,
                total_len,
                str(self._get_mm_num_tokens(mm_inputs)),
            )
215

216
        return DummyEncoderData(encoder_prompt_token_ids)
217

218
219
220
221
222
    def get_decoder_dummy_data(
        self,
        seq_len: int,
        mm_counts: Optional[Mapping[str, int]] = None,
    ) -> DummyDecoderData:
223
        mm_inputs = self._get_dummy_mm_inputs(seq_len, mm_counts)
224

225
        prompt_token_ids = mm_inputs["prompt_token_ids"]
226
227
228
        total_len = len(prompt_token_ids)

        # V0 does not support chunked prefill.
229
        if total_len > seq_len and not envs.VLLM_USE_V1:
230
            # `max_num_batched_tokens` is defined by `SchedulerConfig`
231
            logger.warning_once(
232
233
234
235
236
237
238
239
                "The sequence length used for profiling (max_num_batched_tokens / max_num_seqs = %d) "  # noqa: E501
                "is too short to hold the multi-modal embeddings in the worst case (%d tokens in total, out of which %s are reserved for multi-modal embeddings). "  # noqa: E501
                "This may cause certain multi-modal inputs to fail during inference, even when the input text is short. "  # noqa: E501
                "To avoid this, you should increase `max_model_len`, reduce `max_num_seqs`, and/or reduce `mm_counts`.",  # noqa: E501
                seq_len,
                total_len,
                str(self._get_mm_num_tokens(mm_inputs)),
            )
240

241
242
        if total_len < seq_len:
            prompt_token_ids.extend([0] * (seq_len - total_len))
243

244
245
        return DummyDecoderData(
            prompt_token_ids=prompt_token_ids,
246
            multi_modal_data=mm_inputs["mm_kwargs"],
247
            multi_modal_placeholders=mm_inputs["mm_placeholders"],
248
        )
249
250
251
252
253
254
255
256
257

    def get_mm_max_tokens(
        self,
        seq_len: int,
        mm_counts: Optional[Mapping[str, int]] = None,
    ) -> Mapping[str, int]:
        mm_inputs = self._get_dummy_mm_inputs(seq_len, mm_counts)

        return self._get_mm_num_tokens(mm_inputs)