LLM Class#

class vllm.LLM(model: str, tokenizer: str | None = None, tokenizer_mode: str = 'auto', skip_tokenizer_init: bool = False, trust_remote_code: bool = False, allowed_local_media_path: str = '', tensor_parallel_size: int = 1, dtype: str = 'auto', quantization: str | None = None, revision: str | None = None, tokenizer_revision: str | None = None, seed: int = 0, gpu_memory_utilization: float = 0.9, swap_space: float = 4, cpu_offload_gb: float = 0, enforce_eager: bool | None = None, max_seq_len_to_capture: int = 8192, disable_custom_all_reduce: bool = False, disable_async_output_proc: bool = False, hf_overrides: Dict[str, Any] | Callable[[transformers.PretrainedConfig], transformers.PretrainedConfig] | None = None, mm_processor_kwargs: Dict[str, Any] | None = None, task: Literal['auto', 'generate', 'embedding', 'embed', 'classify', 'score', 'reward'] = 'auto', override_pooler_config: PoolerConfig | None = None, compilation_config: int | Dict[str, Any] | None = None, **kwargs)[source][source]#

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.

Parameters:
  • model – The name or path of a HuggingFace Transformers model.

  • tokenizer – The name or path of a HuggingFace Transformers tokenizer.

  • tokenizer_mode – The tokenizer mode. “auto” will use the fast tokenizer if available, and “slow” will always use the slow tokenizer.

  • skip_tokenizer_init – If true, skip initialization of tokenizer and detokenizer. Expect valid prompt_token_ids and None for prompt from the input.

  • trust_remote_code – Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.

  • allowed_local_media_path – Allowing API requests to read local images or videos from directories specified by the server file system. This is a security risk. Should only be enabled in trusted environments.

  • 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, 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.

  • quantization – The method used to quantize the model weights. Currently, we support “awq”, “gptq”, and “fp8” (experimental). 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.

  • revision – The specific model version to use. It can be a branch name, a tag name, or a commit id.

  • tokenizer_revision – The specific tokenizer version to use. It can be a branch name, a tag name, or a commit id.

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

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

  • 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_seq_len_to_capture – Maximum sequence len covered by CUDA graphs. When a sequence has context length larger than this, we fall back to eager mode. Additionally for encoder-decoder models, if the sequence length of the encoder input is larger than this, we fall back to the eager mode.

  • disable_custom_all_reduce – See ParallelConfig

  • disable_async_output_proc – Disable async output processing. This may result in lower performance.

  • hf_overrides – If a dictionary, contains arguments to be forwarded to the HuggingFace config. If a callable, it is called to update the HuggingFace config.

  • compilation_config – Either an integer or a dictionary. If it is an integer, it is used as the level of compilation optimization. If it is a dictionary, it can specify the full compilation configuration.

  • **kwargs – Arguments for EngineArgs. (See Engine Arguments)

Note

This class is intended to be used for offline inference. For online serving, use the AsyncLLMEngine class instead.

DEPRECATE_INIT_POSARGS: ClassVar[bool] = True[source]#

A flag to toggle whether to deprecate positional arguments in LLM.__init__().

DEPRECATE_LEGACY: ClassVar[bool] = True[source]#

A flag to toggle whether to deprecate the legacy generate/encode API.

Generate sequences using beam search.

Parameters:
  • prompts – A list of prompts. Each prompt can be a string or a list of token IDs.

  • params – The beam search parameters.

TODO: how does beam search work together with length penalty, frequency penalty, and stopping criteria, etc.?

