llm.py 30.8 KB
Newer Older
1
2
from contextlib import contextmanager
from typing import ClassVar, List, Optional, Sequence, Union, cast, overload
3

4
from tqdm import tqdm
5

Woosuk Kwon's avatar
Woosuk Kwon committed
6
7
from vllm.engine.arg_utils import EngineArgs
from vllm.engine.llm_engine import LLMEngine
nunjunj's avatar
nunjunj committed
8
from vllm.entrypoints.chat_utils import (ChatCompletionMessageParam,
9
10
                                         apply_hf_chat_template,
                                         apply_mistral_chat_template,
nunjunj's avatar
nunjunj committed
11
                                         parse_chat_messages)
12
13
from vllm.inputs import PromptInputs, TextPrompt, TokensPrompt
from vllm.inputs.parse import parse_and_batch_prompt
14
from vllm.logger import init_logger
15
from vllm.lora.request import LoRARequest
16
17
18
from vllm.model_executor.guided_decoding import (
    GuidedDecodingRequest, get_local_guided_decoding_logits_processor)
from vllm.model_executor.guided_decoding.guided_fields import LLMGuidedOptions
19
20
from vllm.outputs import EmbeddingRequestOutput, RequestOutput
from vllm.pooling_params import PoolingParams
21
from vllm.prompt_adapter.request import PromptAdapterRequest
22
from vllm.sampling_params import RequestOutputKind, SamplingParams
23
from vllm.transformers_utils.tokenizer import (AnyTokenizer, MistralTokenizer,
24
25
                                               get_cached_tokenizer)
from vllm.transformers_utils.tokenizer_group import TokenizerGroup
yhu422's avatar
yhu422 committed
26
from vllm.usage.usage_lib import UsageContext
27
from vllm.utils import Counter, deprecate_kwargs, is_list_of
28

29
30
logger = init_logger(__name__)

31
32

class LLM:
Woosuk Kwon's avatar
Woosuk Kwon committed
33
34
35
36
37
38
39
40
41
42
    """An LLM for generating texts from given prompts and sampling parameters.

    This class includes a tokenizer, a language model (possibly distributed
    across multiple GPUs), and GPU memory space allocated for intermediate
    states (aka KV cache). Given a batch of prompts and sampling parameters,
    this class generates texts from the model, using an intelligent batching
    mechanism and efficient memory management.

    Args:
        model: The name or path of a HuggingFace Transformers model.
43
        tokenizer: The name or path of a HuggingFace Transformers tokenizer.
44
45
        tokenizer_mode: The tokenizer mode. "auto" will use the fast tokenizer
            if available, and "slow" will always use the slow tokenizer.
46
47
48
        skip_tokenizer_init: If true, skip initialization of tokenizer and
            detokenizer. Expect valid prompt_token_ids and None for prompt
            from the input.
49
50
        trust_remote_code: Trust remote code (e.g., from HuggingFace) when
            downloading the model and tokenizer.
Woosuk Kwon's avatar
Woosuk Kwon committed
51
52
53
        tensor_parallel_size: The number of GPUs to use for distributed
            execution with tensor parallelism.
        dtype: The data type for the model weights and activations. Currently,
Woosuk Kwon's avatar
Woosuk Kwon committed
54
55
56
57
            we support `float32`, `float16`, and `bfloat16`. If `auto`, we use
            the `torch_dtype` attribute specified in the model config file.
            However, if the `torch_dtype` in the config is `float32`, we will
            use `float16` instead.
58
        quantization: The method used to quantize the model weights. Currently,
59
            we support "awq", "gptq", and "fp8" (experimental).
60
61
62
63
            If None, we first check the `quantization_config` attribute in the
            model config file. If that is None, we assume the model weights are
            not quantized and use `dtype` to determine the data type of
            the weights.
Jasmond L's avatar
Jasmond L committed
64
65
        revision: The specific model version to use. It can be a branch name,
            a tag name, or a commit id.
66
67
        tokenizer_revision: The specific tokenizer version to use. It can be a
            branch name, a tag name, or a commit id.
68
69
70
71
72
73
74
75
76
77
78
        seed: The seed to initialize the random number generator for sampling.
        gpu_memory_utilization: The ratio (between 0 and 1) of GPU memory to
            reserve for the model weights, activations, and KV cache. Higher
            values will increase the KV cache size and thus improve the model's
            throughput. However, if the value is too high, it may cause out-of-
            memory (OOM) errors.
        swap_space: The size (GiB) of CPU memory per GPU to use as swap space.
            This can be used for temporarily storing the states of the requests
            when their `best_of` sampling parameters are larger than 1. If all
            requests will have `best_of=1`, you can safely set this to 0.
            Otherwise, too small values may cause out-of-memory (OOM) errors.
79
80
81
82
        cpu_offload_gb: The size (GiB) of CPU memory to use for offloading
            the model weights. This virtually increases the GPU memory space
            you can use to hold the model weights, at the cost of CPU-GPU data
            transfer for every forward pass.
83
84
85
86
        enforce_eager: Whether to enforce eager execution. If True, we will
            disable CUDA graph and always execute the model in eager mode.
            If False, we will use CUDA graph and eager execution in hybrid.
        max_context_len_to_capture: Maximum context len covered by CUDA graphs.
87
88
89
            When a sequence has context length larger than this, we fall back
            to eager mode (DEPRECATED. Use `max_seq_len_to_capture` instead).
        max_seq_len_to_capture: Maximum sequence len covered by CUDA graphs.
90
91
            When a sequence has context length larger than this, we fall back
            to eager mode.
92
        disable_custom_all_reduce: See ParallelConfig
93
94
        **kwargs: Arguments for :class:`~vllm.EngineArgs`. (See
            :ref:`engine_args`)
nunjunj's avatar
nunjunj committed
95

96
97
98
    Note:
        This class is intended to be used for offline inference. For online
        serving, use the :class:`~vllm.AsyncLLMEngine` class instead.
Woosuk Kwon's avatar
Woosuk Kwon committed
99
    """
