preprocess.py 30 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
import asyncio
4
from typing import List, Mapping, Optional, Tuple, Union, cast
5
6
7
8
9
10

from typing_extensions import assert_never

from vllm.config import ModelConfig
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
11
from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
12
13
from vllm.multimodal.inputs import (MultiModalDataDict, MultiModalEncDecInputs,
                                    MultiModalInputs)
14
15
16
from vllm.prompt_adapter.request import PromptAdapterRequest
from vllm.transformers_utils.tokenizer_group import BaseTokenizerGroup

17
18
from .data import (DecoderOnlyInputs, EncoderDecoderInputs, ProcessorInputs,
                   PromptType, SingletonInputs, SingletonPrompt, token_inputs)
19
20
21
22
23
24
25
26
27
28
29
from .parse import is_explicit_encoder_decoder_prompt, parse_singleton_prompt

logger = init_logger(__name__)


class InputPreprocessor:

    def __init__(
        self,
        model_config: ModelConfig,
        tokenizer: Optional[BaseTokenizerGroup],
30
        mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
31
32
33
34
35
    ) -> None:
        super().__init__()

        self.model_config = model_config
        self.tokenizer = tokenizer
36
        self.mm_registry = mm_registry
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

    def get_tokenizer_group(self) -> BaseTokenizerGroup:
        if self.tokenizer is None:
            raise ValueError("You cannot pass text prompts when "
                             "`skip_tokenizer_init` is True")

        return self.tokenizer

    def get_bos_token_id(self,
                         lora_request: Optional[LoRARequest] = None
                         ) -> Optional[int]:
        if self.tokenizer is None:
            logger.warning("Using None for BOS token id because tokenizer "
                           "is not initialized")
            return None

        return self.tokenizer.get_lora_tokenizer(lora_request).bos_token_id

    def get_eos_token_id(self,
                         lora_request: Optional[LoRARequest] = None
                         ) -> Optional[int]:
        if self.tokenizer is None:
            logger.warning("Using None for EOS token id because tokenizer "
                           "is not initialized")
            return None

        return self.tokenizer.get_lora_tokenizer(lora_request).eos_token_id

    def get_decoder_start_token_id(self) -> Optional[int]:
        '''
        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.
        '''

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

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

        dec_start_token_id = getattr(self.model_config.hf_config,
                                     'decoder_start_token_id', None)
        if dec_start_token_id is None:
87
88
89
90
            logger.warning_once(
                "Falling back on <BOS> for decoder start token "
                "id because decoder start token id is not "
                "available.")
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
            dec_start_token_id = self.get_bos_token_id()

        return dec_start_token_id

    def _get_default_enc_dec_decoder_prompt(self) -> List[int]:
        '''
        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
117
        other models may have different or more
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
        complex logic for the default decoder prompt.
        This motivates having a special helper method
        for default decoder prompts.

        Returns:

        * prompt_token_ids
        '''

        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,
        decoder_input_ids: Optional[List[int]],
    ) -> List[int]:
        """
        Prepares `decoder_input_ids` for generation with encoder-decoder models.

        Based on

        https://github.com/huggingface/transformers/blob/
        4037a2b5b1278736e566aec12e169100275545ea/
        src/transformers/generation/utils.py

        specifically GenerationMixin._prepare_decoder_input_ids_for_generation()

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

163
164
        if (len(decoder_input_ids) == 0
                or decoder_input_ids[0] != decoder_start_token_id):
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
            decoder_input_ids = [decoder_start_token_id] + decoder_input_ids

        return decoder_input_ids

    def _apply_prompt_adapter(
        self,
        prompt_token_ids: List[int],
        prompt_adapter_request: Optional[PromptAdapterRequest],
    ) -> List[int]:
        if prompt_adapter_request:
            prompt_token_ids = (
                [0] * prompt_adapter_request.prompt_adapter_num_virtual_tokens
                + prompt_token_ids)

        return prompt_token_ids

    def _tokenize_prompt(
        self,
        prompt: str,
        request_id: str,
        lora_request: Optional[LoRARequest],
    ) -> List[int]:
        """
        Apply the model's tokenizer to a text prompt, returning the
        corresponding token IDs.
        """
        tokenizer = self.get_tokenizer_group()
192
193
194
195
196
197
        add_special_tokens = None
        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.
            add_special_tokens = False
198
199
200
201
202
203

        if (self.model_config.encoder_config is not None
                and self.model_config.encoder_config.get(
                    "do_lower_case", False)):
            prompt = prompt.lower()

204
205
        return tokenizer.encode(request_id=request_id,
                                prompt=prompt,
206
207
                                lora_request=lora_request,
                                add_special_tokens=add_special_tokens)
208
209
210
211
212
213
214
215
216

    async def _tokenize_prompt_async(
        self,
        prompt: str,
        request_id: str,
        lora_request: Optional[LoRARequest],
    ) -> List[int]:
        """Async version of :meth:`_tokenize_prompt`."""
        tokenizer = self.get_tokenizer_group()
217
218
219
220
221
222
223
224
225
226
227
        add_special_tokens = None
        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.
            add_special_tokens = False
        return await tokenizer.encode_async(
            request_id=request_id,
            prompt=prompt,
            lora_request=lora_request,
            add_special_tokens=add_special_tokens)
228

229
230
231
232
233
234
235
236
237
238
    def _can_process_multimodal(self) -> bool:
        model_config = self.model_config

        if not model_config.is_multimodal_model:
            raise ValueError("Your model does not support multi-modal inputs")

        # Interim measure so we can handle models that have yet to be
        # updated to use the new multi-modal processor
        can_process_multimodal = self.mm_registry.has_processor(model_config)
        if not can_process_multimodal:
239
240
241
242
243
244
245
246
247
            from vllm.model_executor.models.registry import _VLLM_MODELS
            if not any(arch in _VLLM_MODELS
                       for arch in model_config.architectures):
                logger.warning_once(
                    "Your model uses the legacy input pipeline, which will be "
                    "removed in an upcoming release. "
                    "Please upgrade to the new multi-modal processing pipeline "
                    "(https://docs.vllm.ai/en/latest/design/mm_processing.html)"
                )
248
249
250
251
252
253
254
255
256

        return can_process_multimodal

    def _process_multimodal(
        self,
        prompt: Union[str, List[int]],
        mm_data: MultiModalDataDict,
        mm_processor_kwargs: Optional[Mapping[str, object]],
        lora_request: Optional[LoRARequest],
257
        return_mm_hashes: bool = False,
258
    ) -> MultiModalInputs:
259
260
261
262
        """
        Apply the model's multi-modal processor to a multi-modal prompt,
        returning the corresponding token IDs and metadata.
        """
263
264
265
266
267
268
269
270
        # At the moment on model (PrithviGeoSpatialMAE) requires to be
        # initialized without a tokenizer while using also multi-modal
        # input.
        if not self.tokenizer:
            tokenizer = None
        else:
            tokenizer_group = self.get_tokenizer_group()
            tokenizer = tokenizer_group.get_lora_tokenizer(lora_request)
271
272
273
274
275
276
277

        mm_processor = self.mm_registry.create_processor(
            self.model_config, tokenizer)

        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

278
279
        return mm_processor.apply(prompt, mm_data, mm_processor_kwargs,
                                  return_mm_hashes)
280
281
282
283
284
285
286

    async def _process_multimodal_async(
        self,
        prompt: Union[str, List[int]],
        mm_data: MultiModalDataDict,
        mm_processor_kwargs: Optional[Mapping[str, object]],
        lora_request: Optional[LoRARequest],
287
        return_mm_hashes: bool = False,
288
    ) -> MultiModalInputs:
289
        """Async version of :meth:`_process_multimodal`."""
290
291
292
293
294
295
296
297
298
        # At the moment on model (PrithviGeoSpatialMAE) requires to be
        # initialized without a tokenizer while using also multi-modal
        # input.
        if not self.tokenizer:
            tokenizer = None
        else:
            tokenizer_group = self.get_tokenizer_group()
            tokenizer = await tokenizer_group.get_lora_tokenizer_async(
                lora_request)
299
300
301
302
303
304

        mm_processor = self.mm_registry.create_processor(
            self.model_config, tokenizer)
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}

305
306
        return mm_processor.apply(prompt, mm_data, mm_processor_kwargs,
                                  return_mm_hashes)
307

308
    def _prompt_to_llm_inputs(
309
        self,
310
        prompt: SingletonPrompt,
311
312
        request_id: str,
        lora_request: Optional[LoRARequest] = None,
313
        return_mm_hashes: bool = False,
314
    ) -> SingletonInputs:
315
316
        """
        Extract the singleton inputs from a prompt.
