preprocess.py 18.9 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
from collections.abc import Mapping
5
from typing import Any, overload
6
7
8

from typing_extensions import assert_never

9
from vllm.config import ModelConfig, ObservabilityConfig
10
from vllm.logger import init_logger
11
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
12
from vllm.multimodal.cache import BaseMultiModalProcessorCache
13
14
15
16
17
from vllm.multimodal.inputs import (
    MultiModalDataDict,
    MultiModalInputs,
    MultiModalUUIDDict,
)
18
from vllm.multimodal.processing import BaseMultiModalProcessor
19
from vllm.renderers import BaseRenderer, renderer_from_config
20
21
22
23
24
25
26
27
28
29
from vllm.renderers.inputs import (
    DecoderDictPrompt,
    DecoderOnlyDictPrompt,
    DictPrompt,
    EncoderDecoderDictPrompt,
    EncoderDictPrompt,
    SingletonDictPrompt,
    TokPrompt,
)
from vllm.renderers.inputs.preprocess import parse_dec_only_prompt, parse_enc_dec_prompt
30
from vllm.tokenizers import TokenizerLike
31
from vllm.utils.jsontree import json_iter_leaves
32
from vllm.v1.metrics.stats import MultiModalCacheStats
33

34
from .data import (
35
    DecoderInputs,
36
37
38
39
    DecoderOnlyInputs,
    EmbedsInputs,
    EmbedsPrompt,
    EncoderDecoderInputs,
40
    EncoderInputs,
41
42
43
44
45
46
47
48
49
    ProcessorInputs,
    PromptType,
    SingletonInputs,
    TextPrompt,
    TokenInputs,
    TokensPrompt,
    embeds_inputs,
    token_inputs,
)
50
51
52
53
54
55
56

logger = init_logger(__name__)


class InputPreprocessor:
    def __init__(
        self,
57
        model_config: ModelConfig,
58
        observability_config: ObservabilityConfig | None = None,
59
        renderer: BaseRenderer | None = None,
60
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
61
        mm_processor_cache: BaseMultiModalProcessorCache | None = None,
62
63
64
    ) -> None:
        super().__init__()

65
        self.model_config = model_config
66
        self.observability_config = observability_config
67
        self.renderer = renderer or renderer_from_config(model_config)
68
        self.mm_registry = mm_registry
69
        self.mm_processor_cache = mm_processor_cache
70

71
72
        self.mm_cache_stats = MultiModalCacheStats() if mm_processor_cache else None

73
74
75
    @property
    def tokenizer(self) -> TokenizerLike | None:
        return self.renderer.tokenizer
76

77
78
    def get_tokenizer(self) -> TokenizerLike:
        return self.renderer.get_tokenizer()
79

80
    def get_bos_token_id(self) -> int | None:
81
        if self.tokenizer is None:
82
            logger.warning_once(
83
84
                "Using None for BOS token id because tokenizer is not initialized"
            )
85
86
            return None

87
        return self.tokenizer.bos_token_id
88

89
    def get_eos_token_id(self) -> int | None:
90
        if self.tokenizer is None:
91
            logger.warning_once(
92
93
                "Using None for EOS token id because tokenizer is not initialized"
            )
94
95
            return None

96
        return self.tokenizer.eos_token_id
97

98
    def get_decoder_start_token_id(self) -> int:
99
        """
100
        Obtain the decoder start token id employed by an encoder/decoder
101
        model. Raises an error if it is not available.
102
        """
103
104
105
        dec_start_token_id = getattr(
            self.model_config.hf_config, "decoder_start_token_id", None
        )
106

107
        if dec_start_token_id is None:
108
109
110
            logger.warning_once(
                "Falling back on <BOS> for decoder start token "
                "id because decoder start token id is not "
111
112
                "available."
            )
113
114
            dec_start_token_id = self.get_bos_token_id()

115
116
        if dec_start_token_id is None:
            raise RuntimeError("Cannot find decoder start token id or <BOS>")
117

118
        return dec_start_token_id
119

120
    def _prepare_decoder_input_ids(self, decoder_input_ids: list[int]) -> list[int]:
121
122
123
        """
        Prepares `decoder_input_ids` for generation with encoder-decoder models.

124
125
126
127
        Based on:
        https://github.com/huggingface/transformers/blob/4037a2b5b1278736e566aec12e169100275545ea/src/transformers/generation/utils.py
        specifically,
        `GenerationMixin._prepare_decoder_input_ids_for_generation()`.
128
129
130
131
132
133
134
135
136
137
138

        Arguments:

        * decoder_input_ids: input token ids to preprocess

        Returns:

        * Processed token list
        """
        decoder_start_token_id = self.get_decoder_start_token_id()

139
140
141
142
        if (
            len(decoder_input_ids) == 0
            or decoder_input_ids[0] != decoder_start_token_id
        ):
143
144
145
146
            decoder_input_ids = [decoder_start_token_id] + decoder_input_ids

        return decoder_input_ids

147
148
    def _get_tokenization_kw(
        self,
149
        overrides: dict[str, Any] | None = None,
150
151
152
    ) -> dict[str, Any]:
        kwargs = dict[str, Any]()

153
        if self.model_config.is_encoder_decoder:
154
155
156
157
158
159
160
161
162
163
            # For Whisper, special tokens should be provided by the user based
            # on the task and language of their request. Also needed to avoid
            # appending an EOS token to the prompt which disrupts generation.
            kwargs["add_special_tokens"] = False

        if overrides:
            kwargs.update(overrides)

        return kwargs

164
165
166
    def _tokenize_prompt(
        self,
        prompt: str,
167
        tokenization_kwargs: dict[str, Any] | None = None,
168
    ) -> list[int]:
169
170
171
172
        """
        Apply the model's tokenizer to a text prompt, returning the
        corresponding token IDs.
        """
173
        tokenizer = self.get_tokenizer()
174
        tokenization_kwargs = self._get_tokenization_kw(tokenization_kwargs)
175

176
        encoder_config = self.model_config.encoder_config
177

178
        if encoder_config and encoder_config.get("do_lower_case", False):
179
180
            prompt = prompt.lower()

181
        return tokenizer.encode(prompt, **tokenization_kwargs)
182

183
184
185
    def _get_mm_processor(self) -> BaseMultiModalProcessor:
        if not hasattr(self, "_mm_processor"):
            self._mm_processor = self.mm_registry.create_processor(
186
                self.model_config,
187
                self.observability_config,
188
                tokenizer=self.tokenizer,
189
190
191
192
                cache=self.mm_processor_cache,
            )

        return self._mm_processor
193

194
195
    def _process_multimodal(
        self,
196
        prompt: str | list[int],
197
        mm_data: MultiModalDataDict,
198
199
        mm_processor_kwargs: Mapping[str, object] | None,
        tokenization_kwargs: dict[str, Any] | None = None,
200
        *,
201
        mm_uuids: MultiModalUUIDDict | None = None,
202
    ) -> MultiModalInputs:
203
204
205
206
        """
        Apply the model's multi-modal processor to a multi-modal prompt,
        returning the corresponding token IDs and metadata.
        """
207
        mm_processor = self._get_mm_processor()
208

209
210
211
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

212
        mm_items = mm_processor.info.parse_mm_data(mm_data)
213
        mm_input = mm_processor.apply(
214
            prompt,
215
            mm_items,
216
217
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
218
            mm_uuids=mm_uuids,
219
        )
220
221
222
        mm_hashes = mm_input["mm_hashes"]

        # Validate that all mm items have a string as their hash
223
224
225
226
        contains_only_strings = all(
            isinstance(leaf, str) for leaf in json_iter_leaves(mm_hashes)
        )
        if not contains_only_strings:
227
228
229
            raise ValueError(
                f"mm_hashes must contain only strings, got: {mm_hashes}. "
                "This is likely due to an incorrect custom implementation of "
230
231
                "MultiModalProcessor.apply method."
            )
232
233

        return mm_input
234

235
236
237
238
    def _process_embeds(
        self,
        parsed_content: EmbedsPrompt,
    ) -> EmbedsInputs:
239
        if not self.model_config.enable_prompt_embeds:
240
241
242
            raise ValueError(
                "You must set `--enable-prompt-embeds` to input `prompt_embeds`."
            )
