"docs/features/structured_outputs.md" did not exist on "e782e0a170a652c879593234c8723a7350c4784a"
preprocess.py 23.7 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, Optional, Union, 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
from vllm.multimodal.inputs import (MultiModalDataDict, MultiModalEncDecInputs,
14
                                    MultiModalInputs, MultiModalUUIDDict)
15
from vllm.multimodal.processing import BaseMultiModalProcessor
16
from vllm.transformers_utils.tokenizer import AnyTokenizer
17

18
19
20
21
22
from .data import (DecoderOnlyInputs, EmbedsInputs, EmbedsPrompt,
                   EncoderDecoderInputs, ProcessorInputs, PromptType,
                   SingletonInputs, SingletonPrompt, TextPrompt, TokenInputs,
                   TokensPrompt, embeds_inputs, token_inputs)
from .parse import is_explicit_encoder_decoder_prompt, parse_singleton_prompt
23
24
25
26
27
28
29
30
31

logger = init_logger(__name__)


class InputPreprocessor:

    def __init__(
        self,
        model_config: ModelConfig,
32
        tokenizer: Optional[AnyTokenizer],
33
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
34
        mm_processor_cache: Optional[BaseMultiModalProcessorCache] = None,
35
36
37
38
39
    ) -> None:
        super().__init__()

        self.model_config = model_config
        self.tokenizer = tokenizer
40
        self.mm_registry = mm_registry
41
        self.mm_processor_cache = mm_processor_cache
42

43
    def get_tokenizer(self) -> AnyTokenizer:
44
45
46
47
48
49
        if self.tokenizer is None:
            raise ValueError("You cannot pass text prompts when "
                             "`skip_tokenizer_init` is True")

        return self.tokenizer

50
    def get_bos_token_id(self) -> Optional[int]:
51
52
53
54
55
        if self.tokenizer is None:
            logger.warning("Using None for BOS token id because tokenizer "
                           "is not initialized")
            return None

56
        return self.tokenizer.bos_token_id
57

58
    def get_eos_token_id(self) -> Optional[int]:
59
60
61
62
63
        if self.tokenizer is None:
            logger.warning("Using None for EOS token id because tokenizer "
                           "is not initialized")
            return None

64
        return self.tokenizer.eos_token_id
65
66

    def get_decoder_start_token_id(self) -> Optional[int]:
67
        """
68
69
70
        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.
71
        """
72

73
        if not self.model_config.is_encoder_decoder:
74
75
76
            logger.warning_once(
                "Using None for decoder start token id because "
                "this is not an encoder/decoder model.")
77
78
            return None

79
        if self.model_config is None or self.model_config.hf_config is None:
80
81
82
            logger.warning_once(
                "Using None for decoder start token id because "
                "model config is not available.")
83
84
85
            return None

        dec_start_token_id = getattr(self.model_config.hf_config,
86
                                     "decoder_start_token_id", None)
87
        if dec_start_token_id is None:
88
89
90
91
            logger.warning_once(
                "Falling back on <BOS> for decoder start token "
                "id because decoder start token id is not "
                "available.")
92
93
94
95
            dec_start_token_id = self.get_bos_token_id()

        return dec_start_token_id

96
    def _get_default_enc_dec_decoder_prompt(self) -> list[int]:
97
        """
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
        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
118
        other models may have different or more
119
120
121
122
123
124
125
        complex logic for the default decoder prompt.
        This motivates having a special helper method
        for default decoder prompts.

        Returns:

        * prompt_token_ids
126
        """
127
128
129
130
131
132
133

        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,
134
135
        decoder_input_ids: Optional[list[int]],
    ) -> list[int]:
136
137
138
        """
        Prepares `decoder_input_ids` for generation with encoder-decoder models.

139
140
141
142
        Based on:
        https://github.com/huggingface/transformers/blob/4037a2b5b1278736e566aec12e169100275545ea/src/transformers/generation/utils.py
        specifically,
        `GenerationMixin._prepare_decoder_input_ids_for_generation()`.
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160

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

161
162
        if (len(decoder_input_ids) == 0
                or decoder_input_ids[0] != decoder_start_token_id):
163
164
165
166
            decoder_input_ids = [decoder_start_token_id] + decoder_input_ids

        return decoder_input_ids

167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
    def _get_tokenization_kw(
        self,
        overrides: Optional[dict[str, Any]] = None,
    ) -> 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

184
185
186
    def _tokenize_prompt(
        self,
        prompt: str,
187
        tokenization_kwargs: Optional[dict[str, Any]] = None,
188
    ) -> list[int]:
189
190
191
192
        """
        Apply the model's tokenizer to a text prompt, returning the
        corresponding token IDs.
        """
193
        tokenizer = self.get_tokenizer()
194
        tokenization_kwargs = self._get_tokenization_kw(tokenization_kwargs)
195

196
        encoder_config = self.model_config.encoder_config
197

198
        if encoder_config and encoder_config.get("do_lower_case", False):
199
200
            prompt = prompt.lower()

201
        return tokenizer.encode(prompt, **tokenization_kwargs)
202

203
    def _get_mm_tokenizer(self) -> AnyTokenizer:
204
205
206
207
208
        # PrithviGeoSpatialMAE needs to be initialized without a tokenizer
        # while using also multi-modal input
        if not self.tokenizer:
            return cast(AnyTokenizer, object())  # Dummy

209
210
        tokenizer = self.get_tokenizer()
        return tokenizer
211

212
213
214
    def _get_mm_processor(self) -> BaseMultiModalProcessor:
        if not hasattr(self, "_mm_processor"):
            tokenizer = self._get_mm_tokenizer()
215

216
217
218
219
220
221
222
            self._mm_processor = self.mm_registry.create_processor(
                self.model_config,
                tokenizer=tokenizer,
                cache=self.mm_processor_cache,
            )

        return self._mm_processor
223

224
225
    def _process_multimodal(
        self,
226
        prompt: Union[str, list[int]],
227
228
        mm_data: MultiModalDataDict,
        mm_processor_kwargs: Optional[Mapping[str, object]],
229
        tokenization_kwargs: Optional[dict[str, Any]] = None,
230
        *,
231
        mm_uuids: Optional[MultiModalUUIDDict] = None,
232
    ) -> MultiModalInputs:
233
234
235
236
        """
        Apply the model's multi-modal processor to a multi-modal prompt,
        returning the corresponding token IDs and metadata.
        """
237
        mm_processor = self._get_mm_processor()
238

239
240
241
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

242
        mm_input = mm_processor.apply(
243
244
245
246
            prompt,
            mm_data,
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
247
            mm_uuids=mm_uuids,
248
        )
249
250
251
252
253
254
255
256
257
258
        mm_hashes = mm_input["mm_hashes"]

        # Validate that all mm items have a string as their hash
        if not contains_only_strings(mm_hashes):
            raise ValueError(
                f"mm_hashes must contain only strings, got: {mm_hashes}. "
                "This is likely due to an incorrect custom implementation of "
                "MultiModalProcessor.apply method.")

        return mm_input
259

260
261
262
263
    def _process_embeds(
        self,
        parsed_content: EmbedsPrompt,
    ) -> EmbedsInputs:
264
265
266
        if not self.model_config.enable_prompt_embeds:
            raise ValueError("You must set `--enable-prompt-embeds` to input "
                             "`prompt_embeds`.")
267
268

        prompt_embeds = parsed_content["prompt_embeds"]
269

270
271
272
273
274
275
276
277
278
279
280
        # 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:
            raise ValueError(
                "prompt_embeds must be of shape (seq_len, hidden_size).")

281
282
283
284
285
        # 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()

286
287
288
        return embeds_inputs(prompt_embeds=prompt_embeds,
                             cache_salt=parsed_content.get("cache_salt"))

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
    def _truncate_inputs(
            self,
            inputs: list[int],
            tokenization_kwargs: Optional[dict[str, Any]] = None) -> list[int]:

        if not tokenization_kwargs or "truncation" not in \
                tokenization_kwargs or self.tokenizer is None:
            return inputs

        max_length = tokenization_kwargs["max_length"]

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

305
306
307
    def _process_tokens(
        self,
        parsed_content: TokensPrompt,
308
        tokenization_kwargs: Optional[dict[str, Any]] = None,
309
        *,
310
        mm_uuids: Optional[MultiModalUUIDDict] = None,
311
    ) -> Union[TokenInputs, MultiModalInputs]:
312
313
        prompt_token_ids = self._truncate_inputs(
            parsed_content["prompt_token_ids"], tokenization_kwargs)
314
315
316
317
318
319
320

        inputs: Union[TokenInputs, MultiModalInputs]
        if multi_modal_data := parsed_content.get("multi_modal_data"):
            inputs = self._process_multimodal(
                prompt_token_ids,
                multi_modal_data,
                parsed_content.get("mm_processor_kwargs"),
321
                tokenization_kwargs=tokenization_kwargs,
322
                mm_uuids=mm_uuids,
323
            )
324
        else:
325
            inputs = token_inputs(prompt_token_ids=prompt_token_ids)
326
327
328
329
330
331
332
333
334
335

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

        return inputs

    def _process_text(
        self,
        parsed_content: TextPrompt,
        tokenization_kwargs: Optional[dict[str, Any]] = None,
336
        *,
337
        mm_uuids: Optional[MultiModalUUIDDict] = None,
338
339
340
341
342
343
344
345
346
    ) -> Union[TokenInputs, MultiModalInputs]:
        prompt_text = parsed_content["prompt"]

        inputs: Union[TokenInputs, MultiModalInputs]
        if multi_modal_data := parsed_content.get("multi_modal_data"):
            inputs = self._process_multimodal(
                prompt_text,
                multi_modal_data,
                parsed_content.get("mm_processor_kwargs"),
347
                tokenization_kwargs=tokenization_kwargs,
348
                mm_uuids=mm_uuids,
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            )
        else:
            prompt_token_ids = self._tokenize_prompt(
                prompt_text,
                tokenization_kwargs=tokenization_kwargs,
            )
            inputs = token_inputs(
                prompt=prompt_text,
                prompt_token_ids=prompt_token_ids,
            )

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

        return inputs
364

365
    def _prompt_to_llm_inputs(
366
        self,
367
        prompt: SingletonPrompt,
368
        tokenization_kwargs: Optional[dict[str, Any]] = None,
369
        *,
370
        mm_uuids: Optional[MultiModalUUIDDict] = None,
371
    ) -> SingletonInputs:
372
373
        """
        Extract the singleton inputs from a prompt.
