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, 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
14
15
16
17
18
from vllm.multimodal.inputs import (
    MultiModalDataDict,
    MultiModalEncDecInputs,
    MultiModalInputs,
    MultiModalUUIDDict,
)
19
from vllm.multimodal.processing import BaseMultiModalProcessor
20
from vllm.transformers_utils.tokenizer import AnyTokenizer
21

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

logger = init_logger(__name__)


class InputPreprocessor:
    def __init__(
        self,
        model_config: ModelConfig,
47
        tokenizer: Optional[AnyTokenizer],
48
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
49
        mm_processor_cache: Optional[BaseMultiModalProcessorCache] = None,
50
51
52
53
54
    ) -> None:
        super().__init__()

        self.model_config = model_config
        self.tokenizer = tokenizer
55
        self.mm_registry = mm_registry
56
        self.mm_processor_cache = mm_processor_cache
57

58
    def get_tokenizer(self) -> AnyTokenizer:
59
        if self.tokenizer is None:
60
61
62
            raise ValueError(
                "You cannot pass text prompts when `skip_tokenizer_init` is True"
            )
63
64
65

        return self.tokenizer

66
    def get_bos_token_id(self) -> Optional[int]:
67
        if self.tokenizer is None:
68
69
70
            logger.warning(
                "Using None for BOS token id because tokenizer is not initialized"
            )
71
72
            return None

73
        return self.tokenizer.bos_token_id
74

75
    def get_eos_token_id(self) -> Optional[int]:
76
        if self.tokenizer is None:
77
78
79
            logger.warning(
                "Using None for EOS token id because tokenizer is not initialized"
            )
80
81
            return None

82
        return self.tokenizer.eos_token_id
83
84

    def get_decoder_start_token_id(self) -> Optional[int]:
85
        """
86
87
88
        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.
89
        """
90

91
        if not self.model_config.is_encoder_decoder:
92
93
            logger.warning_once(
                "Using None for decoder start token id because "
94
95
                "this is not an encoder/decoder model."
            )
96
97
            return None

98
        if self.model_config is None or self.model_config.hf_config is None:
99
100
            logger.warning_once(
                "Using None for decoder start token id because "
101
102
                "model config is not available."
            )
103
104
            return None

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

        return dec_start_token_id

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

        Returns:

        * prompt_token_ids
148
        """
149
150
151
152
153
154
155

        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,
156
157
        decoder_input_ids: Optional[list[int]],
    ) -> list[int]:
158
159
160
        """
        Prepares `decoder_input_ids` for generation with encoder-decoder models.

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

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

183
184
185
186
        if (
            len(decoder_input_ids) == 0
            or decoder_input_ids[0] != decoder_start_token_id
        ):
187
188
189
190
            decoder_input_ids = [decoder_start_token_id] + decoder_input_ids

        return decoder_input_ids

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    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

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

220
        encoder_config = self.model_config.encoder_config
221

222
        if encoder_config and encoder_config.get("do_lower_case", False):
223
224
            prompt = prompt.lower()

225
        return tokenizer.encode(prompt, **tokenization_kwargs)
226

227
    def _get_mm_tokenizer(self) -> AnyTokenizer:
228
229
230
231
232
        # PrithviGeoSpatialMAE needs to be initialized without a tokenizer
        # while using also multi-modal input
        if not self.tokenizer:
            return cast(AnyTokenizer, object())  # Dummy

233
234
        tokenizer = self.get_tokenizer()
        return tokenizer
235

236
237
238
    def _get_mm_processor(self) -> BaseMultiModalProcessor:
        if not hasattr(self, "_mm_processor"):
            tokenizer = self._get_mm_tokenizer()
239

240
241
242
243
244
245
246
            self._mm_processor = self.mm_registry.create_processor(
                self.model_config,
                tokenizer=tokenizer,
                cache=self.mm_processor_cache,
            )

        return self._mm_processor