100

101
102
103
104
105
106
107
108
109
110
111
112
    DEPRECATE_LEGACY: ClassVar[bool] = False
    """A flag to toggle whether to deprecate the legacy generate/encode API."""

    @classmethod
    @contextmanager
    def deprecate_legacy_api(cls):
        cls.DEPRECATE_LEGACY = True

        yield

        cls.DEPRECATE_LEGACY = False

113
114
115
    def __init__(
        self,
        model: str,
116
        tokenizer: Optional[str] = None,
117
        tokenizer_mode: str = "auto",
118
        skip_tokenizer_init: bool = False,
119
        trust_remote_code: bool = False,
120
        tensor_parallel_size: int = 1,
Woosuk Kwon's avatar
Woosuk Kwon committed
121
        dtype: str = "auto",
122
        quantization: Optional[str] = None,
123
        revision: Optional[str] = None,
124
        tokenizer_revision: Optional[str] = None,
125
126
        seed: int = 0,
        gpu_memory_utilization: float = 0.9,
127
        swap_space: float = 4,
128
        cpu_offload_gb: float = 0,
129
        enforce_eager: Optional[bool] = None,
130
131
        max_context_len_to_capture: Optional[int] = None,
        max_seq_len_to_capture: int = 8192,
132
        disable_custom_all_reduce: bool = False,
133
        disable_async_output_proc: bool = False,
134
135
        **kwargs,
    ) -> None:
136
137
138
139
140
141
142
143
144
        '''
        LLM constructor.

        Note: if enforce_eager is unset (enforce_eager is None)
        it defaults to False for decoder-only models and True
        for encoder/decoder models, since encoder/decoder models
        do not currently support CUDAGraph.
        '''

145
146
        if "disable_log_stats" not in kwargs:
            kwargs["disable_log_stats"] = True
nunjunj's avatar
nunjunj committed
147
148
149
150
151
152
        removed_vision_keys = (
            "image_token_id",
            "image_feature_size",
            "image_input_shape",
            "image_input_type",
        )
