vllm.entrypoints.llm
¶
Classes:
-
LLM–An LLM for generating texts from given prompts and sampling parameters.
LLM
¶
Bases: BeamSearchOfflineMixin, PoolingOfflineMixin, RLOfflineMixin, OfflineInferenceMixin
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¶str) –The name or path of a HuggingFace Transformers model.
-
(tokenizer¶str | None, default:None) –The name or path of a HuggingFace Transformers tokenizer.
-
(tokenizer_mode¶TokenizerMode | str, default:'auto') –The tokenizer mode. See ModelConfig.tokenizer_mode.
-
(skip_tokenizer_init¶bool, default:False) –If true, skip initialization of tokenizer and detokenizer. Expect valid prompt_token_ids and None for prompt from the input.
-
(trust_remote_code¶bool, default:False) –Trust remote code (e.g., from HuggingFace) when downloading the model and tokenizer.
-
(allowed_local_media_path¶str, default:'') –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.
-
(allowed_media_domains¶list[str] | None, default:None) –If set, only media URLs that belong to this domain can be used for multi-modal inputs.
-
(tensor_parallel_size¶int, default:1) –The number of GPUs to use for distributed execution with tensor parallelism.
-
(dtype¶ModelDType, default:'auto') –The data type for the model weights and activations. Currently, we support
float32,float16, andbfloat16. Ifauto, we use thedtypeattribute of the Transformers model's config. However, if thedtypein the config isfloat32, we will usefloat16instead. -
(quantization¶QuantizationMethods | None, default:None) –The method used to quantize the model weights. Currently, we support "awq", "gptq", and "fp8" (experimental). If None, we first check the
quantization_configattribute in the model config file. If that is None, we assume the model weights are not quantized and usedtypeto determine the data type of the weights. -
(revision¶str | None, default:None) –The specific model version to use. It can be a branch name, a tag name, or a commit id.
-
(tokenizer_revision¶str | None, default:None) –The specific tokenizer version to use. It can be a branch name, a tag name, or a commit id.
-
(chat_template¶Path | str | None, default:None) –The chat template to apply.
-
(seed¶int, default:0) –The seed to initialize the random number generator for sampling.
-
(gpu_memory_utilization¶float | None, default:None) –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. Defaults to 1.0 with the extensible KV cache (which sizes the cache from measured memory) and to 0.92 otherwise. With the extensible KV cache (the default on CUDA and ROCm), leave it unset unless the GPU is shared with other processes or something else needs memory that vLLM does not measure; see the "GPU Memory Utilization" section of the optimization guide.
-
(kv_cache_memory_bytes¶int | None, default:None) –Size of KV Cache per GPU in bytes. By default, this is set to None and vllm can automatically infer the kv cache size based on gpu_memory_utilization. However, users may want to manually specify the kv cache memory size. kv_cache_memory_bytes allows more fine-grain control of how much memory gets used when compared with using gpu_memory_utilization. Note that kv_cache_memory_bytes (when not-None) ignores gpu_memory_utilization
-
(enable_extensible_kv_cache¶bool | None, default:None) –Reserve the KV cache address range with device virtual memory and commit physical pages after warmup, so the cache is sized from the memory actually free after CUDA graph capture. Defaults to on for CUDA and ROCm.
-
(cpu_offload_gb¶float, default:0) –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.
-
(offload_group_size¶int, default:0) –Prefetch offloading: Group every N layers together. Offload last
offload_num_in_grouplayers of each group. Default is 0 (disabled). -
(offload_num_in_group¶int, default:1) –Prefetch offloading: Number of layers to offload per group. Default is 1.
-
(offload_prefetch_step¶int, default:1) –Prefetch offloading: Number of layers to prefetch ahead. Higher values hide more latency but use more GPU memory. Default is 1.
-
(offload_params¶set[str] | None, default:None) –Prefetch offloading: Set of parameter name segments to selectively offload. Only parameters whose names contain one of these segments will be offloaded (e.g., {"gate_up_proj", "down_proj"} for MLP weights, or {"w13_weight", "w2_weight"} for MoE expert weights). If None or empty, all parameters are offloaded.
-
(enforce_eager¶bool, default:False) –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.
-
(enable_return_routed_experts¶bool, default:False) –Whether to return routed experts.
-
(disable_custom_all_reduce¶bool, default:False) –See ParallelConfig.
-
(hf_token¶bool | str | None, default:None) –The token to use as HTTP bearer authorization for remote files . If
True, will use the token generated when runninghf auth login(stored in~/.cache/huggingface/token). -
(hf_overrides¶HfOverrides | None, default:None) –If a dictionary, contains arguments to be forwarded to the HuggingFace config. If a callable, it is called to update the HuggingFace config.
-
(mm_processor_kwargs¶dict[str, Any] | None, default:None) –Arguments to be forwarded to the model's processor for multi-modal data, e.g., image processor. Overrides for the multi-modal processor obtained from
AutoProcessor.from_pretrained. The available overrides depend on the model that is being run. For example, for Phi-3-Vision:{"num_crops": 4}. -
(pooler_config¶PoolerConfig | None, default:None) –Initialize non-default pooling config for the pooling model, e.g.,
PoolerConfig(seq_pooling_type="MEAN", use_activation=False). -
(compilation_config¶int | dict[str, Any] | CompilationConfig | None, default:None) –Either an integer or a dictionary. If it is an integer, it is used as the mode of compilation optimization. If it is a dictionary, it can specify the full compilation configuration.
-
(attention_config¶dict[str, Any] | AttentionConfig | None, default:None) –Configuration for attention mechanisms. Can be a dictionary or an AttentionConfig instance. If a dictionary, it will be converted to an AttentionConfig. Allows specifying the attention backend and other attention-related settings.
-
(return_sampling_mask¶bool, default:False) –Return each sampled token's post-processing support set. Requires Model Runner V2 and processed log probabilities.
-
(spec_method¶str | None, default:None) –Top-level alias for
speculative_config["method"]. -
(spec_model¶str | None, default:None) –Top-level alias for
speculative_config["model"]. -
(spec_tokens¶int | None, default:None) –Top-level alias for
speculative_config["num_speculative_tokens"]. -
(**kwargs¶Any, default:{}) –Arguments for
EngineArgs.
Note
This class is intended to be used for offline inference. For online serving, use the AsyncLLMEngine class instead.
Methods:
-
__init__–LLM constructor.
-
__repr__–Return a local model summary without querying workers.
-
apply_model–Run a function directly on the model inside each worker,
-
chat–Generate responses for a chat conversation.
-
collective_rpc–Execute an RPC call on all workers.
-
enqueue–Enqueue prompts for generation without waiting for completion.
-
enqueue_chat–Enqueue chat conversations for generation without waiting.
-
from_engine_args–Create an LLM instance from EngineArgs.
-
generate–Generates the completions for the input prompts.
-
get_metrics–Return a snapshot of aggregated metrics from Prometheus.
-
get_model_inspection–Return a cached transformers-style hierarchical view of the model.
-
get_world_size–Get the world size from the parallel config.
-
release_kv_cache_memory–Release the GPU physical memory backing the KV cache.
-
sleep–Put the engine to sleep. The engine should not process any requests.
-
start_profile–Start profiling with optional per-session overrides.
-
wait_for_completion–Wait for all enqueued requests to complete and return results.
-
wake_up–Wake up the engine from sleep mode. See the sleep
__init__(model, *, runner='auto', convert='auto', tokenizer=None, tokenizer_mode='auto', skip_tokenizer_init=False, trust_remote_code=False, allowed_local_media_path='', allowed_media_domains=None, tensor_parallel_size=1, dtype='auto', quantization=None, revision=None, tokenizer_revision=None, chat_template=None, seed=0, gpu_memory_utilization=None, cpu_offload_gb=0, offload_group_size=0, offload_num_in_group=1, offload_prefetch_step=1, offload_params=None, enforce_eager=False, enable_return_routed_experts=False, return_sampling_mask=False, disable_custom_all_reduce=False, hf_token=None, hf_overrides=None, mm_processor_kwargs=None, pooler_config=None, structured_outputs_config=None, profiler_config=None, attention_config=None, kv_cache_memory_bytes=None, enable_extensible_kv_cache=None, compilation_config=None, quantization_config=None, logits_processors=None, spec_method=None, spec_model=None, spec_tokens=None, **kwargs)
¶
LLM constructor.
__repr__()
¶
Return a local model summary without querying workers.
apply_model(func)
¶
Run a function directly on the model inside each worker, returning the result for each of them.
Warning
To reduce the overhead of data transfer, avoid returning large arrays or tensors from this method. If you must return them, make sure you move them to CPU first to avoid taking up additional VRAM!
chat(messages, sampling_params=None, use_tqdm=True, lora_request=None, priority=None, chat_template=None, chat_template_content_format='auto', add_generation_prompt=True, continue_final_message=False, tools=None, chat_template_kwargs=None, tokenization_kwargs=None, mm_processor_kwargs=None)
¶
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¶list[ChatCompletionMessageParam] | Sequence[list[ChatCompletionMessageParam]]) –A sequence 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¶SamplingParams | Sequence[SamplingParams] | None, default:None) –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¶bool | Callable[..., tqdm], default:True) –If
True, shows a tqdm progress bar. If a callable (e.g.,functools.partial(tqdm, leave=False)), it is used to create the progress bar. IfFalse, no progress bar is created. -
(lora_request¶Sequence[LoRARequest] | LoRARequest | None, default:None) –LoRA request to use for generation, if any.
-
(priority¶int | Sequence[int] | None, default:None) –The priority of the requests, if any. Only applicable when priority scheduling policy is enabled. 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.
-
(chat_template¶str | None, default:None) –The template to use for structuring the chat. If not provided, the model's default chat template will be used.
-
(chat_template_content_format¶ChatTemplateContentFormatOption, default:'auto') –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?"}]
- "string" will render the content as a string.
Example:
-
(add_generation_prompt¶bool, default:True) –If True, adds a generation template to each message.
-
(continue_final_message¶bool, default:False) –If True, continues the final message in the conversation instead of starting a new one. Cannot be
Trueifadd_generation_promptis alsoTrue. -
(chat_template_kwargs¶dict[str, Any] | None, default:None) –Additional kwargs to pass to the chat template.
-
(tokenization_kwargs¶dict[str, Any] | None, default:None) –Overrides for
tokenizer.encode. -
(mm_processor_kwargs¶dict[str, Any] | None, default:None) –Overrides for
processor.__call__. -
(tools¶list[dict[str, Any]] | None, default:None) –Tools to make available to the model, if any.
Returns:
-
list[RequestOutput]–A list of
RequestOutputobjects containing the generated -
list[RequestOutput]–responses in the same order as the input messages.
collective_rpc(method, timeout=None, args=(), kwargs=None)
¶
Execute an RPC call on all workers.
Parameters:
-
(method¶str | Callable[..., _R]) –Name of the worker method to execute, or a callable that is serialized and sent to all workers to execute.
If the method is a callable, it should accept an additional
selfargument, in addition to the arguments passed inargsandkwargs. Theselfargument will be the worker object. -
(timeout¶float | None, default:None) –Maximum time in seconds to wait for execution. Raises a
TimeoutErroron timeout.Nonemeans wait indefinitely. -
(args¶tuple, default:()) –Positional arguments to pass to the worker method.
-
(kwargs¶dict[str, Any] | None, default:None) –Keyword arguments to pass to the worker method.
Returns:
-
list[_R]–A list containing the results from each worker.
Note
It is recommended to use this API to only pass control messages, and set up data-plane communication to pass data.
enqueue(prompts, sampling_params=None, lora_request=None, priority=None, use_tqdm=True, tokenization_kwargs=None, mm_processor_kwargs=None)
¶
Enqueue prompts for generation without waiting for completion.
This method adds requests to the engine queue but does not start processing them. Use wait_for_completion() to process the queued requests and get results.
Parameters:
-
(prompts¶PromptType | Sequence[PromptType]) –The prompts to the LLM. See generate() for details.
-
(sampling_params¶SamplingParams | Sequence[SamplingParams] | None, default:None) –The sampling parameters for text generation.
-
(lora_request¶Sequence[LoRARequest] | LoRARequest | None, default:None) –LoRA request to use for generation, if any.
-
(priority¶int | Sequence[int] | None, default:None) –The priority of the requests, if any. Only applicable when priority scheduling policy is enabled. 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¶bool | Callable[..., tqdm], default:True) –If True, shows a tqdm progress bar while adding requests.
-
(tokenization_kwargs¶dict[str, Any] | None, default:None) –Overrides for
tokenizer.encode. -
(mm_processor_kwargs¶dict[str, Any] | None, default:None) –Overrides for
processor.__call__.
Returns:
enqueue_chat(messages, sampling_params=None, use_tqdm=True, lora_request=None, priority=None, chat_template=None, chat_template_content_format='auto', add_generation_prompt=True, continue_final_message=False, tools=None, chat_template_kwargs=None, tokenization_kwargs=None, mm_processor_kwargs=None)
¶
Enqueue chat conversations for generation without waiting.
This method renders chat conversations and adds the resulting requests to the engine queue. Use wait_for_completion() to get results. To guarantee that all requests are queued before scheduling starts, pause scheduling with sleep(level=0) before calling this method and resume it with wake_up(tags=["scheduling"]) afterward.
Parameters:
-
(messages¶list[ChatCompletionMessageParam] | Sequence[list[ChatCompletionMessageParam]]) –A sequence of conversations or a single conversation. Each conversation is represented as a list of messages.
-
(sampling_params¶SamplingParams | Sequence[SamplingParams] | None, default:None) –The sampling parameters for text generation. If None, we use the default sampling parameters.
-
(use_tqdm¶bool | Callable[..., tqdm], default:True) –If
True, shows a tqdm progress bar while rendering conversations. -
(lora_request¶Sequence[LoRARequest] | LoRARequest | None, default:None) –LoRA request to use for generation, if any.
-
(priority¶int | Sequence[int] | None, default:None) –The priority of the requests, if any. Only applicable when priority scheduling policy is enabled. 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.
-
(chat_template¶str | None, default:None) –The template to use for structuring the chat.
-
(chat_template_content_format¶ChatTemplateContentFormatOption, default:'auto') –The format to render message content.
-
(add_generation_prompt¶bool, default:True) –If True, adds a generation template to each message.
-
(continue_final_message¶bool, default:False) –If True, continues the final message in the conversation instead of starting a new one.
-
(tools¶list[dict[str, Any]] | None, default:None) –Tools to make available to the model, if any.
-
(chat_template_kwargs¶dict[str, Any] | None, default:None) –Additional kwargs to pass to the chat template.
-
(tokenization_kwargs¶dict[str, Any] | None, default:None) –Overrides for
tokenizer.encode. -
(mm_processor_kwargs¶dict[str, Any] | None, default:None) –Overrides for
processor.__call__.
Returns:
from_engine_args(engine_args)
classmethod
¶
Create an LLM instance from EngineArgs.
generate(prompts, sampling_params=None, *, use_tqdm=True, lora_request=None, priority=None, tokenization_kwargs=None, mm_processor_kwargs=None)
¶
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¶PromptType | Sequence[PromptType]) –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 prompt.
-
(sampling_params¶SamplingParams | Sequence[SamplingParams] | None, default:None) –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¶bool | Callable[..., tqdm], default:True) –If
True, shows a tqdm progress bar. If a callable (e.g.,functools.partial(tqdm, leave=False)), it is used to create the progress bar. IfFalse, no progress bar is created. -
(lora_request¶Sequence[LoRARequest] | LoRARequest | None, default:None) –LoRA request to use for generation, if any.
-
(priority¶int | Sequence[int] | None, default:None) –The priority of the requests, if any. Only applicable when priority scheduling policy is enabled. 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.
-
(tokenization_kwargs¶dict[str, Any] | None, default:None) –Overrides for
tokenizer.encode. -
(mm_processor_kwargs¶dict[str, Any] | None, default:None) –Overrides for
processor.__call__.
Returns:
-
list[RequestOutput]–A list of
RequestOutputobjects containing the -
list[RequestOutput]–generated completions in the same order as the input prompts.
get_metrics()
¶
get_model_inspection()
¶
Return a cached transformers-style hierarchical view of the model.
get_world_size(include_dp=True)
¶
release_kv_cache_memory(reset_connector=True)
¶
sleep(level=1, mode='abort', reset_connector=True)
¶
Put the engine to sleep. The engine should not process any requests.
The caller should guarantee that no requests are being processed
during the sleep period, before wake_up is called.
Parameters:
-
(level¶int, default:1) –The sleep level. - Level 0: Pause scheduling but continue accepting requests. Requests are queued but not processed. - Level 1: Offload model weights to CPU, discard KV cache. The content of kv cache is forgotten. Good for sleeping and waking up the engine to run the same model again. Please make sure there's enough CPU memory to store the model weights. - Level 2: Discard model parameters and KV cache, and offload the rest of the model's GPU state to CPU. Good for sleeping and waking up the engine to update the model's weights, where the previous weights are not needed. It reduces CPU memory pressure.
-
(mode¶PauseMode, default:'abort') –How to handle any existing requests, can be "abort", "wait", or "keep".
-
(reset_connector¶bool, default:True) –Also reset the KV connector's cache, such as blocks offloaded to CPU. Set
Falseonly if the weights do not change beforewake_up. Ignored at level 0.
start_profile(profile_prefix=None, *, delay_iterations=None, max_iterations=None, profiler_kwargs=None)
¶
Start profiling with optional per-session overrides.
Parameters:
-
(profile_prefix¶str | None, default:None) –Optional prefix for the trace file names. If provided, trace files will be named as "
_dp _pp _tp ". If not provided, default naming will be used. -
(delay_iterations¶int | None, default:None) –Optional number of worker iterations to skip before profiling starts.
-
(max_iterations¶int | None, default:None) –Optional maximum number of worker iterations to profile. Zero means no limit.
-
(profiler_kwargs¶dict[str, Any] | None, default:None) –Optional dictionary of keyword arguments to pass to the underlying profiler.
wait_for_completion(output_type=None, *, use_tqdm=True)
¶
Wait for all enqueued requests to complete and return results.
This method processes all requests currently in the engine queue and returns their outputs. Use after enqueue() to get results.
Parameters:
-
(output_type¶type[Any] | tuple[type[Any], ...] | None, default:None) –The expected output type(s). If not provided, accepts both RequestOutput and PoolingRequestOutput.
-
(use_tqdm¶bool | Callable[..., tqdm], default:True) –If True, shows a tqdm progress bar.
Returns:
wake_up(tags=None)
¶
Wake up the engine from sleep mode. See the sleep method for more details.
Parameters:
-
(tags¶list[str] | None, default:None) –An optional list of tags to reallocate the engine memory for specific memory allocations. Values must be in
("weights", "kv_cache", "scheduling"). If None, all memory is reallocated. wake_up should be called with all tags (or None) before the engine is used again. Use tags=["scheduling"] to resume from level 0 sleep.
Returns:
-
bool–Whether the engine is fully awake.