317
318
319
320

        Arguments:

        * request_id
321
        * prompt: single encoder or decoder input prompt
322
        * lora_request: this is only valid for decoder prompts
323
        * return_mm_hashes: whether to return multimodal hashes
324
325
326

        Returns:

327
328
        * :class:`SingletonInputs` instance
        """
329
        parsed = parse_singleton_prompt(prompt)
330
331

        if parsed["type"] == "str":
332
            prompt_text = parsed["content"]
333
            prompt_token_ids = self._tokenize_prompt(
334
                prompt_text,
335
336
337
                request_id=request_id,
                lora_request=lora_request,
            )
338
339
340
341
342
343
344
345
346
347

            return token_inputs(
                prompt=prompt_text,
                prompt_token_ids=prompt_token_ids,
            )

        if parsed["type"] == "tokens":
            tokens_content = parsed["content"]

            prompt_token_ids = tokens_content["prompt_token_ids"]
348
            token_type_ids = tokens_content.get("token_type_ids")
349
350
351
            multi_modal_data = tokens_content.get("multi_modal_data")
            mm_processor_kwargs = tokens_content.get("mm_processor_kwargs")

352
353
354
355
356
357
            if multi_modal_data is not None and self._can_process_multimodal():
                return self._process_multimodal(
                    prompt_token_ids,
                    multi_modal_data,
                    mm_processor_kwargs,
                    lora_request=lora_request,
358
                    return_mm_hashes=return_mm_hashes,
359
360
                )

361
362
            return token_inputs(
                prompt_token_ids=prompt_token_ids,
363
                token_type_ids=token_type_ids,
364
365
366
367
368
369
370
371
                multi_modal_data=multi_modal_data,
                mm_processor_kwargs=mm_processor_kwargs,
            )

        if parsed["type"] == "text":
            text_content = parsed["content"]

            prompt_text = text_content["prompt"]
372
373
374
375
376
377
378
379
380
381
382
            multi_modal_data = text_content.get("multi_modal_data")
            mm_processor_kwargs = text_content.get("mm_processor_kwargs")

            if multi_modal_data is not None and self._can_process_multimodal():
                return self._process_multimodal(
                    prompt_text,
                    multi_modal_data,
                    mm_processor_kwargs,
                    lora_request=lora_request,
                )

383
            prompt_token_ids = self._tokenize_prompt(
384
                prompt_text,
385
386
387
                request_id=request_id,
                lora_request=lora_request,
            )
388
389
390
391
392
393
394

            return token_inputs(
                prompt=prompt_text,
                prompt_token_ids=prompt_token_ids,
                multi_modal_data=multi_modal_data,
                mm_processor_kwargs=mm_processor_kwargs,
            )
395

396
        assert_never(parsed)
397

398
    async def _prompt_to_llm_inputs_async(
399
        self,
400
        prompt: SingletonPrompt,
401
402
        request_id: str,
        lora_request: Optional[LoRARequest] = None,
403
    ) -> SingletonInputs:
404
        """Async version of :meth:`_extract_prompt_components`."""
405
        parsed = parse_singleton_prompt(prompt)
406
407

        if parsed["type"] == "str":
408
            prompt_text = parsed["content"]
409
            prompt_token_ids = await self._tokenize_prompt_async(
410
                prompt_text,
411
412
413
                request_id=request_id,
                lora_request=lora_request,
            )
414
415
416
417
418
419
420
421
422
423
424
425
426

            return token_inputs(
                prompt=prompt_text,
                prompt_token_ids=prompt_token_ids,
            )

        if parsed["type"] == "tokens":
            tokens_content = parsed["content"]

            prompt_token_ids = tokens_content["prompt_token_ids"]
            multi_modal_data = tokens_content.get("multi_modal_data")
            mm_processor_kwargs = tokens_content.get("mm_processor_kwargs")

427
428
429
430
431
432
433
434
            if multi_modal_data is not None and self._can_process_multimodal():
                return await self._process_multimodal_async(
                    prompt_token_ids,
                    multi_modal_data,
                    mm_processor_kwargs,
                    lora_request=lora_request,
                )

435
436
437
438
439
440
441
442
443
444
            return token_inputs(
                prompt_token_ids=prompt_token_ids,
                multi_modal_data=multi_modal_data,
                mm_processor_kwargs=mm_processor_kwargs,
            )

        if parsed["type"] == "text":
            text_content = parsed["content"]

            prompt_text = text_content["prompt"]
445
446
447
448
449
450
451
452
453
454
455
            multi_modal_data = text_content.get("multi_modal_data")
            mm_processor_kwargs = text_content.get("mm_processor_kwargs")

            if multi_modal_data is not None and self._can_process_multimodal():
                return await self._process_multimodal_async(
                    prompt_text,
                    multi_modal_data,
                    mm_processor_kwargs,
                    lora_request=lora_request,
                )

456
            prompt_token_ids = await self._tokenize_prompt_async(
457
                prompt_text,
458
459
460
                request_id=request_id,
                lora_request=lora_request,
            )
461
462
463
464
465
466
467

            return token_inputs(
                prompt=prompt_text,
                prompt_token_ids=prompt_token_ids,
                multi_modal_data=multi_modal_data,
                mm_processor_kwargs=mm_processor_kwargs,
            )
468

469
        assert_never(parsed)
470
471
472

    def _build_enc_dec_llm_inputs(
        self,
473
474
        encoder_inputs: SingletonInputs,
        decoder_inputs: Optional[SingletonInputs],
475
    ) -> EncoderDecoderInputs:
476
477
        if (encoder_inputs["type"] == "token"
                or encoder_inputs["type"] == "multimodal"):
478
479
            pass
        else:
480
            assert_never(encoder_inputs)  # type: ignore[arg-type]
481
482

        if decoder_inputs is None:
483
484
485
486
487
488
489
490
491
            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)
492
            decoder_inputs = token_inputs(dec_token_ids)
493
494
        elif (decoder_inputs["type"] == "token"
              or decoder_inputs["type"] == "multimodal"):
495
496
497
498
499
500
501
502
            dec_token_ids = self._prepare_decoder_input_ids_for_generation(
                decoder_inputs["prompt_token_ids"])
            decoder_inputs["prompt_token_ids"] = dec_token_ids

            if "multi_modal_data" in decoder_inputs:
                raise ValueError("Multi-modal decoder inputs of encoder-"
                                 "decoder models are not supported yet")
        else:
503
            assert_never(encoder_inputs)  # type: ignore[arg-type]
504

505
        return EncoderDecoderInputs(
506
507
            encoder=encoder_inputs,
            decoder=decoder_inputs,
508
509
        )

510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    def _separate_enc_dec_inputs_from_mm_processor_outputs(
        self,
        inputs: SingletonInputs,
        decoder_inputs_to_override: Optional[SingletonInputs] = None,
    ) -> Tuple[SingletonInputs, SingletonInputs]:
        """
        For encoder/decoder models only:
        Separate Encoder/Decoder inputs from a MultiModalEncDecInputs
        """
        encoder_inputs: SingletonInputs
        decoder_inputs: SingletonInputs
        if inputs["type"] == "multimodal":
            # Multimodal data inputs
            assert ("encoder_prompt" in inputs
                    and "encoder_prompt_token_ids" in inputs)
            inputs = cast(MultiModalEncDecInputs, inputs)
            encoder_inputs = token_inputs(
                prompt=inputs["encoder_prompt"],
                prompt_token_ids=inputs["encoder_prompt_token_ids"],
            )
            if decoder_inputs_to_override is not None:
                decoder_inputs = MultiModalInputs(
                    type="multimodal",
                    prompt=decoder_inputs_to_override.get("prompt", ""),
                    prompt_token_ids=decoder_inputs_to_override[
                        "prompt_token_ids"],
                    mm_kwargs=inputs["mm_kwargs"],
                    mm_placeholders=inputs["mm_placeholders"],
                )
            else:
                decoder_inputs = MultiModalInputs(
                    type="multimodal",
                    prompt=inputs["prompt"],
                    prompt_token_ids=inputs["prompt_token_ids"],
                    mm_kwargs=inputs["mm_kwargs"],
                    mm_placeholders=inputs["mm_placeholders"],
                )
        elif inputs["type"] == "token":
            # Text-only inputs
            encoder_inputs = token_inputs(prompt="", prompt_token_ids=[])
            decoder_inputs = decoder_inputs_to_override or inputs
        else:
            assert_never(inputs)  # type: ignore[arg-type]
        return encoder_inputs, decoder_inputs

555
556
    def _process_encoder_decoder_prompt(
        self,
557
        prompt: PromptType,
558
        request_id: str,
559
    ) -> EncoderDecoderInputs:
560
        """