374
375
376

        Arguments:

377
        * prompt: single encoder or decoder input prompt
378
379
380

        Returns:

381
        * [`SingletonInputs`][vllm.inputs.data.SingletonInputs] instance
382
        """
383
        parsed = parse_singleton_prompt(prompt)
384
385

        if parsed["type"] == "embeds":
386
387
388
389
            return self._process_embeds(parsed["content"])
        if parsed["type"] == "tokens":
            return self._process_tokens(
                parsed["content"],
390
                mm_uuids=mm_uuids,
391
            )
392
393
394
395
        if parsed["type"] == "text":
            return self._process_text(
                parsed["content"],
                tokenization_kwargs=tokenization_kwargs,
396
                mm_uuids=mm_uuids,
397
398
399
400
            )
        if parsed["type"] == "str":
            return self._process_text(
                TextPrompt(prompt=parsed["content"]),
401
                tokenization_kwargs=tokenization_kwargs,
402
                mm_uuids=mm_uuids,
403
            )
404

405
406
        assert_never(parsed)

407
408
    def _build_enc_dec_llm_inputs(
        self,
409
410
        encoder_inputs: SingletonInputs,
        decoder_inputs: Optional[SingletonInputs],
411
    ) -> EncoderDecoderInputs:
412
413
414
415
        if (encoder_inputs["type"] == "embeds"
                or decoder_inputs and decoder_inputs["type"] == "embeds"):
            raise ValueError("Embedding inputs are not supported for encoder-"
                             "decoder models")
416

417
418
419
420
421
        # Needed for mypy
        encoder_inputs = cast(Union[TokenInputs, MultiModalInputs],
                              encoder_inputs)
        decoder_inputs = cast(Optional[Union[TokenInputs, MultiModalInputs]],
                              decoder_inputs)
422

423
        if decoder_inputs is None:
424
425
426
427
428
429
430
431
432
            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:
                dec_token_ids = self._prepare_decoder_input_ids_for_generation(
                    None)
433
            decoder_inputs = token_inputs(dec_token_ids)
434
        else:
435
436
437
            if "multi_modal_data" in decoder_inputs:
                raise ValueError("Multi-modal decoder inputs of encoder-"
                                 "decoder models are not supported yet")
438
439
440
441

            dec_token_ids = self._prepare_decoder_input_ids_for_generation(
                decoder_inputs["prompt_token_ids"])
            decoder_inputs["prompt_token_ids"] = dec_token_ids
442

443
        return EncoderDecoderInputs(
444
445
            encoder=encoder_inputs,
            decoder=decoder_inputs,
446
447
        )

448
    def _split_enc_dec_mm_inputs(
449
        self,
450
451
        inputs: Union[SingletonInputs, MultiModalEncDecInputs],
        decoder_inputs_to_override: Optional[SingletonInputs] = None,
452
    ) -> tuple[SingletonInputs, SingletonInputs]:
453
454
455
456
        """
        For encoder/decoder models only:
        Separate Encoder/Decoder inputs from a MultiModalEncDecInputs
        """
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
        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")

        # Needed for mypy
        inputs = cast(
            Union[TokenInputs, MultiModalInputs, MultiModalEncDecInputs],
            inputs,
        )
        decoder_inputs_to_override = cast(
            Optional[Union[TokenInputs, MultiModalInputs]],
            decoder_inputs_to_override,
        )

472
473
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
474
475
476
477
478
479
480

        if inputs["type"] == "multimodal":  # Multimodal data inputs
            if not ("encoder_prompt" in inputs
                    and "encoder_prompt_token_ids" in inputs):
                raise RuntimeError("You should register an encoder-decoder "
                                   "multi-modal processor for encoder-decoder "
                                   "models.")
481
            inputs = cast(MultiModalEncDecInputs, inputs)
482

483
484
485
486
            encoder_inputs = token_inputs(
                prompt=inputs["encoder_prompt"],
                prompt_token_ids=inputs["encoder_prompt_token_ids"],
            )
487

488
489
490
491
492
493
494
495
496
497
            decoder_prompt_inputs = decoder_inputs_to_override or inputs
            decoder_inputs = MultiModalInputs(
                type="multimodal",
                prompt=decoder_prompt_inputs.get("prompt", ""),
                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"):
498
499
                decoder_inputs["cache_salt"] = cache_salt

500
        elif inputs["type"] == "token":  # Text-only inputs
501
502
503
504
            encoder_inputs = token_inputs(prompt="", prompt_token_ids=[])
            decoder_inputs = decoder_inputs_to_override or inputs
        else:
            assert_never(inputs)  # type: ignore[arg-type]
505

506
507
        return encoder_inputs, decoder_inputs

508
509
    def _process_encoder_decoder_prompt(
        self,
510
        prompt: PromptType,
511
        tokenization_kwargs: Optional[dict[str, Any]] = None,
512
        *,
513
        mm_uuids: Optional[MultiModalUUIDDict] = None,
514
    ) -> EncoderDecoderInputs:
515
        """