243
244

        prompt_embeds = parsed_content["prompt_embeds"]
245

246
247
248
249
250
251
252
253
        # prompt_embeds must be (seq_len, hidden_size), but if the user
        # passes in a batch of size 1, i.e. (1, seq_len, hidden_size),
        # we can unambiguously process the intent by squeezing the batch
        # dimension.
        if prompt_embeds.ndim == 3:
            prompt_embeds = prompt_embeds.squeeze(dim=0)

        if prompt_embeds.ndim != 2:
254
            raise ValueError("prompt_embeds must be of shape (seq_len, hidden_size).")
255

256
257
258
259
260
        # Tensors must be on CPU for serialization between processes
        # in the MsgpackEncoder. Casting to CPU here ensures that there is no
        # hidden device transfer in the critical path of generation.
        prompt_embeds = prompt_embeds.cpu()

261
262
263
        return embeds_inputs(
            prompt_embeds=prompt_embeds, cache_salt=parsed_content.get("cache_salt")
        )
264

265
    def _truncate_inputs(
266
        self, inputs: list[int], tokenization_kwargs: dict[str, Any] | None = None
267
268
269
270
271
272
    ) -> list[int]:
        if (
            not tokenization_kwargs
            or "truncation" not in tokenization_kwargs
            or self.tokenizer is None
        ):
273
274
275
276
277
278
279
280
281
            return inputs

        max_length = tokenization_kwargs["max_length"]

        if self.tokenizer.truncation_side == "left":
            return inputs[-max_length:]
        else:
            return inputs[:max_length]