561
        For encoder/decoder models only:
562
        Process an input prompt into an :class:`EncoderDecoderInputs` instance.
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580

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

582
583
        Arguments:

584
        * prompt: an input prompt
585
586
587
588
        * request_id

        Returns:

589
        * :class:`EncoderDecoderInputs` instance
590
        """
591
592
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
593

594
        if is_explicit_encoder_decoder_prompt(prompt):
595
            encoder_inputs = self._prompt_to_llm_inputs(
596
                prompt["encoder_prompt"],
597
598
                request_id=request_id,
            )
599
            if (decoder_input := prompt["decoder_prompt"]) is None:
600
                decoder_inputs = None
601
            else:
602
                decoder_inputs = self._prompt_to_llm_inputs(
603
604
605
                    decoder_input,
                    request_id=request_id,
                )
606
607
608
609
610
611
612
            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
            if self.model_config.is_multimodal_model and (
                    self._can_process_multimodal()):
                encoder_inputs, decoder_inputs = (
                    self._separate_enc_dec_inputs_from_mm_processor_outputs(
                        encoder_inputs, decoder_inputs))
613
        else:
614
            inputs = self._prompt_to_llm_inputs(
615
                prompt,
616
617
                request_id=request_id,
            )
618
619
620
621
622
623
624
625
            if self.model_config.is_multimodal_model and (
                    self._can_process_multimodal()):
                # Encoder-Decoder Multimodal model
                encoder_inputs, decoder_inputs = (
                    self._separate_enc_dec_inputs_from_mm_processor_outputs(
                        inputs))
            else:
                encoder_inputs = inputs
626

627
                decoder_inputs = None
628
629

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
630
631
632

    async def _process_encoder_decoder_prompt_async(
        self,
633
        prompt: PromptType,
634
        request_id: str,
635
    ) -> EncoderDecoderInputs:
636
        """Async version of :meth:`_process_encoder_decoder_prompt`."""
637
638
        encoder_inputs: SingletonInputs
        decoder_inputs: Optional[SingletonInputs]
639

640
        if is_explicit_encoder_decoder_prompt(prompt):
641
            encoder_task = self._prompt_to_llm_inputs_async(
642
                prompt["encoder_prompt"],
643
644
645
                request_id=request_id,
            )

646
            if (decoder_input := prompt["decoder_prompt"]) is None:
647
648
                encoder_inputs = await encoder_task
                decoder_inputs = None
649
            else:
650
                decoder_task = self._prompt_to_llm_inputs_async(
651
652
653
654
                    decoder_input,
                    request_id=request_id,
                )

655
                encoder_inputs, decoder_inputs = await asyncio.gather(
656
                    encoder_task, decoder_task)
657
658
659
660
661
662
663
664

            # For multimodal model, override decoder prompt from processor
            # with explicit decoder prompt.
            if self.model_config.is_multimodal_model and (
                    self._can_process_multimodal()):
                encoder_inputs, decoder_inputs = (
                    self._separate_enc_dec_inputs_from_mm_processor_outputs(
                        encoder_inputs, decoder_inputs))
665
        else:
666
            inputs = await self._prompt_to_llm_inputs_async(
667
                prompt,
668
669
                request_id=request_id,
            )
670
671
672
673
674
675
676
677
            if self.model_config.is_multimodal_model and (
                    self._can_process_multimodal()):
                # Encoder-Decoder Multimodal model
                encoder_inputs, decoder_inputs = (
                    self._separate_enc_dec_inputs_from_mm_processor_outputs(
                        inputs))
            else:
                encoder_inputs = inputs
678

679
                decoder_inputs = None
680
681

        return self._build_enc_dec_llm_inputs(encoder_inputs, decoder_inputs)
682
683
684

    def _build_decoder_only_llm_inputs(
        self,
685
        prompt_inputs: DecoderOnlyInputs,
686
        prompt_adapter_request: Optional[PromptAdapterRequest],
687
    ) -> DecoderOnlyInputs:
688
689
        if (prompt_inputs["type"] == "token"
                or prompt_inputs["type"] == "multimodal"):
690
691
692
693
694
            prompt_inputs["prompt_token_ids"] = self._apply_prompt_adapter(
                prompt_inputs["prompt_token_ids"],
                prompt_adapter_request=prompt_adapter_request,
            )
        else:
695
            assert_never(prompt_inputs)  # type: ignore[arg-type]
696

697
        return prompt_inputs
698
699
700

    def _process_decoder_only_prompt(
        self,
701
        prompt: SingletonPrompt,
702
703
704
        request_id: str,
        lora_request: Optional[LoRARequest] = None,
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
705
        return_mm_hashes: bool = False,
706
    ) -> DecoderOnlyInputs:
707
        """
