preprocess.py 24.2 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, cast
6
7
8

from typing_extensions import assert_never

9
from vllm.config import RendererConfig
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
18
from vllm.multimodal.inputs import (
    MultiModalDataDict,
    MultiModalEncDecInputs,
    MultiModalInputs,
    MultiModalUUIDDict,
)
19
from vllm.multimodal.processing import BaseMultiModalProcessor
20
from vllm.tokenizers import TokenizerLike
21
from vllm.utils.jsontree import json_iter_leaves
22
from vllm.v1.metrics.stats import MultiModalCacheStats
23

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from .data import (
    DecoderOnlyInputs,
    EmbedsInputs,
    EmbedsPrompt,
    EncoderDecoderInputs,
    ExplicitEncoderDecoderPrompt,
    ProcessorInputs,
    PromptType,
    SingletonInputs,
    SingletonPrompt,
    TextPrompt,
    TokenInputs,
    TokensPrompt,
    embeds_inputs,
    token_inputs,
)
40
from .parse import is_explicit_encoder_decoder_prompt, parse_singleton_prompt
41
42
43
44
45
46
47

logger = init_logger(__name__)


class InputPreprocessor:
    def __init__(
        self,
48
        renderer_config: RendererConfig,
49
        tokenizer: TokenizerLike | None,
50
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
51
        mm_processor_cache: BaseMultiModalProcessorCache | None = None,
52
53
54
    ) -> None:
        super().__init__()

55
56
        self.renderer_config = renderer_config
        self.model_config = renderer_config.model_config
57
        self.tokenizer = tokenizer
58
        self.mm_registry = mm_registry
59
        self.mm_processor_cache = mm_processor_cache
60

61
62
        self.mm_cache_stats = MultiModalCacheStats() if mm_processor_cache else None

63
    def get_tokenizer(self) -> TokenizerLike:
64
        if self.tokenizer is None:
65
            raise ValueError(
66
                "You cannot pass text prompts when `skip_tokenizer_init=True`"
67
            )
68
69
70

        return self.tokenizer

71
    def get_bos_token_id(self) -> int | None:
72
        if self.tokenizer is None:
73
            logger.warning_once(
74
75
                "Using None for BOS token id because tokenizer is not initialized"
            )
76
77
            return None

78
        return self.tokenizer.bos_token_id
79

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

87
        return self.tokenizer.eos_token_id
88

89
    def get_decoder_start_token_id(self) -> int | None:
90
        """
91
92
93
        Obtain the decoder start token id employed by an encoder/decoder
        model. Returns None for non-encoder/decoder models or if the
        model config is unavailable.
94
        """
95

96
        if not self.model_config.is_encoder_decoder:
97
98
            logger.warning_once(
                "Using None for decoder start token id because "
99
100
                "this is not an encoder/decoder model."
            )
101
102
            return None

103
        if self.model_config is None or self.model_config.hf_config is None:
104
105
            logger.warning_once(
                "Using None for decoder start token id because "
106
107
                "model config is not available."
            )
108
109
            return None

110
111
112
        dec_start_token_id = getattr(
            self.model_config.hf_config, "decoder_start_token_id", None
        )
113
        if dec_start_token_id is None:
114
115
116
            logger.warning_once(
                "Falling back on <BOS> for decoder start token "
                "id because decoder start token id is not "
117
118
                "available."
            )
119
120
121
122
            dec_start_token_id = self.get_bos_token_id()

        return dec_start_token_id

123
    def _get_default_enc_dec_decoder_prompt(self) -> list[int]:
124
        """
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
        Specifically for encoder/decoder models:
        generate a default decoder prompt for when
        the user specifies only the encoder prompt.

        Encoder/decoder models utilize the decoder
        prompt in different ways; as new models are
        added, it is intended that this function
        will be extended to produce differing
        default decoder prompts, depending on the
        model variety.

        Absent a special case, the default behavior
        of this method is to mirror the behavior of
        the HuggingFace (HF) GenerationMixin for a None
        decoder prompt, which is to employ a logit processor
        setting to force the first decoded token to be <BOS>.
        Here, this behavior is approximated by having the
        "default" decoder prompt be <BOS>.

        However, it is possible that in the future
145
        other models may have different or more
146
147
148
149
150
151
152
        complex logic for the default decoder prompt.
        This motivates having a special helper method
        for default decoder prompts.

        Returns:

        * prompt_token_ids
153
        """
154
155
156
157
158
159
160

        bos_token_id = self.get_bos_token_id()
        assert bos_token_id is not None
        return [bos_token_id]

    def _prepare_decoder_input_ids_for_generation(
        self,
161
        decoder_input_ids: list[int] | None,
162
    ) -> list[int]:
163
164
165
        """
        Prepares `decoder_input_ids` for generation with encoder-decoder models.

166
167
168
169
        Based on:
        https://github.com/huggingface/transformers/blob/4037a2b5b1278736e566aec12e169100275545ea/src/transformers/generation/utils.py
        specifically,
        `GenerationMixin._prepare_decoder_input_ids_for_generation()`.
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187

        Arguments:

        * decoder_input_ids: input token ids to preprocess

        Returns:

        * Processed token list
        """

        decoder_start_token_id = self.get_decoder_start_token_id()
        assert decoder_start_token_id is not None

        if decoder_input_ids is None:
            # no decoder prompt input ->
            # use decoder_start_token_id as decoder_input_ids
            decoder_input_ids = self._get_default_enc_dec_decoder_prompt()

188
189
190
191
        if (
            len(decoder_input_ids) == 0
            or decoder_input_ids[0] != decoder_start_token_id
        ):
192
193
194
195
            decoder_input_ids = [decoder_start_token_id] + decoder_input_ids

        return decoder_input_ids

196
197
    def _get_tokenization_kw(
        self,
198
        overrides: dict[str, Any] | None = None,
199
200
201
    ) -> dict[str, Any]:
        kwargs = dict[str, Any]()

202
        if self.model_config.is_encoder_decoder:
203
204
205
206
207
208
209
210
211
212
            # 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

213
214
215
    def _tokenize_prompt(
        self,
        prompt: str,
216
        tokenization_kwargs: dict[str, Any] | None = None,
217
    ) -> list[int]:
218
219
220
221
        """
        Apply the model's tokenizer to a text prompt, returning the
        corresponding token IDs.
        """
222
        tokenizer = self.get_tokenizer()
223
        tokenization_kwargs = self._get_tokenization_kw(tokenization_kwargs)
224

225
        encoder_config = self.model_config.encoder_config
226

227
        if encoder_config and encoder_config.get("do_lower_case", False):
228
229
            prompt = prompt.lower()

230
        return tokenizer.encode(prompt, **tokenization_kwargs)
231

232
233
234
    def _get_mm_processor(self) -> BaseMultiModalProcessor:
        if not hasattr(self, "_mm_processor"):
            self._mm_processor = self.mm_registry.create_processor(
235
                self.renderer_config,
236
                tokenizer=self.tokenizer,
237
238
239
240
                cache=self.mm_processor_cache,
            )

        return self._mm_processor
241

242
243
    def _process_multimodal(
        self,
244
        prompt: str | list[int],
245
        mm_data: MultiModalDataDict,
246
247
        mm_processor_kwargs: Mapping[str, object] | None,
        tokenization_kwargs: dict[str, Any] | None = None,
248
        *,
249
        mm_uuids: MultiModalUUIDDict | None = None,
250
    ) -> MultiModalInputs:
251
252
253
254
        """
        Apply the model's multi-modal processor to a multi-modal prompt,
        returning the corresponding token IDs and metadata.
        """
255
        mm_processor = self._get_mm_processor()
256

