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

4
from collections.abc import Mapping
5
from typing import Any, 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
from .data import (DecoderOnlyInputs, EmbedsInputs, EmbedsPrompt,
                   EncoderDecoderInputs, ProcessorInputs, PromptType,
                   SingletonInputs, SingletonPrompt, TextPrompt, TokenInputs,
                   TokensPrompt, embeds_inputs, token_inputs)
22
23
24
25
26
27
28
29
30
31
from .parse import is_explicit_encoder_decoder_prompt, parse_singleton_prompt

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
202
203
        if self.model_config.tokenizer_mode == "cpm":
                return [tokenizer.bos_id] + tokenizer.encode(prompt)
        else:
204
            return tokenizer.encode(prompt, **tokenization_kwargs)
205

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

212
213
        tokenizer = self.get_tokenizer()
        return tokenizer
214

215
216
217
    def _get_mm_processor(self) -> BaseMultiModalProcessor:
        if not hasattr(self, "_mm_processor"):
            tokenizer = self._get_mm_tokenizer()
218

219
220
221
222
223
            self._mm_processor = self.mm_registry.create_processor(
                self.model_config,
                tokenizer=tokenizer,
                cache=self.mm_processor_cache,
            )
224

225
        return self._mm_processor
226

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

242
243
244
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

245
        mm_input = mm_processor.apply(
246
247
248
249
            prompt,
            mm_data,
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
250
            mm_uuids=mm_uuids,
251
        )
252
253
254
255
256
257
258
259
260
261
        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
262

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

271
        prompt_embeds = parsed_content["prompt_embeds"]
272

273
274
275
276
277
278
        # 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)
279

280
281
282
        if prompt_embeds.ndim != 2:
            raise ValueError(
                "prompt_embeds must be of shape (seq_len, hidden_size).")
283

284
285
286
287
288
        # 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()

289
290
        return embeds_inputs(prompt_embeds=prompt_embeds,
                             cache_salt=parsed_content.get("cache_salt"))
291

292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    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]

308
309
310
    def _process_tokens(
        self,
        parsed_content: TokensPrompt,
311
        tokenization_kwargs: Optional[dict[str, Any]] = None,
312
        *,
313
        mm_uuids: Optional[MultiModalUUIDDict] = None,
314
    ) -> Union[TokenInputs, MultiModalInputs]:
315
316
        prompt_token_ids = self._truncate_inputs(
            parsed_content["prompt_token_ids"], tokenization_kwargs)
317
318
319
320
321
322
        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"),
323
                tokenization_kwargs=tokenization_kwargs,
324
                mm_uuids=mm_uuids,
325
            )
326
        else:
luopl's avatar
luopl committed
327
328
            inputs = token_inputs(prompt_token_ids=prompt_token_ids,
                                  qfeat=parsed_content["qfeat"])
329

330
331
332
333
        if cache_salt := parsed_content.get("cache_salt"):
            inputs["cache_salt"] = cache_salt

        return inputs
334

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

344
345
346
347
348
349
        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"),
350
                tokenization_kwargs=tokenization_kwargs,
351
                mm_uuids=mm_uuids,
352
353
            )
        else:
354
            prompt_token_ids = self._tokenize_prompt(
355
                prompt_text,
356
                tokenization_kwargs=tokenization_kwargs,
357
            )
358
            inputs = token_inputs(
359
360
                prompt=prompt_text,
                prompt_token_ids=prompt_token_ids,
luopl's avatar
luopl committed
361
                qfeat=parsed_content["qfeat"]
362
363
            )

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

367
        return inputs
368
369

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

379
380
        Arguments:

381
        * prompt: single encoder or decoder input prompt
382
383
384

        Returns:

385
        * [`SingletonInputs`][vllm.inputs.data.SingletonInputs] instance
386
        """
387
        parsed = parse_singleton_prompt(prompt)
388
389

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

409
        assert_never(parsed)
410
411
412

    def _build_enc_dec_llm_inputs(
        self,
413
414
        encoder_inputs: SingletonInputs,
        decoder_inputs: Optional[SingletonInputs],
415
    ) -> EncoderDecoderInputs:
416
417
418
419
        if (encoder_inputs["type"] == "embeds"
                or decoder_inputs and decoder_inputs["type"] == "embeds"):
            raise ValueError("Embedding inputs are not supported for encoder-"
                             "decoder models")
420

421
422
423
424
425
        # Needed for mypy
        encoder_inputs = cast(Union[TokenInputs, MultiModalInputs],
                              encoder_inputs)
        decoder_inputs = cast(Optional[Union[TokenInputs, MultiModalInputs]],
                              decoder_inputs)
426
427

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

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

447
        return EncoderDecoderInputs(
448
449
            encoder=encoder_inputs,
            decoder=decoder_inputs,
450
451
        )

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

476
477
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
478
479
480
481
482
483
484

        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.")
485
            inputs = cast(MultiModalEncDecInputs, inputs)
486

487
488
489
490
            encoder_inputs = token_inputs(
                prompt=inputs["encoder_prompt"],
                prompt_token_ids=inputs["encoder_prompt_token_ids"],
            )
491

492
493
494
495
496
497
498
499
500
501
            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"):
502
503
                decoder_inputs["cache_salt"] = cache_salt

504
        elif inputs["type"] == "token":  # Text-only inputs
505
506
507
508
            encoder_inputs = token_inputs(prompt="", prompt_token_ids=[])
            decoder_inputs = decoder_inputs_to_override or inputs
        else:
            assert_never(inputs)  # type: ignore[arg-type]
509

510
511
        return encoder_inputs, decoder_inputs

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

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

543
544
        Arguments:

545
        * prompt: an input prompt
546
547
548

        Returns:

549
550
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
551
        """
552
553
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
554

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

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
586
587
588

    def _build_decoder_only_llm_inputs(
        self,
589
        prompt_inputs: DecoderOnlyInputs,
590
    ) -> DecoderOnlyInputs:
591
592
593
        if "prompt_token_ids" in prompt_inputs:
            prompt_inputs = cast(Union[TokenInputs, MultiModalInputs],
                                 prompt_inputs)  # Needed for mypy
594

595
        return prompt_inputs
596
597
598

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

        Arguments:

611
        * prompt: input prompt
612
613
614

        Returns:

615
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
616
        """
617

618
        prompt_comps = self._prompt_to_llm_inputs(
619
            prompt,
620
            tokenization_kwargs=tokenization_kwargs,
621
            mm_uuids=mm_uuids,
622
623
        )

624
        return self._build_decoder_only_llm_inputs(prompt_comps)
625
626
627

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

643
        if is_explicit_encoder_decoder_prompt(prompt):
644
645
646
647
648
            raise ValueError("Cannot pass encoder-decoder prompt "
                             "to decoder-only models")

        # Decoder-only operation
        return self._process_decoder_only_prompt(
649
            prompt,
650
            tokenization_kwargs=tokenization_kwargs,
651
            mm_uuids=mm_uuids,
652
        )
653
654
655
656

    def clear_cache(self) -> None:
        if self.mm_processor_cache is not None:
            self.mm_processor_cache.clear_cache()
657
658
659
660
661
662
663
664
665
666
667
668


# 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