708
        For decoder-only models:
709
        Process an input prompt into an :class:`DecoderOnlyInputs` instance.
710
711
712

        Arguments:

713
        * prompt: input prompt
714
715
716
        * request_id
        * lora_request
        * prompt_adapter_request
717
        * return_mm_hashes
718
719
720

        Returns:

721
        * :class:`DecoderOnlyInputs` instance
722
        """
723

724
        prompt_comps = self._prompt_to_llm_inputs(
725
            prompt,
726
727
728
729
730
731
732
733
734
735
736
            request_id=request_id,
            lora_request=lora_request,
        )

        return self._build_decoder_only_llm_inputs(
            prompt_comps,
            prompt_adapter_request=prompt_adapter_request,
        )

    async def _process_decoder_only_prompt_async(
        self,
737
        prompt: SingletonPrompt,
738
739
740
        request_id: str,
        lora_request: Optional[LoRARequest] = None,
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
741
        return_mm_hashes: bool = False,
742
    ) -> DecoderOnlyInputs:
743
        """Async version of :meth:`_process_decoder_only_prompt`."""
744
        prompt_comps = await self._prompt_to_llm_inputs_async(
745
            prompt,
746
747
748
749
750
751
752
753
754
755
756
            request_id=request_id,
            lora_request=lora_request,
        )

        return self._build_decoder_only_llm_inputs(
            prompt_comps,
            prompt_adapter_request=prompt_adapter_request,
        )

    def preprocess(
        self,
757
        prompt: PromptType,
758
759
760
        request_id: str,
        lora_request: Optional[LoRARequest] = None,
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
761
        return_mm_hashes: bool = False,
762
    ) -> ProcessorInputs:
763
        """Preprocess the input prompt."""
764
        if self.model_config.is_encoder_decoder:
765
766
767
            assert not return_mm_hashes, (
                "Multimodal hashes for encoder-decoder models should not be ",
                "returned until they are supported on vLLM V1.")
768
769
770
            # Encoder-decoder model requires special mapping of
            # input prompts to encoder & decoder
            return self._process_encoder_decoder_prompt(
771
                prompt,
772
773
774
                request_id=request_id,
            )

775
        if is_explicit_encoder_decoder_prompt(prompt):
776
777
778
779
780
            raise ValueError("Cannot pass encoder-decoder prompt "
                             "to decoder-only models")

        # Decoder-only operation
        return self._process_decoder_only_prompt(
781
            prompt,
782
783
784
            request_id=request_id,
            lora_request=lora_request,
            prompt_adapter_request=prompt_adapter_request,
785
            return_mm_hashes=return_mm_hashes,
786
787
788
789
        )

    async def preprocess_async(
        self,
790
        prompt: PromptType,
791
792
793
        request_id: str,
        lora_request: Optional[LoRARequest] = None,
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
794
        return_mm_hashes: bool = False,
795
    ) -> ProcessorInputs:
796
        """Async version of :meth:`preprocess`."""
797
        if self.model_config.is_encoder_decoder:
798
799
800
            assert not return_mm_hashes, (
                "Multimodal hashes for encoder-decoder models should not be ",
                "returned until they are supported on vLLM V1.")
801
802
803
            # Encoder-decoder model requires special mapping of
            # input prompts to encoder & decoder
            return await self._process_encoder_decoder_prompt_async(
804
                prompt,
805
806
807
                request_id=request_id,
            )

808
        if is_explicit_encoder_decoder_prompt(prompt):
809
810
811
812
813
            raise ValueError("Cannot pass encoder-decoder prompt "
                             "to decoder-only models")

        # Decoder-only operation
        return await self._process_decoder_only_prompt_async(
814
            prompt,
815
816
817
            request_id=request_id,
            lora_request=lora_request,
            prompt_adapter_request=prompt_adapter_request,
818
            return_mm_hashes=return_mm_hashes,
819
        )