247

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

263
264
265
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

266
        mm_input = mm_processor.apply(
267
268
269
270
            prompt,
            mm_data,
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
271
            mm_uuids=mm_uuids,
272
        )
273
274
275
276
277
278
279
        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 "
280
281
                "MultiModalProcessor.apply method."
            )
282
283

        return mm_input
284

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

        prompt_embeds = parsed_content["prompt_embeds"]
295

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

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

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

315
    def _truncate_inputs(
316
317
318
319
320
321
322
        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
        ):
323
324
325
326
327
328
329
330
331
            return inputs

        max_length = tokenization_kwargs["max_length"]

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

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

        inputs: Union[TokenInputs, MultiModalInputs]
344
        if self.model_config.is_multimodal_model:
345
346
            inputs = self._process_multimodal(
                prompt_token_ids,
347
                parsed_content.get("multi_modal_data", {}),
348
                parsed_content.get("mm_processor_kwargs"),
349
                tokenization_kwargs=tokenization_kwargs,
350
                mm_uuids=mm_uuids,
351
            )
352
        else:
353
            if parsed_content.get("multi_modal_data"):
354
                raise ValueError("This model does not support multimodal inputs")
355

356
            inputs = token_inputs(prompt_token_ids)
357
358
359
360
361
362
363
364
365
366

        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,
367
        *,
368
        mm_uuids: Optional[MultiModalUUIDDict] = None,
369
370
371
372
    ) -> Union[TokenInputs, MultiModalInputs]:
        prompt_text = parsed_content["prompt"]

        inputs: Union[TokenInputs, MultiModalInputs]
373
        if self.model_config.is_multimodal_model:
374
375
            inputs = self._process_multimodal(
                prompt_text,
376
                parsed_content.get("multi_modal_data", {}),
377
                parsed_content.get("mm_processor_kwargs"),
378
                tokenization_kwargs=tokenization_kwargs,
379
                mm_uuids=mm_uuids,
380
381
            )
        else:
382
            if parsed_content.get("multi_modal_data"):
383
                raise ValueError("This model does not support multimodal inputs")
384

385
386
387
388
            prompt_token_ids = self._tokenize_prompt(
                prompt_text,
                tokenization_kwargs=tokenization_kwargs,
            )
389
            inputs = token_inputs(prompt_token_ids)
390
391
392
393
394

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

        return inputs
395

396
    def _prompt_to_llm_inputs(
397
        self,
398
        prompt: SingletonPrompt,
399
        tokenization_kwargs: Optional[dict[str, Any]] = None,
400
        *,
401
        mm_uuids: Optional[MultiModalUUIDDict] = None,
402
    ) -> SingletonInputs:
403
404
        """
        Extract the singleton inputs from a prompt.
405
406
407

        Arguments:

408
        * prompt: single encoder or decoder input prompt
409
410
411

        Returns:

412
        * [`SingletonInputs`][vllm.inputs.data.SingletonInputs] instance
413
        """
414
        parsed = parse_singleton_prompt(prompt)
415
416

        if parsed["type"] == "embeds":
417
418
419
420
            return self._process_embeds(parsed["content"])
        if parsed["type"] == "tokens":
            return self._process_tokens(
                parsed["content"],
421
                mm_uuids=mm_uuids,
422
            )
423
424
425
426
        if parsed["type"] == "text":
            return self._process_text(
                parsed["content"],
                tokenization_kwargs=tokenization_kwargs,
427
                mm_uuids=mm_uuids,
428
429
430
431
            )
        if parsed["type"] == "str":
            return self._process_text(
                TextPrompt(prompt=parsed["content"]),
432
                tokenization_kwargs=tokenization_kwargs,
433
                mm_uuids=mm_uuids,
434
            )
435

436
437
        assert_never(parsed)