153
154
155
        if any(k in kwargs for k in removed_vision_keys):
            raise TypeError(
                "There is no need to pass vision-related arguments anymore.")
Zhuohan Li's avatar
Zhuohan Li committed
156
        engine_args = EngineArgs(
157
            model=model,
158
            tokenizer=tokenizer,
159
            tokenizer_mode=tokenizer_mode,
160
            skip_tokenizer_init=skip_tokenizer_init,
161
            trust_remote_code=trust_remote_code,
162
163
            tensor_parallel_size=tensor_parallel_size,
            dtype=dtype,
164
            quantization=quantization,
165
            revision=revision,
166
            tokenizer_revision=tokenizer_revision,
167
168
169
            seed=seed,
            gpu_memory_utilization=gpu_memory_utilization,
            swap_space=swap_space,
170
            cpu_offload_gb=cpu_offload_gb,
171
172
            enforce_eager=enforce_eager,
            max_context_len_to_capture=max_context_len_to_capture,
173
            max_seq_len_to_capture=max_seq_len_to_capture,
174
            disable_custom_all_reduce=disable_custom_all_reduce,
175
            disable_async_output_proc=disable_async_output_proc,
176
177
            **kwargs,
        )
yhu422's avatar
yhu422 committed
178
179
        self.llm_engine = LLMEngine.from_engine_args(
            engine_args, usage_context=UsageContext.LLM_CLASS)
180
181
        self.request_counter = Counter()

182
183
184
185
186
    def get_tokenizer(self) -> AnyTokenizer:
        return self.llm_engine.get_tokenizer_group(TokenizerGroup).tokenizer

    def set_tokenizer(self, tokenizer: AnyTokenizer) -> None:
        tokenizer_group = self.llm_engine.get_tokenizer_group(TokenizerGroup)
187

188
189
190
191
        # While CachedTokenizer is dynamic, have no choice but
        # compare class name. Misjudgment will arise from
        # user-defined tokenizer started with 'Cached'
        if tokenizer.__class__.__name__.startswith("Cached"):
192
            tokenizer_group.tokenizer = tokenizer
193
        else:
194
            tokenizer_group.tokenizer = get_cached_tokenizer(tokenizer)
195

196
197
198
199
200
201
202
203
    @overload  # LEGACY: single (prompt + optional token ids)
    def generate(
        self,
        prompts: str,
        sampling_params: Optional[Union[SamplingParams,
                                        List[SamplingParams]]] = None,
        prompt_token_ids: Optional[List[int]] = None,
        use_tqdm: bool = True,
204
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
205
206
207
208
    ) -> List[RequestOutput]:
        ...

    @overload  # LEGACY: multi (prompt + optional token ids)
209
210
    def generate(
        self,
211
        prompts: List[str],
212
213
        sampling_params: Optional[Union[SamplingParams,
                                        List[SamplingParams]]] = None,
214
        prompt_token_ids: Optional[List[List[int]]] = None,
215
        use_tqdm: bool = True,
216
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
217
218
219
220
221
222
223
224
225
226
227
228
    ) -> List[RequestOutput]:
        ...

    @overload  # LEGACY: single (token ids + optional prompt)
    def generate(
        self,
        prompts: Optional[str] = None,
        sampling_params: Optional[Union[SamplingParams,
                                        List[SamplingParams]]] = None,
        *,
        prompt_token_ids: List[int],
        use_tqdm: bool = True,
229
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
230
231
232
233
234
235
236
237
238
239
240
241
    ) -> List[RequestOutput]:
        ...

    @overload  # LEGACY: multi (token ids + optional prompt)
    def generate(
        self,
        prompts: Optional[List[str]] = None,
        sampling_params: Optional[Union[SamplingParams,
                                        List[SamplingParams]]] = None,
        *,
        prompt_token_ids: List[List[int]],
        use_tqdm: bool = True,
242
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
243
244
245
246
247
248
249
250
251
252
    ) -> List[RequestOutput]:
        ...

    @overload  # LEGACY: single or multi token ids [pos-only]
    def generate(
        self,
        prompts: None,
        sampling_params: None,
        prompt_token_ids: Union[List[int], List[List[int]]],
        use_tqdm: bool = True,
253
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
254
255
256
257
258
259
    ) -> List[RequestOutput]:
        ...

    @overload
    def generate(
        self,
260
        inputs: Union[PromptInputs, Sequence[PromptInputs]],
261
262
263
264
265
        /,  # We may enable `inputs` keyword after removing the old API
        *,
        sampling_params: Optional[Union[SamplingParams,
                                        Sequence[SamplingParams]]] = None,
        use_tqdm: bool = True,
266
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
267
268
269
    ) -> List[RequestOutput]:
        ...

