preprocess.py 24 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
9
10

from typing_extensions import assert_never

from vllm.config import ModelConfig
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
48

logger = init_logger(__name__)


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

        self.model_config = model_config
56
        self.tokenizer = tokenizer
57
        self.mm_registry = mm_registry
58
        self.mm_processor_cache = mm_processor_cache
59

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

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

        return self.tokenizer

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

77
        return self.tokenizer.bos_token_id
78

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

86
        return self.tokenizer.eos_token_id
87

88
    def get_decoder_start_token_id(self) -> int | None:
89
        """
90
91
92
        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.
93
        """
94

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

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

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

        return dec_start_token_id

122
    def _get_default_enc_dec_decoder_prompt(self) -> list[int]:
123
        """
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
        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
144
        other models may have different or more
145
146
147
148
149
150
151
        complex logic for the default decoder prompt.
        This motivates having a special helper method
        for default decoder prompts.

        Returns:

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

        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,
160
        decoder_input_ids: list[int] | None,
161
    ) -> list[int]:
162
163
164
        """
        Prepares `decoder_input_ids` for generation with encoder-decoder models.

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

        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()

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

        return decoder_input_ids

195
196
    def _get_tokenization_kw(
        self,
197
        overrides: dict[str, Any] | None = None,
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    ) -> dict[str, Any]:
        kwargs = dict[str, Any]()

        if self.model_config.hf_config.model_type == "whisper":
            # 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

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

224
        encoder_config = self.model_config.encoder_config
225

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

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

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

        return self._mm_processor
240

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

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

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

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

        return mm_input
280

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

        prompt_embeds = parsed_content["prompt_embeds"]
291

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

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

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

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

        max_length = tokenization_kwargs["max_length"]

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

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

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

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

        return inputs

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

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

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

        return inputs
385

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

        Arguments:

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

        Returns:

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

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

426
427
        assert_never(parsed)

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

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

446
        if decoder_inputs is None:
447
448
449
450
451
452
453
            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:
454
                dec_token_ids = self._prepare_decoder_input_ids_for_generation(None)
455
            decoder_inputs = token_inputs(dec_token_ids)
456
        else:
457
            if "multi_modal_data" in decoder_inputs:
458
459
460
461
                raise ValueError(
                    "Multi-modal decoder inputs of encoder-"
                    "decoder models are not supported yet"
                )
462
463

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

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

473
    def _split_enc_dec_mm_inputs(
474
        self,
475
476
        inputs: SingletonInputs | MultiModalEncDecInputs,
        decoder_inputs_to_override: SingletonInputs | None = None,
477
    ) -> tuple[SingletonInputs, SingletonInputs]:
478
479
480
481
        """
        For encoder/decoder models only:
        Separate Encoder/Decoder inputs from a MultiModalEncDecInputs
        """
482
483
484
485
486
487
488
489
        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"
            )
490
491
492

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

501
502
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
503
504

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

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

515
516
517
518
519
520
521
522
523
            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"):
524
525
                decoder_inputs["cache_salt"] = cache_salt

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

532
533
        return encoder_inputs, decoder_inputs

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

        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.
564

565
566
        Arguments:

567
        * prompt: an input prompt
568
569
570

        Returns:

571
572
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
573
        """
574
        encoder_inputs: SingletonInputs
575
        decoder_inputs: SingletonInputs | None
576

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
                decoder_inputs = self._prompt_to_llm_inputs(decoder_input)
589
590
            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
591
            if self.model_config.is_multimodal_model:
592
593
594
                encoder_inputs, decoder_inputs = self._split_enc_dec_mm_inputs(
                    encoder_inputs, decoder_inputs
                )
595
        else:
596
            # `cast` is needed for mypy, but not pyright
597
            inputs = self._prompt_to_llm_inputs(
598
                cast(SingletonPrompt, prompt),
599
                tokenization_kwargs=tokenization_kwargs,
600
                mm_uuids=mm_uuids,
601
            )
602
            if self.model_config.is_multimodal_model:
603
                # Encoder-Decoder Multimodal model
604
                encoder_inputs, decoder_inputs = self._split_enc_dec_mm_inputs(inputs)
605
606
607
            else:
                encoder_inputs = inputs
                decoder_inputs = None
608
609

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
610
611
612

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

620
        return prompt_inputs
621
622
623

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

        Arguments:

636
        * prompt: input prompt
637
638
639

        Returns:

640
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
641
        """
642

643
        prompt_comps = self._prompt_to_llm_inputs(
644
            prompt,
645
            tokenization_kwargs=tokenization_kwargs,
646
            mm_uuids=mm_uuids,
647
648
        )

649
        return self._build_decoder_only_llm_inputs(prompt_comps)
650

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

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

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

680
681
682
    def preprocess(
        self,
        prompt: PromptType,
683
        tokenization_kwargs: dict[str, Any] | None = None,
684
        *,
685
        mm_uuids: MultiModalUUIDDict | None = None,
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
    ) -> 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

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

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