282
283
284
    def _process_tokens(
        self,
        parsed_content: TokensPrompt,
285
        tokenization_kwargs: dict[str, Any] | None = None,
286
        *,
287
288
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> TokenInputs | MultiModalInputs:
289
        prompt_token_ids = self._truncate_inputs(
290
291
            parsed_content["prompt_token_ids"], tokenization_kwargs
        )
292

293
        inputs: TokenInputs | MultiModalInputs
294
        if multi_modal_data := parsed_content.get("multi_modal_data"):
295
296
            inputs = self._process_multimodal(
                prompt_token_ids,
297
                multi_modal_data,
298
                parsed_content.get("mm_processor_kwargs") or {},
299
                tokenization_kwargs=tokenization_kwargs,
300
                mm_uuids=mm_uuids,
301
            )
302
        else:
303
            inputs = token_inputs(prompt_token_ids)
304
305
306
307
308
309
310
311
312

        if cache_salt := parsed_content.get("cache_salt"):
            inputs["cache_salt"] = cache_salt

        return inputs

    def _process_text(
        self,
        parsed_content: TextPrompt,
313
        tokenization_kwargs: dict[str, Any] | None = None,
314
        *,
315
316
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> TokenInputs | MultiModalInputs:
317
318
        prompt_text = parsed_content["prompt"]

319
        inputs: TokenInputs | MultiModalInputs
320
        if multi_modal_data := parsed_content.get("multi_modal_data"):
321
322
            inputs = self._process_multimodal(
                prompt_text,
323
                multi_modal_data,
324
                parsed_content.get("mm_processor_kwargs") or {},
325
                tokenization_kwargs=tokenization_kwargs,
326
                mm_uuids=mm_uuids,
327
328
329
330
331
332
            )
        else:
            prompt_token_ids = self._tokenize_prompt(
                prompt_text,
                tokenization_kwargs=tokenization_kwargs,
            )
333
            inputs = token_inputs(prompt_token_ids)
334
335
336
337
338

        if cache_salt := parsed_content.get("cache_salt"):
            inputs["cache_salt"] = cache_salt

        return inputs
339

340
    @overload
341
    def _prompt_to_llm_inputs(
342
        self,
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
        prompt: EncoderDictPrompt,
        tokenization_kwargs: dict[str, Any] | None = None,
        *,
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> EncoderInputs: ...

    @overload
    def _prompt_to_llm_inputs(  # type: ignore[misc]
        self,
        prompt: DecoderDictPrompt,
        tokenization_kwargs: dict[str, Any] | None = None,
        *,
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> DecoderInputs: ...

    @overload
    def _prompt_to_llm_inputs(  # type: ignore[misc]
        self,
        prompt: DecoderOnlyDictPrompt,
        tokenization_kwargs: dict[str, Any] | None = None,
        *,
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> DecoderOnlyInputs: ...

    def _prompt_to_llm_inputs(
        self,
        prompt: SingletonDictPrompt,
370
        tokenization_kwargs: dict[str, Any] | None = None,
371
        *,
372
        mm_uuids: MultiModalUUIDDict | None = None,
373
    ) -> SingletonInputs:
374
375
        """
        Extract the singleton inputs from a prompt.
376
377
378

        Arguments:

379
        * prompt: single encoder or decoder input prompt
380
381
382

        Returns:

383
        * [`SingletonInputs`][vllm.inputs.data.SingletonInputs] instance
384
        """
385
386
        if "prompt_embeds" in prompt:
            return self._process_embeds(prompt)  # type: ignore[arg-type]
387

388
        if "prompt_token_ids" in prompt:
389
            return self._process_tokens(
390
                prompt,  # type: ignore[arg-type]
391
                mm_uuids=mm_uuids,
392
            )
393
394

        if "prompt" in prompt:
395
            return self._process_text(
396
                prompt,  # type: ignore[arg-type]
397
                tokenization_kwargs=tokenization_kwargs,
398
                mm_uuids=mm_uuids,
399
            )
400

401
        assert_never(prompt)  # type: ignore[arg-type]
402

403
    def _validate_enc_inputs(self, inputs: SingletonInputs) -> EncoderInputs:
404
        if inputs["type"] == "embeds":
405
406
407
            raise ValueError(
                "Embedding inputs are not supported for encoder-decoder models"
            )
408

409
410
411
412
        if inputs["type"] == "multimodal" and "encoder_prompt_token_ids" not in inputs:
            raise RuntimeError(
                "You should register an encoder-decoder "
                "multi-modal processor for encoder-decoder models."
413
            )
414

415
        return inputs  # type: ignore[return-value]
416

417
    def _validate_dec_inputs(self, inputs: SingletonInputs) -> DecoderInputs:
418
        if inputs["type"] == "embeds":
419
420
421
            raise ValueError(
                "Embedding inputs are not supported for encoder-decoder models"
            )
422

423
        return inputs
424

425
426
427
428
429
430
    def _build_enc_dec_inputs(
        self,
        encoder_inputs: SingletonInputs,
        decoder_inputs: SingletonInputs | None = None,
    ) -> EncoderDecoderInputs:
        enc_inputs = self._validate_enc_inputs(encoder_inputs)
431

432
433
434
435
436
437
438
        if decoder_inputs is None:
            dec_inputs: DecoderInputs = enc_inputs  # type: ignore[assignment]
        else:
            dec_inputs = self._validate_dec_inputs(decoder_inputs)

        enc_inputs_new: EncoderInputs
        dec_inputs_new: DecoderInputs
439

440
441
442
        if enc_inputs["type"] == "multimodal":
            enc_inputs_new = token_inputs(enc_inputs["encoder_prompt_token_ids"])
            dec_inputs_new = MultiModalInputs(
443
                type="multimodal",
444
445
446
447
                prompt_token_ids=dec_inputs["prompt_token_ids"],
                mm_kwargs=enc_inputs["mm_kwargs"],
                mm_hashes=enc_inputs["mm_hashes"],
                mm_placeholders=enc_inputs["mm_placeholders"],
448
            )
449
450
451
        elif enc_inputs["type"] == "token":
            enc_inputs_new = token_inputs(prompt_token_ids=[])
            dec_inputs_new = dec_inputs
452
        else:
453
454
455
456
457
458
459
            assert_never(enc_inputs)

        dec_inputs_new["prompt_token_ids"] = self._prepare_decoder_input_ids(
            dec_inputs_new["prompt_token_ids"]
        )
        if cache_salt := enc_inputs.get("cache_salt"):
            dec_inputs_new["cache_salt"] = cache_salt
460

461
        return EncoderDecoderInputs(encoder=enc_inputs_new, decoder=dec_inputs_new)
462

463
464
    def _process_encoder_decoder_prompt(
        self,
465
        prompt: EncoderDecoderDictPrompt,
466
        tokenization_kwargs: dict[str, Any] | None = None,
467
        *,
468
        mm_uuids: MultiModalUUIDDict | None = None,
469
    ) -> EncoderDecoderInputs:
470
        """
471
        For encoder/decoder models only:
472
473
474
        Process an input prompt into an
        [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
        instance.
475
476
477

        Arguments:

478
        * prompt: an input prompt
479
480
481

        Returns:

482
483
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
484
        """
485
486
        encoder_prompt = prompt["encoder_prompt"]
        decoder_prompt = prompt["decoder_prompt"]
487
488
489
490

        return self._build_enc_dec_inputs(
            encoder_inputs=self._prompt_to_llm_inputs(
                encoder_prompt,
491
                tokenization_kwargs=tokenization_kwargs,
492
                mm_uuids=mm_uuids,
493
494
495
496
497
498
499
            ),
            decoder_inputs=(
                None
                if decoder_prompt is None
                else self._prompt_to_llm_inputs(
                    decoder_prompt,
                    tokenization_kwargs=tokenization_kwargs,
500
                )
501
502
            ),
        )
503
504
505

    def _process_decoder_only_prompt(
        self,
506
        prompt: DecoderOnlyDictPrompt,
507
        tokenization_kwargs: dict[str, Any] | None = None,
508
        *,
509
        mm_uuids: MultiModalUUIDDict | None = None,
510
    ) -> DecoderOnlyInputs:
511
        """
512
        For decoder-only models:
513
514
        Process an input prompt into a
        [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance.
515
516
517

        Arguments:

518
        * prompt: input prompt
519
520
521

        Returns:

522
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
523
        """
524
        return self._prompt_to_llm_inputs(
525
            prompt,
526
            tokenization_kwargs=tokenization_kwargs,
527
            mm_uuids=mm_uuids,
528
529
        )

530
    def _preprocess(
531
        self,
532
        prompt: PromptType | DictPrompt | TokPrompt,
533
        tokenization_kwargs: dict[str, Any] | None = None,
534
        *,
535
        mm_uuids: MultiModalUUIDDict | None = None,
536
    ) -> ProcessorInputs:
537
        if self.model_config.is_encoder_decoder:
538
            # Encoder-decoder model requires special mapping of
539
            # input prompts to encoder & decoder.
540
            return self._process_encoder_decoder_prompt(
541
                parse_enc_dec_prompt(prompt),
542
                tokenization_kwargs,
543
                mm_uuids=mm_uuids,
544
            )
545
546

        return self._process_decoder_only_prompt(
547
            parse_dec_only_prompt(prompt),
548
            tokenization_kwargs=tokenization_kwargs,
549
            mm_uuids=mm_uuids,
550
551
        )

552
553
    def preprocess(
        self,
554
        prompt: PromptType | DictPrompt | TokPrompt,
555
        tokenization_kwargs: dict[str, Any] | None = None,
556
        *,
557
        mm_uuids: MultiModalUUIDDict | None = None,
558
559
    ) -> ProcessorInputs:
        """Preprocess the input prompt."""
560
        res = self._preprocess(prompt, tokenization_kwargs, mm_uuids=mm_uuids)
561
562
563
564
565
566
567
568
569

        if self.mm_processor_cache and self.mm_cache_stats is not None:
            delta = self.mm_processor_cache.make_stats(delta=True)
            self.mm_cache_stats.requests += 1
            self.mm_cache_stats.queries += delta.total
            self.mm_cache_stats.hits += delta.hits

        return res

570
    def stat_mm_cache(self) -> MultiModalCacheStats | None:
571
572
573
574
575
576
577
578
579
        mm_cache_stats = self.mm_cache_stats
        if mm_cache_stats is None:
            return None

        self.mm_cache_stats = MultiModalCacheStats()

        return mm_cache_stats

    def clear_mm_cache(self) -> None:
580
581
        if self.mm_processor_cache is not None:
            self.mm_processor_cache.clear_cache()
582
583
584

        if self.mm_cache_stats is not None:
            self.mm_cache_stats.reset = True