257
258
259
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

260
        mm_input = mm_processor.apply(
261
262
263
264
            prompt,
            mm_data,
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
265
            mm_uuids=mm_uuids,
266
        )
267
268
269
        mm_hashes = mm_input["mm_hashes"]

        # Validate that all mm items have a string as their hash
270
271
272
273
        contains_only_strings = all(
            isinstance(leaf, str) for leaf in json_iter_leaves(mm_hashes)
        )
        if not contains_only_strings:
274
275
276
            raise ValueError(
                f"mm_hashes must contain only strings, got: {mm_hashes}. "
                "This is likely due to an incorrect custom implementation of "
277
278
                "MultiModalProcessor.apply method."
            )
279
280

        return mm_input
281

282
283
284
285
    def _process_embeds(
        self,
        parsed_content: EmbedsPrompt,
    ) -> EmbedsInputs:
286
        if not self.model_config.enable_prompt_embeds:
287
288
289
            raise ValueError(
                "You must set `--enable-prompt-embeds` to input `prompt_embeds`."
            )
290
291

        prompt_embeds = parsed_content["prompt_embeds"]
292

293
294
295
296
297
298
299
300
        # 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:
301
            raise ValueError("prompt_embeds must be of shape (seq_len, hidden_size).")
302

303
304
305
306
307
        # 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()

308
309
310
        return embeds_inputs(
            prompt_embeds=prompt_embeds, cache_salt=parsed_content.get("cache_salt")
        )
311

312
    def _truncate_inputs(
313
        self, inputs: list[int], tokenization_kwargs: dict[str, Any] | None = None
314
315
316
317
318
319
    ) -> list[int]:
        if (
            not tokenization_kwargs
            or "truncation" not in tokenization_kwargs
            or self.tokenizer is None
        ):
320
321
322
323
324
325
326
327
328
            return inputs

        max_length = tokenization_kwargs["max_length"]

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