nunjunj's avatar
nunjunj committed
270
271
272
273
274
275
    @deprecate_kwargs(
        "prompts",
        "prompt_token_ids",
        is_deprecated=lambda: LLM.DEPRECATE_LEGACY,
        additional_message="Please use the 'inputs' parameter instead.",
    )
276
277
    def generate(
        self,
278
        prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
279
280
281
282
283
                       Optional[Union[str, List[str]]]] = None,
        sampling_params: Optional[Union[SamplingParams,
                                        Sequence[SamplingParams]]] = None,
        prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
        use_tqdm: bool = True,
284
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
285
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
286
287
        guided_options_request: Optional[Union[LLMGuidedOptions,
                                               GuidedDecodingRequest]] = None
288
    ) -> List[RequestOutput]:
Woosuk Kwon's avatar
Woosuk Kwon committed
289
290
        """Generates the completions for the input prompts.

291
        This class automatically batches the given prompts, considering
Woosuk Kwon's avatar
Woosuk Kwon committed
292
293
294
295
        the memory constraint. For the best performance, put all of your prompts
        into a single list and pass it to this method.

        Args:
296
            inputs: A list of inputs to generate completions for.
Woosuk Kwon's avatar
Woosuk Kwon committed
297
            sampling_params: The sampling parameters for text generation. If
nunjunj's avatar
nunjunj committed
298
299
300
                None, we use the default sampling parameters.
                When it is a single value, it is applied to every prompt.
                When it is a list, the list must have the same length as the
301
                prompts and it is paired one by one with the prompt.
Woosuk Kwon's avatar
Woosuk Kwon committed
302
            use_tqdm: Whether to use tqdm to display the progress bar.
303
            lora_request: LoRA request to use for generation, if any.
nunjunj's avatar
nunjunj committed
304
            prompt_adapter_request: Prompt Adapter request to use for
305
                generation, if any.
Woosuk Kwon's avatar
Woosuk Kwon committed
306
307

        Returns:
nunjunj's avatar
nunjunj committed
308
            A list of ``RequestOutput`` objects containing the
309
            generated completions in the same order as the input prompts.
310
311
312
313
314

        Note:
            Using ``prompts`` and ``prompt_token_ids`` as keyword parameters is
            considered legacy and may be deprecated in the future. You should
            instead pass them via the ``inputs`` parameter.
315
        """
316
317
        if self.llm_engine.model_config.embedding_mode:
            raise ValueError(
318
319
                "LLM.generate() is only supported for (conditional) generation "
                "models (XForCausalLM, XForConditionalGeneration).")
320

321
        if prompt_token_ids is not None:
322
323
324
325
326
            inputs = self._convert_v1_inputs(
                prompts=cast(Optional[Union[str, List[str]]], prompts),
                prompt_token_ids=prompt_token_ids,
            )
        else:
327
            inputs = cast(Union[PromptInputs, Sequence[PromptInputs]], prompts)
328

329
330
331
332
333
334
335
336
        if isinstance(guided_options_request, dict):
            if len(guided_options_request) > 1:
                raise ValueError(
                    "You can only use one guided decoding but multiple is "
                    f"specified: {guided_options_request}")
            guided_options_request = GuidedDecodingRequest(
                **guided_options_request)

337
338
339
340
        if sampling_params is None:
            # Use default sampling params.
            sampling_params = SamplingParams()

