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 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
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
        model_config: ModelConfig,
49
        tokenizer: TokenizerLike | None,
50
        observability_config: ObservabilityConfig | None = None,
51
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
52
        mm_processor_cache: BaseMultiModalProcessorCache | None = None,
53
54
55
    ) -> None:
        super().__init__()

56
        self.model_config = model_config
57
        self.tokenizer = tokenizer
58
        self.observability_config = observability_config
59
        self.mm_registry = mm_registry
60
        self.mm_processor_cache = mm_processor_cache
61

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

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

        return self.tokenizer

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

79
        return self.tokenizer.bos_token_id
80

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

88
        return self.tokenizer.eos_token_id
89

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

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

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

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

        return dec_start_token_id

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

        Returns:

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

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

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

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

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

        return decoder_input_ids

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

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

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

226
        encoder_config = self.model_config.encoder_config
227

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

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

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

        return self._mm_processor
243

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

259
260
261
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

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

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

        return mm_input
283

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

        prompt_embeds = parsed_content["prompt_embeds"]
294

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

305
306
307
308
309
        # 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()

310
311
312
        return embeds_inputs(
            prompt_embeds=prompt_embeds, cache_salt=parsed_content.get("cache_salt")
        )
313

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

        max_length = tokenization_kwargs["max_length"]

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

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

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

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

        return inputs

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

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

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

        return inputs
388

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

        Arguments:

401
        * prompt: single encoder or decoder input prompt
402
403
404

        Returns:

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

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

429
430
        assert_never(parsed)

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

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

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

            dec_token_ids = self._prepare_decoder_input_ids_for_generation(
467
468
                decoder_inputs["prompt_token_ids"]
            )
469
            decoder_inputs["prompt_token_ids"] = dec_token_ids
470

471
        return EncoderDecoderInputs(
472
473
            encoder=encoder_inputs,
            decoder=decoder_inputs,
474
475
        )

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

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

504
505
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
506
507

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

516
            encoder_inputs = token_inputs(inputs["encoder_prompt_token_ids"])
517

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

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

535
536
        return encoder_inputs, decoder_inputs

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

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

568
569
        Arguments:

570
        * prompt: an input prompt
571
572
573

        Returns:

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

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
614
615
616

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

624
        return prompt_inputs
625
626
627

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

        Arguments:

640
        * prompt: input prompt
641
642
643

        Returns:

644
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
645
        """
646

647
        prompt_comps = self._prompt_to_llm_inputs(
648
            prompt,
649
            tokenization_kwargs=tokenization_kwargs,
650
            mm_uuids=mm_uuids,
651
652
        )

653
        return self._build_decoder_only_llm_inputs(prompt_comps)
654

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

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

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

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

        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