chat(messages: List[ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam | ChatCompletionToolMessageParam | ChatCompletionFunctionMessageParam | CustomChatCompletionMessageParam] | List[List[ChatCompletionDeveloperMessageParam | ChatCompletionSystemMessageParam | ChatCompletionUserMessageParam | ChatCompletionAssistantMessageParam | ChatCompletionToolMessageParam | ChatCompletionFunctionMessageParam | CustomChatCompletionMessageParam]], sampling_params: SamplingParams | List[SamplingParams] | None = None, use_tqdm: bool = True, lora_request: LoRARequest | None = None, chat_template: str | None = None, chat_template_content_format: Literal['auto', 'string', 'openai'] = 'auto', add_generation_prompt: bool = True, continue_final_message: bool = False, tools: List[Dict[str, Any]] | None = None, mm_processor_kwargs: Dict[str, Any] | None = None) List[RequestOutput][source][source]#

Generate responses for a chat conversation.

The chat conversation is converted into a text prompt using the tokenizer and calls the generate() method to generate the responses.

Multi-modal inputs can be passed in the same way you would pass them to the OpenAI API.

Parameters:
  • messages

    A list of conversations or a single conversation.

    • Each conversation is represented as a list of messages.

    • Each message is a dictionary with ‘role’ and ‘content’ keys.

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

  • chat_template_content_format

    The format to render message content.

    • ”string” will render the content as a string. Example: "Who are you?"

    • ”openai” will render the content as a list of dictionaries, similar to OpenAI schema. Example: [{"type": "text", "text": "Who are you?"}]

  • add_generation_prompt – If True, adds a generation template to each message.

  • continue_final_message – If True, continues the final message in the conversation instead of starting a new one. Cannot be True if add_generation_prompt is also True.

  • mm_processor_kwargs – Multimodal processor kwarg overrides for this chat request. Only used for offline requests.

Returns:

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