341
342
343
344
        self._validate_and_add_requests(
            inputs=inputs,
            params=sampling_params,
            lora_request=lora_request,
345
346
            prompt_adapter_request=prompt_adapter_request,
            guided_options=guided_options_request)
347

348
349
        outputs = self._run_engine(use_tqdm=use_tqdm)
        return LLMEngine.validate_outputs(outputs, RequestOutput)
350

nunjunj's avatar
nunjunj committed
351
352
353
354
355
356
357
358
    def chat(
        self,
        messages: List[ChatCompletionMessageParam],
        sampling_params: Optional[Union[SamplingParams,
                                        List[SamplingParams]]] = None,
        use_tqdm: bool = True,
        lora_request: Optional[LoRARequest] = None,
        chat_template: Optional[str] = None,
359
        add_generation_prompt: bool = True,
nunjunj's avatar
nunjunj committed
360
361
    ) -> List[RequestOutput]:
        """
362
        Generate responses for a chat conversation.
nunjunj's avatar
nunjunj committed
363

364
365
366
367
368
369
        The chat conversation is converted into a text prompt using the
        tokenizer and calls the :meth:`generate` method to generate the
        responses.

        Multi-modal inputs can be passed in the same way you would pass them
        to the OpenAI API.
nunjunj's avatar
nunjunj committed
370
371

        Args:
372
373
            messages: A single conversation represented as a list of messages.
                Each message is a dictionary with 'role' and 'content' keys.
nunjunj's avatar
nunjunj committed
374
375
376
377
378
379
380
381
382
            sampling_params: The sampling parameters for text generation.
                If None, we use the default sampling parameters. When it
                is a single value, it is applied to every prompt. When it
                is a list, the list must have the same length as the
                prompts and it is paired one by one with the prompt.
            use_tqdm: Whether to use tqdm to display the progress bar.
            lora_request: LoRA request to use for generation, if any.
            chat_template: The template to use for structuring the chat.
              If not provided, the model's default chat template will be used.
383
            add_generation_prompt: If True, adds a generation template
nunjunj's avatar
nunjunj committed
384
385
386
387
388
389
390
391
392
393
                to each message.

        Returns:
            A list of ``RequestOutput`` objects containing the generated
            responses in the same order as the input messages.
        """

        tokenizer = self.get_tokenizer()
        model_config = self.llm_engine.get_model_config()

394
395
        conversation, mm_data = parse_chat_messages(messages, model_config,
                                                    tokenizer)
nunjunj's avatar
nunjunj committed
396

397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
        prompt: Union[str, List[int]]
        if isinstance(tokenizer, MistralTokenizer):
            prompt = apply_mistral_chat_template(
                tokenizer,
                messages=messages,
                chat_template=chat_template,
                add_generation_prompt=add_generation_prompt,
            )
        else:
            prompt = apply_hf_chat_template(
                tokenizer,
                conversation=conversation,
                chat_template=chat_template,
                add_generation_prompt=add_generation_prompt,
            )
nunjunj's avatar
nunjunj committed
412

413
        inputs: PromptInputs
414
        if is_list_of(prompt, int):
415
416
417
418
            inputs = TokensPrompt(prompt_token_ids=prompt)
        else:
            inputs = TextPrompt(prompt=prompt)

419
420
421
        if mm_data is not None:
            inputs["multi_modal_data"] = mm_data

nunjunj's avatar
nunjunj committed
422
        return self.generate(
423
424
            inputs,
            sampling_params=sampling_params,
nunjunj's avatar
nunjunj committed
425
426
427
428
            use_tqdm=use_tqdm,
            lora_request=lora_request,
        )

429
430
431
432
433
434
435
436
    @overload  # LEGACY: single (prompt + optional token ids)
    def encode(
        self,
        prompts: str,
        pooling_params: Optional[Union[PoolingParams,
                                       Sequence[PoolingParams]]] = None,
        prompt_token_ids: Optional[List[int]] = None,
        use_tqdm: bool = True,
437
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
438
439
    ) -> List[EmbeddingRequestOutput]:
        ...
440

441
    @overload  # LEGACY: multi (prompt + optional token ids)
