"vscode:/vscode.git/clone" did not exist on "25e16eea999e9dab048b93ff8b25a3ffbc52ce63"
preprocess.py 32.8 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import asyncio
5
from collections.abc import Mapping
6
from typing import Any, Optional, Union, cast
7
8
9
10
11

from typing_extensions import assert_never

from vllm.config import ModelConfig
from vllm.logger import init_logger
12
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
13
from vllm.multimodal.cache import BaseMultiModalProcessorCache
14
from vllm.multimodal.inputs import (MultiModalDataDict, MultiModalEncDecInputs,
15
                                    MultiModalInputs, MultiModalUUIDDict)
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
204
205

    async def _tokenize_prompt_async(
        self,
        prompt: str,
206
        tokenization_kwargs: Optional[dict[str, Any]] = None,
207
    ) -> list[int]:
208
209
210
211
        """
        Async version of
        [`_tokenize_prompt`][vllm.inputs.preprocess.InputPreprocessor._tokenize_prompt].
        """
212
        tokenizer = self.get_tokenizer()
213
        tokenization_kwargs = self._get_tokenization_kw(tokenization_kwargs)
214

215
        return tokenizer.encode(prompt, **tokenization_kwargs)
216

217
    def _get_mm_tokenizer(self) -> AnyTokenizer:
218
219
220
221
222
        # PrithviGeoSpatialMAE needs to be initialized without a tokenizer
        # while using also multi-modal input
        if not self.tokenizer:
            return cast(AnyTokenizer, object())  # Dummy

223
224
        tokenizer = self.get_tokenizer()
        return tokenizer
225

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

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

235
236
    def _process_multimodal(
        self,
237
        prompt: Union[str, list[int]],
238
239
        mm_data: MultiModalDataDict,
        mm_processor_kwargs: Optional[Mapping[str, object]],
240
        tokenization_kwargs: Optional[dict[str, Any]] = None,
241
        *,
242
        mm_uuids: Optional[MultiModalUUIDDict] = None,
243
    ) -> MultiModalInputs:
244
245
246
247
        """
        Apply the model's multi-modal processor to a multi-modal prompt,
        returning the corresponding token IDs and metadata.
        """
248
        tokenizer = self._get_mm_tokenizer()
249

250
251
252
253
254
        mm_processor = self.mm_registry.create_processor(
            self.model_config,
            tokenizer=tokenizer,
            cache=self.mm_processor_cache,
        )
255
256
257
258

        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

259
        mm_input = mm_processor.apply(
260
261
262
263
            prompt,
            mm_data,
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
264
            mm_uuids=mm_uuids,
265
        )
266
267
268
269
270
271
272
273
274
275
        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
276
277
278

    async def _process_multimodal_async(
        self,
279
        prompt: Union[str, list[int]],
280
281
        mm_data: MultiModalDataDict,
        mm_processor_kwargs: Optional[Mapping[str, object]],
282
        tokenization_kwargs: Optional[dict[str, Any]] = None,
283
        *,
284
        mm_uuids: Optional[MultiModalUUIDDict] = None,
285
    ) -> MultiModalInputs:
286
287
288
289
        """
        Async version of
        [`_process_multimodal`][vllm.inputs.preprocess.InputPreprocessor._process_multimodal].
        """
290
        tokenizer = await self._get_mm_tokenizer_async()
291

292
293
294
295
296
297
        mm_processor = self.mm_registry.create_processor(
            self.model_config,
            tokenizer=tokenizer,
            cache=self.mm_processor_cache,
        )

298
299
300
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

301
        mm_input = mm_processor.apply(
302
303
304
305
            prompt,
            mm_data,
            hf_processor_mm_kwargs=mm_processor_kwargs,
            tokenization_kwargs=tokenization_kwargs,
306
            mm_uuids=mm_uuids,
307
        )
308
309
310
311
312
313
314
315
316
317
        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
318

319
320
321
322
    def _process_embeds(
        self,
        parsed_content: EmbedsPrompt,
    ) -> EmbedsInputs:
323
324
325
        if not self.model_config.enable_prompt_embeds:
            raise ValueError("You must set `--enable-prompt-embeds` to input "
                             "`prompt_embeds`.")
326
327

        prompt_embeds = parsed_content["prompt_embeds"]
328