438
439
    def _build_enc_dec_llm_inputs(
        self,
440
441
        encoder_inputs: SingletonInputs,
        decoder_inputs: Optional[SingletonInputs],
442
    ) -> EncoderDecoderInputs:
443
444
445
446
447
448
449
450
        if (
            encoder_inputs["type"] == "embeds"
            or decoder_inputs
            and decoder_inputs["type"] == "embeds"
        ):
            raise ValueError(
                "Embedding inputs are not supported for encoder-decoder models"
            )
451

452
        # Needed for mypy
453
454
455
456
        encoder_inputs = cast(Union[TokenInputs, MultiModalInputs], encoder_inputs)
        decoder_inputs = cast(
            Optional[Union[TokenInputs, MultiModalInputs]], decoder_inputs
        )
457

458
        if decoder_inputs is None:
459
460
461
462
463
464
465
            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:
466
                dec_token_ids = self._prepare_decoder_input_ids_for_generation(None)
467
            decoder_inputs = token_inputs(dec_token_ids)
468
        else:
469
            if "multi_modal_data" in decoder_inputs:
470
471
472
473
                raise ValueError(
                    "Multi-modal decoder inputs of encoder-"
                    "decoder models are not supported yet"
                )
474
475

            dec_token_ids = self._prepare_decoder_input_ids_for_generation(
476
477
                decoder_inputs["prompt_token_ids"]
            )
478
            decoder_inputs["prompt_token_ids"] = dec_token_ids
479

480
        return EncoderDecoderInputs(
481
482
            encoder=encoder_inputs,
            decoder=decoder_inputs,
483
484
        )

485
    def _split_enc_dec_mm_inputs(
486
        self,
487
488
        inputs: Union[SingletonInputs, MultiModalEncDecInputs],
        decoder_inputs_to_override: Optional[SingletonInputs] = None,
489
    ) -> tuple[SingletonInputs, SingletonInputs]:
490
491
492
493
        """
        For encoder/decoder models only:
        Separate Encoder/Decoder inputs from a MultiModalEncDecInputs
        """
494
495
496
497
498
499
500
501
        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"
            )
502
503
504
505
506
507
508
509
510
511
512

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

513
514
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
515
516

        if inputs["type"] == "multimodal":  # Multimodal data inputs
517
            if "encoder_prompt_token_ids" not in inputs:
518
519
520
521
522
                raise RuntimeError(
                    "You should register an encoder-decoder "
                    "multi-modal processor for encoder-decoder "
                    "models."
                )
523
            inputs = cast(MultiModalEncDecInputs, inputs)
524

525
            encoder_inputs = token_inputs(inputs["encoder_prompt_token_ids"])
526

527
528
529
530
531
532
533
534
535
            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"):
536
537
                decoder_inputs["cache_salt"] = cache_salt

538
        elif inputs["type"] == "token":  # Text-only inputs
539
            encoder_inputs = token_inputs(prompt_token_ids=[])
540
541
542
            decoder_inputs = decoder_inputs_to_override or inputs
        else:
            assert_never(inputs)  # type: ignore[arg-type]
543

544
545
        return encoder_inputs, decoder_inputs

546
547
    def _process_encoder_decoder_prompt(
        self,
548
        prompt: PromptType,
549
        tokenization_kwargs: Optional[dict[str, Any]] = None,
550
        *,
551
        mm_uuids: Optional[MultiModalUUIDDict] = None,
552
    ) -> EncoderDecoderInputs:
553
        """
554
        For encoder/decoder models only:
555
556
557
        Process an input prompt into an
        [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
        instance.
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575

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

577
578
        Arguments:

579
        * prompt: an input prompt
580
581
582

        Returns:

583
584
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
585
        """
586
587
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
588

589
        if is_explicit_encoder_decoder_prompt(prompt):
590
591
            # `cast` is needed for mypy, but not pyright
            prompt_ = cast(ExplicitEncoderDecoderPrompt, prompt)