442
443
    def encode(
        self,
444
        prompts: List[str],
445
        pooling_params: Optional[Union[PoolingParams,
446
                                       Sequence[PoolingParams]]] = None,
447
448
        prompt_token_ids: Optional[List[List[int]]] = None,
        use_tqdm: bool = True,
449
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
450
451
452
453
454
455
456
457
458
459
460
461
    ) -> List[EmbeddingRequestOutput]:
        ...

    @overload  # LEGACY: single (token ids + optional prompt)
    def encode(
        self,
        prompts: Optional[str] = None,
        pooling_params: Optional[Union[PoolingParams,
                                       Sequence[PoolingParams]]] = None,
        *,
        prompt_token_ids: List[int],
        use_tqdm: bool = True,
462
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
463
464
465
466
467
468
469
470
471
472
473
474
    ) -> List[EmbeddingRequestOutput]:
        ...

    @overload  # LEGACY: multi (token ids + optional prompt)
    def encode(
        self,
        prompts: Optional[List[str]] = None,
        pooling_params: Optional[Union[PoolingParams,
                                       Sequence[PoolingParams]]] = None,
        *,
        prompt_token_ids: List[List[int]],
        use_tqdm: bool = True,
475
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
476
477
478
479
480
481
482
483
484
485
    ) -> List[EmbeddingRequestOutput]:
        ...

    @overload  # LEGACY: single or multi token ids [pos-only]
    def encode(
        self,
        prompts: None,
        pooling_params: None,
        prompt_token_ids: Union[List[int], List[List[int]]],
        use_tqdm: bool = True,
486
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
487
488
489
490
491
492
    ) -> List[EmbeddingRequestOutput]:
        ...

    @overload
    def encode(
        self,
493
        inputs: Union[PromptInputs, Sequence[PromptInputs]],
494
495
496
497
498
        /,  # We may enable `inputs` keyword after removing the old API
        *,
        pooling_params: Optional[Union[PoolingParams,
                                       Sequence[PoolingParams]]] = None,
        use_tqdm: bool = True,
499
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
500
501
502
    ) -> List[EmbeddingRequestOutput]:
        ...

nunjunj's avatar
nunjunj committed
503
504
505
506
507
508
    @deprecate_kwargs(
        "prompts",
        "prompt_token_ids",
        is_deprecated=lambda: LLM.DEPRECATE_LEGACY,
        additional_message="Please use the 'inputs' parameter instead.",
    )
509
510
    def encode(
        self,
511
        prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
512
513
514
515
516
                       Optional[Union[str, List[str]]]] = None,
        pooling_params: Optional[Union[PoolingParams,
                                       Sequence[PoolingParams]]] = None,
        prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
        use_tqdm: bool = True,
517
        lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
518
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
519
520
521
    ) -> List[EmbeddingRequestOutput]:
        """Generates the completions for the input prompts.

522
        This class automatically batches the given prompts, considering
523
524
525
526
        the memory constraint. For the best performance, put all of your prompts
        into a single list and pass it to this method.

        Args:
527
            inputs: The inputs to the LLM. You may pass a sequence of inputs for
528
                batch inference. See :class:`~vllm.inputs.PromptInputs`
529
                for more details about the format of each input.
530
531
532
533
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            use_tqdm: Whether to use tqdm to display the progress bar.
            lora_request: LoRA request to use for generation, if any.
nunjunj's avatar
nunjunj committed
534
            prompt_adapter_request: Prompt Adapter request to use for
535
                generation, if any.
536
537
538
539

        Returns:
            A list of `EmbeddingRequestOutput` objects containing the
            generated embeddings in the same order as the input prompts.
540
541
542
543
544

        Note:
            Using ``prompts`` and ``prompt_token_ids`` as keyword parameters is
            considered legacy and may be deprecated in the future. You should
            instead pass them via the ``inputs`` parameter.
545
        """
546
547
548
549
550
        if not self.llm_engine.model_config.embedding_mode:
            raise ValueError(
                "LLM.encode() is only supported for embedding models (XModel)."
            )

551
        if prompt_token_ids is not None:
552
553
554
555
556
            inputs = self._convert_v1_inputs(
                prompts=cast(Optional[Union[str, List[str]]], prompts),
                prompt_token_ids=prompt_token_ids,
            )
        else:
557
            inputs = cast(Union[PromptInputs, Sequence[PromptInputs]], prompts)
558

559
560
561
562
        if pooling_params is None:
            # Use default pooling params.
            pooling_params = PoolingParams()

563
564
565
566
        self._validate_and_add_requests(
            inputs=inputs,
            params=pooling_params,
            lora_request=lora_request,
567
            prompt_adapter_request=prompt_adapter_request,
568
569
        )

570
571
        outputs = self._run_engine(use_tqdm=use_tqdm)
        return LLMEngine.validate_outputs(outputs, EmbeddingRequestOutput)
572

573
574
575
576
577
578
    def start_profile(self) -> None:
        self.llm_engine.start_profile()

    def stop_profile(self) -> None:
        self.llm_engine.stop_profile()

579
580
    # LEGACY
    def _convert_v1_inputs(
581
582
        self,
        prompts: Optional[Union[str, List[str]]],
583
584
585
        prompt_token_ids: Optional[Union[List[int], List[List[int]]]],
    ):
        # skip_tokenizer_init is now checked in engine
586

587
588
589
590
591
592
        if prompts is not None:
            prompts = [p["content"] for p in parse_and_batch_prompt(prompts)]
        if prompt_token_ids is not None:
            prompt_token_ids = [
                p["content"] for p in parse_and_batch_prompt(prompt_token_ids)
            ]
593

594
        num_requests = None
595
596
        if prompts is not None:
            num_requests = len(prompts)
597
598
599
600
601
602
        if prompt_token_ids is not None:
            if (num_requests is not None
                    and num_requests != len(prompt_token_ids)):
                raise ValueError("The lengths of prompts and prompt_token_ids "
                                 "must be the same.")

603
            num_requests = len(prompt_token_ids)
604
605
606
607
608
609
        if num_requests is None:
            raise ValueError("Either prompts or prompt_token_ids must be "
                             "provided.")

        inputs: List[PromptInputs] = []
        for i in range(num_requests):
610
611
            item: PromptInputs

612
            if prompts is not None:
613
614
615
                item = TextPrompt(prompt=prompts[i])
            elif prompt_token_ids is not None:
                item = TokensPrompt(prompt_token_ids=prompt_token_ids[i])
616
            else:
617
                raise AssertionError
618
619
620
621
622
623
624

            inputs.append(item)

        return inputs

    def _validate_and_add_requests(
        self,
625
        inputs: Union[PromptInputs, Sequence[PromptInputs]],
626
627
        params: Union[SamplingParams, Sequence[SamplingParams], PoolingParams,
                      Sequence[PoolingParams]],
628
        lora_request: Optional[Union[Sequence[LoRARequest], LoRARequest]],
629
        prompt_adapter_request: Optional[PromptAdapterRequest],
630
        guided_options: Optional[GuidedDecodingRequest] = None,
631
632
633
634
635
636
    ) -> None:
        if isinstance(inputs, (str, dict)):
            # Convert a single prompt to a list.
            inputs = [inputs]

        num_requests = len(inputs)
637
638
        if isinstance(params, list) and len(params) != num_requests:
            raise ValueError("The lengths of prompts and params "
639
                             "must be the same.")
640
641
642
643
        if isinstance(lora_request,
                      list) and len(lora_request) != num_requests:
            raise ValueError("The lengths of prompts and lora_request "
                             "must be the same.")
644

645
646
647
648
649
650
        for sp in params if isinstance(params, list) else (params, ):
            if isinstance(sp, SamplingParams):
                self._add_guided_processor(sp, guided_options)

                # We only care about the final output
                sp.output_kind = RequestOutputKind.FINAL_ONLY
651

Zhuohan Li's avatar
Zhuohan Li committed
652
        # Add requests to the engine.