329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
        # 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).")

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

    async def _process_embeds_async(
        self,
        parsed_content: EmbedsPrompt,
    ) -> EmbedsInputs:
        return self._process_embeds(parsed_content)

349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    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]

365
366
367
    def _process_tokens(
        self,
        parsed_content: TokensPrompt,
368
        tokenization_kwargs: Optional[dict[str, Any]] = None,
369
        *,
370
        mm_uuids: Optional[MultiModalUUIDDict] = None,
371
    ) -> Union[TokenInputs, MultiModalInputs]:
372
373
        prompt_token_ids = self._truncate_inputs(
            parsed_content["prompt_token_ids"], tokenization_kwargs)
374
375
376
377
378
379
380

        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"),
381
                tokenization_kwargs=tokenization_kwargs,
382
                mm_uuids=mm_uuids,
383
            )
384
        else:
385
            inputs = token_inputs(prompt_token_ids=prompt_token_ids)
386
387
388
389
390
391
392
393
394

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

        return inputs

    async def _process_tokens_async(
        self,
        parsed_content: TokensPrompt,
395
        tokenization_kwargs: Optional[dict[str, Any]] = None,
396
        *,
397
        mm_uuids: Optional[MultiModalUUIDDict] = None,
398
    ) -> Union[TokenInputs, MultiModalInputs]:
399
400
        prompt_token_ids = self._truncate_inputs(
            parsed_content["prompt_token_ids"], tokenization_kwargs)
401
402
403
404
405
406
407

        inputs: Union[TokenInputs, MultiModalInputs]
        if multi_modal_data := parsed_content.get("multi_modal_data"):
            inputs = await self._process_multimodal_async(
                prompt_token_ids,
                multi_modal_data,
                parsed_content.get("mm_processor_kwargs"),
408
                tokenization_kwargs=tokenization_kwargs,
409
                mm_uuids=mm_uuids,
410
411
            )
        else:
412
            inputs = token_inputs(prompt_token_ids=prompt_token_ids, )
413
414
415
416
417
418
419
420
421
422

        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,
423
        *,
424
        mm_uuids: Optional[MultiModalUUIDDict] = None,
425
426
427
428
429
430
431
432
433
    ) -> 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"),
434
                tokenization_kwargs=tokenization_kwargs,
435
                mm_uuids=mm_uuids,
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
            )
        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
451