516
        For encoder/decoder models only:
517
518
519
        Process an input prompt into an
        [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
        instance.
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537

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

539
540
        Arguments:

541
        * prompt: an input prompt
542
543
544

        Returns:

545
546
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
547
        """
548
549
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
550

551
        if is_explicit_encoder_decoder_prompt(prompt):
552
            encoder_inputs = self._prompt_to_llm_inputs(
553
554
                prompt["encoder_prompt"],
                tokenization_kwargs=tokenization_kwargs,
555
                mm_uuids=mm_uuids,
556
            )
557
            if (decoder_input := prompt["decoder_prompt"]) is None:
558
                decoder_inputs = None
559
            else:
560
                decoder_inputs = self._prompt_to_llm_inputs(decoder_input)
561
562
            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
563
            if self.model_config.is_multimodal_model:
564
                encoder_inputs, decoder_inputs = (
565
566
                    self._split_enc_dec_mm_inputs(encoder_inputs,
                                                  decoder_inputs))
567
        else:
568
569
570
            inputs = self._prompt_to_llm_inputs(
                prompt,
                tokenization_kwargs=tokenization_kwargs,
571
                mm_uuids=mm_uuids,
572
            )
573
            if self.model_config.is_multimodal_model:
574
575
                # Encoder-Decoder Multimodal model
                encoder_inputs, decoder_inputs = (
576
                    self._split_enc_dec_mm_inputs(inputs))
577
578
579
            else:
                encoder_inputs = inputs
                decoder_inputs = None
580
581

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
582
583
584

    def _build_decoder_only_llm_inputs(
        self,
585
        prompt_inputs: DecoderOnlyInputs,
586
    ) -> DecoderOnlyInputs:
587
588
589
        if "prompt_token_ids" in prompt_inputs:
            prompt_inputs = cast(Union[TokenInputs, MultiModalInputs],
                                 prompt_inputs)  # Needed for mypy
590

591
        return prompt_inputs
592
593
594

    def _process_decoder_only_prompt(
        self,
595
        prompt: SingletonPrompt,
596
        tokenization_kwargs: Optional[dict[str, Any]] = None,
597
        *,
598
        mm_uuids: Optional[MultiModalUUIDDict] = None,
599
    ) -> DecoderOnlyInputs:
600
        """
601
        For decoder-only models:
602
603
        Process an input prompt into a
        [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance.
604
605
606

        Arguments:

607
        * prompt: input prompt
608
609
610

        Returns:

611
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
612
        """
613

614
        prompt_comps = self._prompt_to_llm_inputs(
615
            prompt,
616
            tokenization_kwargs=tokenization_kwargs,
617
            mm_uuids=mm_uuids,
618
619
        )

620
        return self._build_decoder_only_llm_inputs(prompt_comps)
621
622
623

    def preprocess(
        self,
624
        prompt: PromptType,
625
        tokenization_kwargs: Optional[dict[str, Any]] = None,
626
        *,
627
        mm_uuids: Optional[MultiModalUUIDDict] = None,
628
    ) -> ProcessorInputs:
629
        """Preprocess the input prompt."""
630
        if self.model_config.is_encoder_decoder:
631
            # Encoder-decoder model requires special mapping of
632
            # input prompts to encoder & decoder.
633
            return self._process_encoder_decoder_prompt(
634
635
                prompt,
                tokenization_kwargs,
636
                mm_uuids=mm_uuids,
637
            )
638

639
        if is_explicit_encoder_decoder_prompt(prompt):
640
641
642
643
644
            raise ValueError("Cannot pass encoder-decoder prompt "
                             "to decoder-only models")

        # Decoder-only operation
        return self._process_decoder_only_prompt(
645
            prompt,
646
            tokenization_kwargs=tokenization_kwargs,
647
            mm_uuids=mm_uuids,
648
649
        )

650
651
652
    def clear_cache(self) -> None:
        if self.mm_processor_cache is not None:
            self.mm_processor_cache.clear_cache()
653
654
655
656
657
658
659
660
661
662
663
664


# Helper function to validate that a nested dictionary contains
# only strings or list of strings as the leaf values.
def contains_only_strings(obj: object):
    if isinstance(obj, str):
        return True
    if isinstance(obj, list):
        return all(isinstance(x, str) for x in obj)
    if isinstance(obj, dict):
        return all(contains_only_strings(v) for v in obj.values())
    return False