classify(prompts: str | TextPrompt | TokensPrompt | ExplicitEncoderDecoderPrompt | Sequence[str | TextPrompt | TokensPrompt | ExplicitEncoderDecoderPrompt], /, *, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[ClassificationRequestOutput][source][source]#

Generate class logits for each prompt.

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

Parameters:
  • prompts – The prompts to the LLM. You may pass a sequence of prompts for batch inference. See PromptType for more details about the format of each prompts.

  • use_tqdm – Whether to use tqdm to display the progress bar.

  • lora_request – LoRA request to use for generation, if any.

  • prompt_adapter_request – Prompt Adapter request to use for generation, if any.

Returns:

A list of ClassificationRequestOutput objects containing the embedding vectors in the same order as the input prompts.

embed(prompts: str | TextPrompt | TokensPrompt | ExplicitEncoderDecoderPrompt | Sequence[str | TextPrompt | TokensPrompt | ExplicitEncoderDecoderPrompt], /, *, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[EmbeddingRequestOutput][source][source]#

Generate an embedding vector for each prompt.

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

Parameters:
  • prompts – The prompts to the LLM. You may pass a sequence of prompts for batch inference. See PromptType for more details about the format of each prompts.

  • use_tqdm – Whether to use tqdm to display the progress bar.

  • lora_request – LoRA request to use for generation, if any.

  • prompt_adapter_request – Prompt Adapter request to use for generation, if any.

Returns:

A list of EmbeddingRequestOutput objects containing the embedding vectors in the same order as the input prompts.

encode(prompts: PromptType | Sequence[PromptType], /, pooling_params: PoolingParams | Sequence[PoolingParams] | None = None, *, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[PoolingRequestOutput][source][source]#
encode(prompts: str, pooling_params: PoolingParams | Sequence[PoolingParams] | None = None, prompt_token_ids: List[int] | None = None, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[PoolingRequestOutput]
encode(prompts: List[str], pooling_params: PoolingParams | Sequence[PoolingParams] | None = None, prompt_token_ids: List[List[int]] | None = None, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[PoolingRequestOutput]
encode(prompts: str | None = None, pooling_params: PoolingParams | Sequence[PoolingParams] | None = None, *, prompt_token_ids: List[int], use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[PoolingRequestOutput]
encode(prompts: List[str] | None = None, pooling_params: PoolingParams | Sequence[PoolingParams] | None = None, *, prompt_token_ids: List[List[int]], use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[PoolingRequestOutput]
encode(prompts: None, pooling_params: None, prompt_token_ids: List[int] | List[List[int]], use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[PoolingRequestOutput]

Apply pooling to the hidden states corresponding to the input prompts.

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

Parameters:
  • prompts – The prompts to the LLM. You may pass a sequence of prompts for batch inference. See PromptType for more details about the format of each prompts.

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

  • prompt_adapter_request – Prompt Adapter request to use for generation, if any.

Returns:

A list of PoolingRequestOutput objects containing the pooled hidden states in the same order as the input prompts.

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.

generate(prompts: PromptType | Sequence[PromptType], /, sampling_params: SamplingParams | Sequence[SamplingParams] | None = None, *, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None, guided_options_request: LLMGuidedOptions | GuidedDecodingRequest | None = None) List[RequestOutput][source][source]#
generate(prompts: str, sampling_params: SamplingParams | List[SamplingParams] | None = None, prompt_token_ids: List[int] | None = None, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None, guided_options_request: LLMGuidedOptions | GuidedDecodingRequest | None = None) List[RequestOutput]
generate(prompts: List[str], sampling_params: SamplingParams | List[SamplingParams] | None = None, prompt_token_ids: List[List[int]] | None = None, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None, guided_options_request: LLMGuidedOptions | GuidedDecodingRequest | None = None) List[RequestOutput]
generate(prompts: str | None = None, sampling_params: SamplingParams | List[SamplingParams] | None = None, *, prompt_token_ids: List[int], use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None, guided_options_request: LLMGuidedOptions | GuidedDecodingRequest | None = None) List[RequestOutput]
generate(prompts: List[str] | None = None, sampling_params: SamplingParams | List[SamplingParams] | None = None, *, prompt_token_ids: List[List[int]], use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None, guided_options_request: LLMGuidedOptions | GuidedDecodingRequest | None = None) List[RequestOutput]
generate(prompts: None, sampling_params: None, prompt_token_ids: List[int] | List[List[int]], use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None, guided_options_request: LLMGuidedOptions | GuidedDecodingRequest | None = None) List[RequestOutput]

Generates the completions for the input prompts.

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

Parameters:
  • prompts – The prompts to the LLM. You may pass a sequence of prompts for batch inference. See PromptType for more details about the format of each prompts.

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

  • prompt_adapter_request – Prompt Adapter request to use for generation, if any.

  • priority – The priority of the requests, if any. Only applicable when priority scheduling policy is enabled.

Returns:

A list of RequestOutput objects containing the generated completions in the same order as the input prompts.

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.

score(text_1: str | TextPrompt | TokensPrompt | Sequence[str | TextPrompt | TokensPrompt], text_2: str | TextPrompt | TokensPrompt | Sequence[str | TextPrompt | TokensPrompt], /, *, truncate_prompt_tokens: int | None = None, use_tqdm: bool = True, lora_request: List[LoRARequest] | LoRARequest | None = None, prompt_adapter_request: PromptAdapterRequest | None = None) List[ScoringRequestOutput][source][source]#

Generate similarity scores for all pairs <text,text_pair>.

The inputs can be 1 -> 1, 1 -> N or N -> N. In the 1 - N case the text_1 sentence will be replicated N times to pair with the text_2 sentences. The input pairs are used to build a list of prompts for the cross encoder model. This class automatically batches the prompts, considering the memory constraint. For the best performance, put all of your texts into a single list and pass it to this method.

Parameters:
  • text_1 – can be a single prompt or a list of prompts, in which case it has to have the same length as the text_2 list

  • text_2 – The texts to pair with the query to form the input to the LLM. See PromptType for more details about the format of each prompts.

  • use_tqdm – Whether to use tqdm to display the progress bar.

  • lora_request – LoRA request to use for generation, if any.

  • prompt_adapter_request – Prompt Adapter request to use for generation, if any.

Returns:

A list of ScoringRequestOutput objects containing the generated scores in the same order as the input prompts.