452
453
454
455
    async def _process_text_async(
        self,
        parsed_content: TextPrompt,
        tokenization_kwargs: Optional[dict[str, Any]] = None,
456
        *,
457
        mm_uuids: Optional[MultiModalUUIDDict] = None,
458
459
460
461
462
463
464
465
466
    ) -> Union[TokenInputs, MultiModalInputs]:
        prompt_text = parsed_content["prompt"]

        inputs: Union[TokenInputs, MultiModalInputs]
        if multi_modal_data := parsed_content.get("multi_modal_data"):
            inputs = await self._process_multimodal_async(
                prompt_text,
                multi_modal_data,
                parsed_content.get("mm_processor_kwargs"),
467
                tokenization_kwargs=tokenization_kwargs,
468
                mm_uuids=mm_uuids,
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
            )
        else:
            prompt_token_ids = await self._tokenize_prompt_async(
                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
484

485
    def _prompt_to_llm_inputs(
486
        self,
487
        prompt: SingletonPrompt,
488
        tokenization_kwargs: Optional[dict[str, Any]] = None,
489
        *,
490
        mm_uuids: Optional[MultiModalUUIDDict] = None,
491
    ) -> SingletonInputs:
492
493
        """
        Extract the singleton inputs from a prompt.
494
495
496

        Arguments:

497
        * prompt: single encoder or decoder input prompt
498
499
500

        Returns:

501
        * [`SingletonInputs`][vllm.inputs.data.SingletonInputs] instance
502
        """
503
        parsed = parse_singleton_prompt(prompt)
504
505

        if parsed["type"] == "embeds":
506
507
508
509
            return self._process_embeds(parsed["content"])
        if parsed["type"] == "tokens":
            return self._process_tokens(
                parsed["content"],
510
                mm_uuids=mm_uuids,
511
            )
512
513
514
515
        if parsed["type"] == "text":
            return self._process_text(
                parsed["content"],
                tokenization_kwargs=tokenization_kwargs,
516
                mm_uuids=mm_uuids,
517
518
519
520
            )
        if parsed["type"] == "str":
            return self._process_text(
                TextPrompt(prompt=parsed["content"]),
521
                tokenization_kwargs=tokenization_kwargs,
522
                mm_uuids=mm_uuids,
523
            )
524

525
526
        assert_never(parsed)

527
    async def _prompt_to_llm_inputs_async(
528
        self,
529
        prompt: SingletonPrompt,
530
        tokenization_kwargs: Optional[dict[str, Any]] = None,
531
        *,
532
        mm_uuids: Optional[MultiModalUUIDDict] = None,
533
    ) -> SingletonInputs:
534
535
536
537
        """
        Async version of
        [`_prompt_to_llm_inputs`][vllm.inputs.preprocess.InputPreprocessor._prompt_to_llm_inputs].
        """
538
        parsed = parse_singleton_prompt(prompt)
539

540
        if parsed["type"] == "embeds":
541
542
543
544
            return await self._process_embeds_async(parsed["content"])
        if parsed["type"] == "tokens":
            return await self._process_tokens_async(
                parsed["content"],
545
                mm_uuids=mm_uuids,
546
            )
547
548
549
550
        if parsed["type"] == "text":
            return await self._process_text_async(
                parsed["content"],
                tokenization_kwargs=tokenization_kwargs,
551
                mm_uuids=mm_uuids,
552
553
554
555
            )
        if parsed["type"] == "str":
            return await self._process_text_async(
                TextPrompt(prompt=parsed["content"]),
556
                tokenization_kwargs=tokenization_kwargs,
557
                mm_uuids=mm_uuids,
558
            )
559

560
561
        assert_never(parsed)

562
563
    def _build_enc_dec_llm_inputs(
        self,
564
565
        encoder_inputs: SingletonInputs,
        decoder_inputs: Optional[SingletonInputs],
566
    ) -> EncoderDecoderInputs:
567
568
569
570
        if (encoder_inputs["type"] == "embeds"
                or decoder_inputs and decoder_inputs["type"] == "embeds"):
            raise ValueError("Embedding inputs are not supported for encoder-"
                             "decoder models")
571

572
573
574
575
576
        # Needed for mypy
        encoder_inputs = cast(Union[TokenInputs, MultiModalInputs],
                              encoder_inputs)
        decoder_inputs = cast(Optional[Union[TokenInputs, MultiModalInputs]],
                              decoder_inputs)
577

578
        if decoder_inputs is None:
579
580
581
582
583
584
585
586
587
            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)
588
            decoder_inputs = token_inputs(dec_token_ids)
589
        else:
590
591
592
            if "multi_modal_data" in decoder_inputs:
                raise ValueError("Multi-modal decoder inputs of encoder-"
                                 "decoder models are not supported yet")
593
594
595
596

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

598
        return EncoderDecoderInputs(
599
600
            encoder=encoder_inputs,
            decoder=decoder_inputs,
601
602
        )

603
    def _split_enc_dec_mm_inputs(
604
        self,
605
606
        inputs: Union[SingletonInputs, MultiModalEncDecInputs],
        decoder_inputs_to_override: Optional[SingletonInputs] = None,
607
    ) -> tuple[SingletonInputs, SingletonInputs]:
608
609
610
611
        """
        For encoder/decoder models only:
        Separate Encoder/Decoder inputs from a MultiModalEncDecInputs
        """
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
        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,
        )

627
628
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
629
630
631
632
633
634
635

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

638
639
640
641
            encoder_inputs = token_inputs(
                prompt=inputs["encoder_prompt"],
                prompt_token_ids=inputs["encoder_prompt_token_ids"],
            )
642

643
644
645
646
647
648
649
650
651
652
            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"):
653
654
                decoder_inputs["cache_salt"] = cache_salt

655
        elif inputs["type"] == "token":  # Text-only inputs
656
657
658
659
            encoder_inputs = token_inputs(prompt="", prompt_token_ids=[])
            decoder_inputs = decoder_inputs_to_override or inputs
        else:
            assert_never(inputs)  # type: ignore[arg-type]
660

661
662
        return encoder_inputs, decoder_inputs

