profiling.py 7.9 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
4
5
from abc import ABC, abstractmethod
from collections.abc import Mapping
from dataclasses import dataclass, field
6
from typing import Generic, TypeVar, cast
7
8
9
10
11

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

12
13
import vllm.envs as envs
from vllm.inputs import DummyData
14
15
from vllm.logger import init_logger

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

logger = init_logger(__name__)


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


34
35
36
37
_I = TypeVar("_I", bound=BaseProcessingInfo)


class BaseDummyInputsBuilder(ABC, Generic[_I]):
38
    """
39
    Abstract base class that constructs the dummy data to profile
40
41
42
    multi-modal models.
    """

43
    def __init__(self, info: _I) -> None:
44
45
        super().__init__()

46
        self.info = info
47
48
49
50
51
52
53
54

    @abstractmethod
    def get_dummy_processor_inputs(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
    ) -> ProcessorInputs:
        """
55
        Build the input which, after processing, results in
56
        :code:`self.info.get_mm_max_tokens_per_item()` placeholder tokens.
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        """
        raise NotImplementedError

    def _get_dummy_audios(
        self,
        *,
        length: int,
        num_audios: int,
    ) -> list[npt.NDArray]:
        audio = np.zeros((length, ))
        return [audio] * num_audios

    def _get_dummy_images(
        self,
        *,
        width: int,
        height: int,
        num_images: int,
    ) -> list[Image.Image]:
        image = Image.new("RGB", (width, height), color=0)
        return [image] * num_images

    def _get_dummy_videos(
        self,
        *,
        width: int,
        height: int,
        num_frames: int,
        num_videos: int,
    ) -> list[npt.NDArray]:
        video = np.zeros((num_frames, width, height, 3))
        return [video] * num_videos

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

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

112
    def get_mm_limits(self) -> Mapping[str, int]:
113
114
        mm_config = self.processing_info.ctx.get_mm_config()
        supported_mm_limits = self.processing_info.get_supported_mm_limits()
115
116

        mm_limits = {
117
            modality: mm_config.get_limit_per_prompt(modality)
118
119
120
121
122
123
124
125
126
127
128
129
            for modality in supported_mm_limits
        }

        for modality, supported_limit in supported_mm_limits.items():
            limit = mm_limits[modality]
            if supported_limit is not None and supported_limit < limit:
                raise ValueError(
                    f"You set {modality}={limit} (or defaulted to 1) in "
                    f"`--limit-mm-per-prompt`, but this model only supports "
                    f"at most {supported_limit} {modality} items.")

        return mm_limits
130
131
132
133
134

    def _get_dummy_mm_inputs(
        self,
        seq_len: int,
        mm_counts: Mapping[str, int],
135
    ) -> MultiModalInputs:
136
137
138
139
140
        factory = self.dummy_inputs
        processor_inputs = factory.get_dummy_processor_inputs(
            seq_len, mm_counts)

        return self.processor.apply(
141
            prompt=processor_inputs.prompt_text,
142
143
144
145
            mm_data=processor_inputs.mm_data,
            hf_processor_mm_kwargs=processor_inputs.hf_processor_mm_kwargs,
        )

146
    def get_and_validate_mm_inputs(
147
148
        self,
        seq_len: int,
149
    ) -> tuple[MultiModalInputs, Mapping[str, int]]:
150
        mm_counts = self.get_mm_limits()
151
152

        info = self.processing_info
153
154
        mm_max_tokens_per_item = info.get_mm_max_tokens_per_item(
            seq_len, mm_counts)
155
156
157

        if mm_counts.keys() != mm_max_tokens_per_item.keys():
            raise AssertionError(
158
                "The keys returned by `get_supported_mm_limits` "
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
                f"({set(mm_counts.keys())}) should be the same as those "
                "returned by `get_mm_max_tokens_per_item` "
                f"({set(mm_max_tokens_per_item.keys())})")

        mm_inputs = self._get_dummy_mm_inputs(seq_len, mm_counts)
        placeholders_by_modality = mm_inputs["mm_placeholders"]

        total_placeholders_by_modality = {
            modality: sum(item["length"] for item in placeholders)
            for modality, placeholders in placeholders_by_modality.items()
        }
        expected_placeholders_by_modality = {
            modality: mm_max_tokens_per_item[modality] * mm_counts[modality]
            for modality in placeholders_by_modality
        }
        if total_placeholders_by_modality != expected_placeholders_by_modality:
            raise AssertionError(
                f"The processed dummy data has a total of "
                f"{total_placeholders_by_modality} placeholder tokens, which "
                f"is not the expected {expected_placeholders_by_modality} "
                "tokens.")
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        return mm_inputs, total_placeholders_by_modality

    def get_encoder_dummy_data(
        self,
        seq_len: int,
    ) -> DummyData:
        # Avoid circular import
        from vllm.sequence import SequenceData

        mm_inputs, _ = self.get_and_validate_mm_inputs(seq_len)
        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)
        num_tokens_to_pad = max(total_len, seq_len) - total_len
        encoder_prompt_token_ids.extend([0] * num_tokens_to_pad)

        return DummyData(
            seq_data=SequenceData.from_seqs(encoder_prompt_token_ids),
            multi_modal_data=None,
            multi_modal_placeholders=None,
        )

    def get_decoder_dummy_data(
        self,
        seq_len: int,
    ) -> DummyData:
        # Avoid circular import
        from vllm.sequence import SequenceData

        (mm_inputs, total_placeholders_by_modality
         ) = self.get_and_validate_mm_inputs(seq_len)
215

216
        prompt_token_ids = mm_inputs["prompt_token_ids"]
217
218
219
        total_len = len(prompt_token_ids)

        # V0 does not support chunked prefill.
220
221
222
223
224
225
226
227
228
229
230
        if total_len > seq_len and not envs.VLLM_USE_V1:
            logger.warning(
                "The context length (%d) of the model 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). This may cause certain "
                "multi-modal inputs to fail during inference, even when "
                "the input text is short. To avoid this, you should "
                "increase `max_model_len`, reduce `max_num_seqs`, "
                "and/or reduce `mm_counts`.", seq_len, total_len,
                total_placeholders_by_modality)
231

232
            return DummyData(
233
                seq_data=SequenceData.from_prompt_token_counts((0, seq_len)),
234
235
236
237
238
239
240
241
242
                multi_modal_data=None,
                multi_modal_placeholders=None,
            )

        prompt_token_ids.extend([0] * (seq_len - len(prompt_token_ids)))

        return DummyData(
            seq_data=SequenceData.from_seqs(prompt_token_ids),
            multi_modal_data=mm_inputs["mm_kwargs"],
243
            multi_modal_placeholders=mm_inputs["mm_placeholders"],
244
        )