592
            encoder_inputs = self._prompt_to_llm_inputs(
593
                prompt_["encoder_prompt"],
594
                tokenization_kwargs=tokenization_kwargs,
595
                mm_uuids=mm_uuids,
596
            )
597
            if (decoder_input := prompt_["decoder_prompt"]) is None:
598
                decoder_inputs = None
599
            else:
600
                decoder_inputs = self._prompt_to_llm_inputs(decoder_input)
601
602
            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
603
            if self.model_config.is_multimodal_model:
604
605
606
                encoder_inputs, decoder_inputs = self._split_enc_dec_mm_inputs(
                    encoder_inputs, decoder_inputs
                )
607
        else:
608
            # `cast` is needed for mypy, but not pyright
609
            inputs = self._prompt_to_llm_inputs(
610
                cast(SingletonPrompt, prompt),
611
                tokenization_kwargs=tokenization_kwargs,
612
                mm_uuids=mm_uuids,
613
            )
614
            if self.model_config.is_multimodal_model:
615
                # Encoder-Decoder Multimodal model
616
                encoder_inputs, decoder_inputs = self._split_enc_dec_mm_inputs(inputs)
617
618
619
            else:
                encoder_inputs = inputs
                decoder_inputs = None
620
621

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
622
623
624

    def _build_decoder_only_llm_inputs(
        self,
625
        prompt_inputs: DecoderOnlyInputs,
626
    ) -> DecoderOnlyInputs:
627
        if "prompt_token_ids" in prompt_inputs:
628
629
630
            prompt_inputs = cast(
                Union[TokenInputs, MultiModalInputs], prompt_inputs
            )  # Needed for mypy
631

632
        return prompt_inputs
633
634
635

    def _process_decoder_only_prompt(
        self,
636
        prompt: SingletonPrompt,
637
        tokenization_kwargs: Optional[dict[str, Any]] = None,
638
        *,
639
        mm_uuids: Optional[MultiModalUUIDDict] = None,
640
    ) -> DecoderOnlyInputs:
641
        """
642
        For decoder-only models:
643
644
        Process an input prompt into a
        [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance.
645
646
647

        Arguments:

648
        * prompt: input prompt
649
650
651

        Returns:

652
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
653
        """
654

655
        prompt_comps = self._prompt_to_llm_inputs(
656
            prompt,
657
            tokenization_kwargs=tokenization_kwargs,
658
            mm_uuids=mm_uuids,
659
660
        )

661
        return self._build_decoder_only_llm_inputs(prompt_comps)
662
663
664

    def preprocess(
        self,
665
        prompt: PromptType,
666
        tokenization_kwargs: Optional[dict[str, Any]] = None,
667
        *,
668
        mm_uuids: Optional[MultiModalUUIDDict] = None,
669
    ) -> ProcessorInputs:
670
        """Preprocess the input prompt."""
671
        if self.model_config.is_encoder_decoder:
672
            # Encoder-decoder model requires special mapping of
673
            # input prompts to encoder & decoder.
674
            return self._process_encoder_decoder_prompt(
675
676
                prompt,
                tokenization_kwargs,
677
                mm_uuids=mm_uuids,
678
            )
679

680
        if is_explicit_encoder_decoder_prompt(prompt):
681
682
683
            raise ValueError(
                "Cannot pass encoder-decoder prompt to decoder-only models"
            )
684
685

        # Decoder-only operation
686
        # `cast` is needed for mypy, but not pyright
687
        return self._process_decoder_only_prompt(
688
            cast(SingletonPrompt, prompt),
689
            tokenization_kwargs=tokenization_kwargs,
690
            mm_uuids=mm_uuids,
691
692
        )

693
694
695
    def clear_cache(self) -> None:
        if self.mm_processor_cache is not None:
            self.mm_processor_cache.clear_cache()
696
697
698
699
700
701
702
703
704
705
706
707


# 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