663
664
    def _process_encoder_decoder_prompt(
        self,
665
        prompt: PromptType,
666
        tokenization_kwargs: Optional[dict[str, Any]] = None,
667
        *,
668
        mm_uuids: Optional[MultiModalUUIDDict] = None,
669
    ) -> EncoderDecoderInputs:
670
        """
671
        For encoder/decoder models only:
672
673
674
        Process an input prompt into an
        [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
        instance.
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692

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

694
695
        Arguments:

696
        * prompt: an input prompt
697
698
699

        Returns:

700
701
        * [`EncoderDecoderInputs`][vllm.inputs.data.EncoderDecoderInputs]
          instance
702
        """
703
704
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
705

706
        if is_explicit_encoder_decoder_prompt(prompt):
707
            encoder_inputs = self._prompt_to_llm_inputs(
708
709
                prompt["encoder_prompt"],
                tokenization_kwargs=tokenization_kwargs,
710
                mm_uuids=mm_uuids,
711
            )
712
            if (decoder_input := prompt["decoder_prompt"]) is None:
713
                decoder_inputs = None
714
            else:
715
                decoder_inputs = self._prompt_to_llm_inputs(decoder_input)
716
717
            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
718
            if self.model_config.is_multimodal_model:
719
                encoder_inputs, decoder_inputs = (
720
721
                    self._split_enc_dec_mm_inputs(encoder_inputs,
                                                  decoder_inputs))
722
        else:
723
724
725
            inputs = self._prompt_to_llm_inputs(
                prompt,
                tokenization_kwargs=tokenization_kwargs,
726
                mm_uuids=mm_uuids,
727
            )
728
            if self.model_config.is_multimodal_model:
729
730
                # Encoder-Decoder Multimodal model
                encoder_inputs, decoder_inputs = (
731
                    self._split_enc_dec_mm_inputs(inputs))
732
733
734
            else:
                encoder_inputs = inputs
                decoder_inputs = None
735
736

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
737
738
739

    async def _process_encoder_decoder_prompt_async(
        self,
740
        prompt: PromptType,
741
        tokenization_kwargs: Optional[dict[str, Any]] = None,
742
        *,
743
        mm_uuids: Optional[MultiModalUUIDDict] = None,
744
    ) -> EncoderDecoderInputs:
745
746
747
748
        """
        Async version of
        [`_process_encoder_decoder_prompt`][vllm.inputs.preprocess.InputPreprocessor._process_encoder_decoder_prompt].
        """
749
750
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
751

752
        if is_explicit_encoder_decoder_prompt(prompt):
753
            encoder_task = self._prompt_to_llm_inputs_async(
754
755
                prompt["encoder_prompt"],
                tokenization_kwargs=tokenization_kwargs,
756
                mm_uuids=mm_uuids,
757
            )
758

759
            if (decoder_input := prompt["decoder_prompt"]) is None:
760
761
                encoder_inputs = await encoder_task
                decoder_inputs = None
762
            else:
763
764
765
                decoder_task = self._prompt_to_llm_inputs_async(
                    decoder_input,
                    tokenization_kwargs=tokenization_kwargs,
766
                    mm_uuids=mm_uuids,
767
                )
768

769
                encoder_inputs, decoder_inputs = await asyncio.gather(
770
                    encoder_task, decoder_task)
771
772
773

            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
774
            if self.model_config.is_multimodal_model:
775
                encoder_inputs, decoder_inputs = (
776
777
                    self._split_enc_dec_mm_inputs(encoder_inputs,
                                                  decoder_inputs))
778
        else:
779
780
781
            inputs = await self._prompt_to_llm_inputs_async(
                prompt,
                tokenization_kwargs=tokenization_kwargs,
782
                mm_uuids=mm_uuids,
783
            )
784
            if self.model_config.is_multimodal_model:
785
786
                # Encoder-Decoder Multimodal model
                encoder_inputs, decoder_inputs = (
787
                    self._split_enc_dec_mm_inputs(inputs))
788
789
790
            else:
                encoder_inputs = inputs
                decoder_inputs = None
791
792

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
793
794
795

    def _build_decoder_only_llm_inputs(
        self,
796
        prompt_inputs: DecoderOnlyInputs,
797
    ) -> DecoderOnlyInputs:
798
799
800
        if "prompt_token_ids" in prompt_inputs:
            prompt_inputs = cast(Union[TokenInputs, MultiModalInputs],
                                 prompt_inputs)  # Needed for mypy