653
654
655
656
        for i, request_inputs in enumerate(inputs):
            self._add_request(
                request_inputs,
                params[i] if isinstance(params, Sequence) else params,
657
658
                lora_request=lora_request[i] if isinstance(
                    lora_request, Sequence) else lora_request,
nunjunj's avatar
nunjunj committed
659
660
                prompt_adapter_request=prompt_adapter_request,
            )
661

662
    def _add_request(
nunjunj's avatar
nunjunj committed
663
664
665
        self,
        inputs: PromptInputs,
        params: Union[SamplingParams, PoolingParams],
666
        lora_request: Optional[LoRARequest] = None,
nunjunj's avatar
nunjunj committed
667
        prompt_adapter_request: Optional[PromptAdapterRequest] = None,
668
669
    ) -> None:
        request_id = str(next(self.request_counter))
670
671
672
673
674
        self.llm_engine.add_request(
            request_id,
            inputs,
            params,
            lora_request=lora_request,
nunjunj's avatar
nunjunj committed
675
676
            prompt_adapter_request=prompt_adapter_request,
        )
677

678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
    def _add_guided_processor(
            self,
            params: SamplingParams,
            guided_options: Optional[GuidedDecodingRequest] = None):
        if guided_options:
            if guided_options.guided_decoding_backend is None:
                decoding_config = self.llm_engine.get_decoding_config()
                guided_options.guided_decoding_backend = (
                    decoding_config.guided_decoding_backend)
            guided_logits_processor = get_local_guided_decoding_logits_processor(  #noqa
                guided_options.guided_decoding_backend, guided_options,
                self.get_tokenizer())
            if guided_logits_processor:
                if params.logits_processors is None:
                    params.logits_processors = []
                params.logits_processors.append(guided_logits_processor)
        return params

696
    def _run_engine(
697
            self, *, use_tqdm: bool
698
    ) -> List[Union[RequestOutput, EmbeddingRequestOutput]]:
699
700
        # Initialize tqdm.
        if use_tqdm:
Zhuohan Li's avatar
Zhuohan Li committed
701
            num_requests = self.llm_engine.get_num_unfinished_requests()
702
703
704
705
            pbar = tqdm(
                total=num_requests,
                desc="Processed prompts",
                dynamic_ncols=True,
706
707
                postfix=(f"est. speed input: {0:.2f} toks/s, "
                         f"output: {0:.2f} toks/s"),
708
            )
709

Zhuohan Li's avatar
Zhuohan Li committed
710
        # Run the engine.
711
        outputs: List[Union[RequestOutput, EmbeddingRequestOutput]] = []
712
713
        total_in_toks = 0
        total_out_toks = 0
Zhuohan Li's avatar
Zhuohan Li committed
714
715
        while self.llm_engine.has_unfinished_requests():
            step_outputs = self.llm_engine.step()
716
            for output in step_outputs:
717
                if output.finished:
718
719
                    outputs.append(output)
                    if use_tqdm:
720
721
                        if isinstance(output, RequestOutput):
                            # Calculate tokens only for RequestOutput
722
                            assert output.prompt_token_ids is not None
723
724
725
                            total_in_toks += len(output.prompt_token_ids)
                            in_spd = total_in_toks / pbar.format_dict["elapsed"]
                            total_out_toks += sum(
726
                                len(stp.token_ids) for stp in output.outputs)
nunjunj's avatar
nunjunj committed
727
728
                            out_spd = (total_out_toks /
                                       pbar.format_dict["elapsed"])
729
730
731
                            pbar.postfix = (
                                f"est. speed input: {in_spd:.2f} toks/s, "
                                f"output: {out_spd:.2f} toks/s")
732
                        pbar.update(1)
733

734
735
        if use_tqdm:
            pbar.close()
736
737
738
        # Sort the outputs by request ID.
        # This is necessary because some requests may be finished earlier than
        # its previous requests.
739
        return sorted(outputs, key=lambda x: int(x.request_id))
740
741
742
743
744
745

    def _is_encoder_decoder_model(self):
        return self.llm_engine.is_encoder_decoder_model()

    def _is_embedding_model(self):
        return self.llm_engine.is_embedding_model()