329
330
331
    def _process_tokens(
        self,
        parsed_content: TokensPrompt,
332
        tokenization_kwargs: dict[str, Any] | None = None,
333
        *,
334
335
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> TokenInputs | MultiModalInputs:
336
        prompt_token_ids = self._truncate_inputs(
337
338
            parsed_content["prompt_token_ids"], tokenization_kwargs
        )
339

340
        inputs: TokenInputs | MultiModalInputs
341
        if multi_modal_data := parsed_content.get("multi_modal_data"):
342
343
            inputs = self._process_multimodal(
                prompt_token_ids,
344
                multi_modal_data,
345
                parsed_content.get("mm_processor_kwargs") or {},
346
                tokenization_kwargs=tokenization_kwargs,
347
                mm_uuids=mm_uuids,
348
            )
349
        else:
350
            inputs = token_inputs(prompt_token_ids)
351
352
353
354
355
356
357
358
359

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

        return inputs

    def _process_text(
        self,
        parsed_content: TextPrompt,
360
        tokenization_kwargs: dict[str, Any] | None = None,
361
        *,
362
363
        mm_uuids: MultiModalUUIDDict | None = None,
    ) -> TokenInputs | MultiModalInputs:
364
365
        prompt_text = parsed_content["prompt"]

366
        inputs: TokenInputs | MultiModalInputs
367
        if multi_modal_data := parsed_content.get("multi_modal_data"):
368
369
            inputs = self._process_multimodal(
                prompt_text,
370
                multi_modal_data,
371
                parsed_content.get("mm_processor_kwargs") or {},
372
                tokenization_kwargs=tokenization_kwargs,
373
                mm_uuids=mm_uuids,
374
375
376
377
378
379
            )
        else:
            prompt_token_ids = self._tokenize_prompt(
                prompt_text,
                tokenization_kwargs=tokenization_kwargs,
            )
380
            inputs = token_inputs(prompt_token_ids)
381
382
383
384
385

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

        return inputs
386

387
    def _prompt_to_llm_inputs(
388
        self,
389
        prompt: SingletonPrompt,
390
        tokenization_kwargs: dict[str, Any] | None = None,
391
        *,
392
        mm_uuids: MultiModalUUIDDict | None = None,
393
    ) -> SingletonInputs:
394
395
        """
        Extract the singleton inputs from a prompt.
396
397
398

        Arguments:

399
        * prompt: single encoder or decoder input prompt
400
401
402

        Returns:

403
        * [`SingletonInputs`][vllm.inputs.data.SingletonInputs] instance
404
        """
405
        parsed = parse_singleton_prompt(prompt)
406
407

        if parsed["type"] == "embeds":
408
409
410
411
            return self._process_embeds(parsed["content"])
        if parsed["type"] == "tokens":
            return self._process_tokens(
                parsed["content"],
412
                mm_uuids=mm_uuids,
413
            )
414
415
416
417
        if parsed["type"] == "text":
            return self._process_text(
                parsed["content"],
                tokenization_kwargs=tokenization_kwargs,
418
                mm_uuids=mm_uuids,
419
420
421
422
            )
        if parsed["type"] == "str":
            return self._process_text(
                TextPrompt(prompt=parsed["content"]),
423
                tokenization_kwargs=tokenization_kwargs,
424
                mm_uuids=mm_uuids,
425
            )
426

427
428
        assert_never(parsed)

429
430
    def _build_enc_dec_llm_inputs(
        self,
431
        encoder_inputs: SingletonInputs,
432
        decoder_inputs: SingletonInputs | None,
433
    ) -> EncoderDecoderInputs:
434
435
436
437
438
439
440
441
        if (
            encoder_inputs["type"] == "embeds"
            or decoder_inputs
            and decoder_inputs["type"] == "embeds"
        ):
            raise ValueError(
                "Embedding inputs are not supported for encoder-decoder models"
            )
442

443
        # Needed for mypy
444
445
        encoder_inputs = cast(TokenInputs | MultiModalInputs, encoder_inputs)
        decoder_inputs = cast(TokenInputs | MultiModalInputs | None, decoder_inputs)
446

447
        if decoder_inputs is None:
448
449
450
451
452
453
454
            if self.model_config.hf_config.model_type == "whisper":
                # For Whisper models, the text prompt should go to the decoder.
                # If no explicit encoder/decoder inputs, then copy the prompt
                # from the encoder to the decoder. The encoder tokens are later
                # overridden by the audio features.
                dec_token_ids = encoder_inputs["prompt_token_ids"].copy()
            else:
455
                dec_token_ids = self._prepare_decoder_input_ids_for_generation(None)
456
            decoder_inputs = token_inputs(dec_token_ids)
457
        else:
458
            if "multi_modal_data" in decoder_inputs:
459
460
461
462
                raise ValueError(
                    "Multi-modal decoder inputs of encoder-"
                    "decoder models are not supported yet"
                )
463
464

            dec_token_ids = self._prepare_decoder_input_ids_for_generation(
465
466
                decoder_inputs["prompt_token_ids"]
            )
467
            decoder_inputs["prompt_token_ids"] = dec_token_ids
468

469
        return EncoderDecoderInputs(
470
471
            encoder=encoder_inputs,
            decoder=decoder_inputs,
472
473
        )

474
    def _split_enc_dec_mm_inputs(
475
        self,
476
477
        inputs: SingletonInputs | MultiModalEncDecInputs,
        decoder_inputs_to_override: SingletonInputs | None = None,
478
    ) -> tuple[SingletonInputs, SingletonInputs]:
479
480
481
482
        """
        For encoder/decoder models only:
        Separate Encoder/Decoder inputs from a MultiModalEncDecInputs
        """
483
484
485
486
487
488
489
490
        if (
            inputs["type"] == "embeds"
            or decoder_inputs_to_override
            and decoder_inputs_to_override["type"] == "embeds"
        ):
            raise ValueError(
                "Embedding inputs are not supported for encoder-decoder models"
            )
491
492
493

        # Needed for mypy
        inputs = cast(
494
            TokenInputs | MultiModalInputs | MultiModalEncDecInputs,
495
496
497
            inputs,
        )
        decoder_inputs_to_override = cast(
498
            TokenInputs | MultiModalInputs | None,
499
500
501
            decoder_inputs_to_override,
        )

502
503
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
504
505

        if inputs["type"] == "multimodal":  # Multimodal data inputs
506
            if "encoder_prompt_token_ids" not in inputs:
507
508
509
510
511
                raise RuntimeError(
                    "You should register an encoder-decoder "
                    "multi-modal processor for encoder-decoder "
                    "models."
                )
512
            inputs = cast(MultiModalEncDecInputs, inputs)
513

514
            encoder_inputs = token_inputs(inputs["encoder_prompt_token_ids"])
515

516
517
518
519
520
521
522
523
524
            decoder_prompt_inputs = decoder_inputs_to_override or inputs
            decoder_inputs = MultiModalInputs(
                type="multimodal",
                prompt_token_ids=decoder_prompt_inputs["prompt_token_ids"],
                mm_kwargs=inputs["mm_kwargs"],
                mm_hashes=inputs["mm_hashes"],
                mm_placeholders=inputs["mm_placeholders"],
            )
            if cache_salt := inputs.get("cache_salt"):
525
526
                decoder_inputs["cache_salt"] = cache_salt

527
        elif inputs["type"] == "token":  # Text-only inputs
528
            encoder_inputs = token_inputs(prompt_token_ids=[])
529
530
531
            decoder_inputs = decoder_inputs_to_override or inputs
        else:
            assert_never(inputs)  # type: ignore[arg-type]
532

533
534
        return encoder_inputs, decoder_inputs

535
536
    def _process_encoder_decoder_prompt(
        self,
537
        prompt: PromptType,
538
        tokenization_kwargs: dict[str, Any] | None = None,
539
        *,
540
        mm_uuids: MultiModalUUIDDict | None = None,
541
    ) -> EncoderDecoderInputs:
542
        """
543
        For encoder/decoder models only:
544
545
546
        Process an input prompt into an
        [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
        instance.
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564

        There are two types of input prompts:
        singleton prompts which carry only the
        encoder prompt, and explicit encoder/decoder
        prompts which carry both the encoder and the
        decoder prompts as member variables.

        This function handles the following scenarios:
        * Singleton encoder prompt: extract encoder prompt
          token ids & infer default decoder prompt token ids
        * Explicit encoder/decoder prompt: extract encoder
          and decoder prompt token ids

        Note that for Explicit encoder/decoder prompts,
        each sub-prompt (encoder or decoder prompt) can
        have any possible singleton type; thus this
        method relies on helper functions to obtain
        token ids for the sub-prompts.
565

566
567
        Arguments:

568
        * prompt: an input prompt
569
570
571

        Returns:

572
573
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
574
        """
575
        encoder_inputs: SingletonInputs
576
        decoder_inputs: SingletonInputs | None
577
        if is_explicit_encoder_decoder_prompt(prompt):
578
579
            # `cast` is needed for mypy, but not pyright
            prompt_ = cast(ExplicitEncoderDecoderPrompt, prompt)
580
            encoder_inputs = self._prompt_to_llm_inputs(
581
                prompt_["encoder_prompt"],
582
                tokenization_kwargs=tokenization_kwargs,
583
                mm_uuids=mm_uuids,
584
            )
585
            if (decoder_input := prompt_["decoder_prompt"]) is None:
586
                decoder_inputs = None
587
            else:
588
589
590
                decoder_inputs = self._prompt_to_llm_inputs(
                    decoder_input, tokenization_kwargs=tokenization_kwargs
                )
591
592
            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
593
            if self.model_config.is_multimodal_model:
594
595
596
                encoder_inputs, decoder_inputs = self._split_enc_dec_mm_inputs(
                    encoder_inputs, decoder_inputs
                )
597
        else:
598
            # `cast` is needed for mypy, but not pyright
599
            inputs = self._prompt_to_llm_inputs(
600
                cast(SingletonPrompt, prompt),
601
                tokenization_kwargs=tokenization_kwargs,
602
                mm_uuids=mm_uuids,
603
            )
604
            if self.model_config.is_multimodal_model:
605
                # Encoder-Decoder Multimodal model
606
                encoder_inputs, decoder_inputs = self._split_enc_dec_mm_inputs(inputs)
607
608
609
            else:
                encoder_inputs = inputs
                decoder_inputs = None
610
611

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
612
613
614

    def _build_decoder_only_llm_inputs(
        self,
615
        prompt_inputs: DecoderOnlyInputs,
616
    ) -> DecoderOnlyInputs:
617
        if "prompt_token_ids" in prompt_inputs:
618
            prompt_inputs = cast(
619
                TokenInputs | MultiModalInputs, prompt_inputs
620
            )  # Needed for mypy
621

622
        return prompt_inputs
623
624
625

    def _process_decoder_only_prompt(
        self,
626
        prompt: SingletonPrompt,
627
        tokenization_kwargs: dict[str, Any] | None = None,
628
        *,
629
        mm_uuids: MultiModalUUIDDict | None = None,
630
    ) -> DecoderOnlyInputs:
631
        """
632
        For decoder-only models:
633
634
        Process an input prompt into a
        [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance.
635
636
637

        Arguments:

638
        * prompt: input prompt
639
640
641

        Returns:

642
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
643
        """
644

645
        prompt_comps = self._prompt_to_llm_inputs(
646
            prompt,
647
            tokenization_kwargs=tokenization_kwargs,
648
            mm_uuids=mm_uuids,
649
650
        )

651
        return self._build_decoder_only_llm_inputs(prompt_comps)
652

653
    def _preprocess(
654
        self,
655
        prompt: PromptType,
656
        tokenization_kwargs: dict[str, Any] | None = None,
657
        *,
658
        mm_uuids: MultiModalUUIDDict | None = None,
659
    ) -> ProcessorInputs:
660
        if self.model_config.is_encoder_decoder:
661
            # Encoder-decoder model requires special mapping of
662
            # input prompts to encoder & decoder.
663
            return self._process_encoder_decoder_prompt(
664
665
                prompt,
                tokenization_kwargs,
666
                mm_uuids=mm_uuids,
667
            )
668

669
        if is_explicit_encoder_decoder_prompt(prompt):
670
671
672
            raise ValueError(
                "Cannot pass encoder-decoder prompt to decoder-only models"
            )
673
674

        # Decoder-only operation
675
        # `cast` is needed for mypy, but not pyright
676
        return self._process_decoder_only_prompt(
677
            cast(SingletonPrompt, prompt),
678
            tokenization_kwargs=tokenization_kwargs,
679
            mm_uuids=mm_uuids,
680
681
        )

682
683
684
    def preprocess(
        self,
        prompt: PromptType,
685
        tokenization_kwargs: dict[str, Any] | None = None,
686
        *,
687
        mm_uuids: MultiModalUUIDDict | None = None,
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
    ) -> ProcessorInputs:
        """Preprocess the input prompt."""
        res = self._preprocess(
            prompt,
            tokenization_kwargs,
            mm_uuids=mm_uuids,
        )

        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

704
    def stat_mm_cache(self) -> MultiModalCacheStats | None:
705
706
707
708
709
710
711
712
713
        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:
714
715
        if self.mm_processor_cache is not None:
            self.mm_processor_cache.clear_cache()
716
717
718

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