801

802
        return prompt_inputs
803
804
805

    def _process_decoder_only_prompt(
        self,
806
        prompt: SingletonPrompt,
807
        tokenization_kwargs: Optional[dict[str, Any]] = None,
808
        *,
809
        mm_uuids: Optional[MultiModalUUIDDict] = None,
810
    ) -> DecoderOnlyInputs:
811
        """
812
        For decoder-only models:
813
814
        Process an input prompt into a
        [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance.
815
816
817

        Arguments:

818
        * prompt: input prompt
819
820
821

        Returns:

822
        * [`DecoderOnlyInputs`][vllm.inputs.data.DecoderOnlyInputs] instance
823
        """
824

825
        prompt_comps = self._prompt_to_llm_inputs(
826
            prompt,
827
            tokenization_kwargs=tokenization_kwargs,
828
            mm_uuids=mm_uuids,
829
830
        )

831
        return self._build_decoder_only_llm_inputs(prompt_comps)
832
833
834

    async def _process_decoder_only_prompt_async(
        self,
835
        prompt: SingletonPrompt,
836
        tokenization_kwargs: Optional[dict[str, Any]] = None,
837
        *,
838
        mm_uuids: Optional[MultiModalUUIDDict] = None,
839
    ) -> DecoderOnlyInputs:
840
841
842
843
        """
        Async version of
        [`_process_decoder_only_prompt`][vllm.inputs.preprocess.InputPreprocessor._process_decoder_only_prompt].
        """
844
        prompt_comps = await self._prompt_to_llm_inputs_async(
845
            prompt,
846
            tokenization_kwargs=tokenization_kwargs,
847
            mm_uuids=mm_uuids,
848
849
        )

850
        return self._build_decoder_only_llm_inputs(prompt_comps)
851
852
853

    def preprocess(
        self,
854
        prompt: PromptType,
855
        tokenization_kwargs: Optional[dict[str, Any]] = None,
856
        *,
857
        mm_uuids: Optional[MultiModalUUIDDict] = None,
858
    ) -> ProcessorInputs:
859
        """Preprocess the input prompt."""
860
        if self.model_config.is_encoder_decoder:
861
            # Encoder-decoder model requires special mapping of
862
            # input prompts to encoder & decoder.
863
            return self._process_encoder_decoder_prompt(
864
865
                prompt,
                tokenization_kwargs,
866
                mm_uuids=mm_uuids,
867
            )
868

869
        if is_explicit_encoder_decoder_prompt(prompt):
870
871
872
873
874
            raise ValueError("Cannot pass encoder-decoder prompt "
                             "to decoder-only models")

        # Decoder-only operation
        return self._process_decoder_only_prompt(
875
            prompt,
876
            tokenization_kwargs=tokenization_kwargs,
877
            mm_uuids=mm_uuids,
878
879
880
881
        )

    async def preprocess_async(
        self,
882
        prompt: PromptType,
883
        tokenization_kwargs: Optional[dict[str, Any]] = None,
884
        *,
885
        mm_uuids: Optional[MultiModalUUIDDict] = None,
886
    ) -> ProcessorInputs:
887
888
889
890
        """
        Async version of
        [`preprocess`][vllm.inputs.preprocess.InputPreprocessor.preprocess].
        """
891
        if self.model_config.is_encoder_decoder:
892
            # Encoder-decoder model requires special mapping of
893
894
895
896
            # input prompts to encoder & decoder.
            return await self._process_encoder_decoder_prompt_async(
                prompt,
                tokenization_kwargs,
897
                mm_uuids=mm_uuids,
898
            )
899

900
        if is_explicit_encoder_decoder_prompt(prompt):
901
902
903
904
905
            raise ValueError("Cannot pass encoder-decoder prompt "
                             "to decoder-only models")

        # Decoder-only operation
        return await self._process_decoder_only_prompt_async(
906
            prompt,
907
            tokenization_kwargs=tokenization_kwargs,
908
            mm_uuids=mm_uuids,
909
        )
910
911
912
913

    def clear_cache(self) -> None:
        if self.mm_processor_cache is not None:
            self.mm_processor_cache.clear_cache()
914
915
916
917
918
919
920
921
922
923
924
925


# 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