o
    
۾iC                    @   s  d dl Z d dlZd dlmZmZ d dlmZmZmZ d dl	Z	d dl
mZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZ d dlmZmZmZmZmZmZ d d	lmZ d d
l m!Z!m"Z"m#Z#m$Z$m%Z% d dl&m'Z'm(Z( d dl)m*Z* d dl+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7 d dl8m9Z9m:Z:m;Z;m<Z<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZC d dlDmEZEmFZFmGZGmHZHmIZI d dlJmKZK d dlLmMZM d dlNmOZOmPZPmQZQ d dlRmSZSmTZT d dlUmVZVmWZWmXZXmYZY d dlZm[Z[m\Z\m]Z] d dl^m_Z_ d dl`maZa d dlbmcZc d dldmeZe d dlfmgZgmhZh d d limjZj d d!lkmlZl d d"lmmnZn er1d d#lompZp e?eqZred$ed%ZsG d&d' d'ZtdS )(    N)CallableSequence)TYPE_CHECKINGAnycast)ValidationError)tqdm)TypeVar)BeamSearchInstanceBeamSearchOutputBeamSearchSequencecreate_sort_beams_key_function)AttentionConfigCompilationConfigPoolerConfigProfilerConfigStructuredOutputsConfigis_init_field)CompilationMode)ConvertOptionHfOverrides
ModelDTypeRunnerOptionTokenizerMode)WeightTransferInitRequestWeightTransferUpdateRequest)
EngineArgs)ChatCompletionMessageParamChatTemplateContentFormatOption)	ScoreDataScoreMultiModalParam_cosine_similaritycompress_token_type_idscompute_maxsim_scoreget_score_promptvalidate_score_input)log_non_default_args)
DataPrompt
PromptTypeSingletonPrompt
TextPromptTokensPrompt)init_logger)LoRARequest)QuantizationMethods)ClassificationRequestOutputEmbeddingRequestOutputPoolingRequestOutputRequestOutputScoringRequestOutput)current_platform)PoolingParams)
ChatParamsTokenizeParamsmerge_kwargs)
DictPrompt	TokPrompt)conversation_to_seqextract_prompt_componentsparse_model_promptprompt_to_seq)BeamSearchParamsRequestOutputKindSamplingParams)PoolingTask)TokenizerLike)MistralTokenizer)UsageContext)as_iter
is_list_of)Counter)	LLMEngine)LogitsProcessor)Metric_R)defaultc                C   @   s  e Zd ZdZdddddddddddddddd	ddddddddddddddd
dededededB deeB dededede	e dB de
dededB dedB dedB de
dedededededed eeB dB d!edB d"eeef dB d#edB d$eeef eB dB d%eeef eB dB d&eeef eB dB d'e
dB d(e
eeef B eB dB d)e	eee B  dB d*ed+dfBd,d-Zd+efd.d/Zdd1ed+e
fd2d3Zdd4d5Zd+efd6d7Z	dd0dddd8d9ee e B d:ee e B dB d;ee!d<e"f B d=e	e# e#B dB d>e	e
 dB d?eeef dB d+e	e$ fd@dAZ%d9e e&e'B  d=e	e# e#B dB fdBdCZ(dDe&e'B d=e#dB dEeeef dB fdFdGZ)		H	ddIee!d<e*f B dJedB dKe+d*eeef dB d+e	e* f
dLdMZ,dNe!e-j.ge*f d+e	e* fdOdPZ/d=e	e# e#B dB d9e	e0e1B  d+e	e#dB  fdQdRZ2			dd9e	e0e1B  dSe3d=e	e# e#B dB d;edTe
dB d+e	e4 fdUdVZ5d?eeef dB fdWdXZ6	dd9e e d?eeef dB d+e e&e'B  fdYdZZ7d?eeef dB fd[d\Z8				0				dd]e e	e9  d^edB d_e:d`eeef dB daedbedce	eeef  dB d?eeef dB d"eeef dB d+e e' fdddeZ;		0				0					ddfe	e9 e e	e9  B d:ee e B dB d;ee!d<e"f B d=e#dB d^edB d_e:daedbedce	eeef  dB d`eeef dB d?eeef dB d"eeef dB d+e	e$ fdgdhZ<	ddd0ddddid9ee e B e=B dje>e e> B dB dke
dB d;ee!d<e"f B d=e	e# e#B dB dle?dB d?eeef dB d+e	e@ fdmdnZAdd0ddddod9ee e B dke
dB d;ee!d<e"f B dje>e e> B dB d=e	e# e#B dB d?eeef dB d+e	eB fdpdqZCdd0dddrd9ee e B dje>e e> B dB d;ee!d<e"f B d=e	e# e#B dB d?eeef dB d+e	eD fdsdtZEddd0dddud9ee e B dje>e e> B dB dke
dB d;ee!d<e"f B d=e	e# e#B dB d?eeef dB d+e	e@ fdvdwZFdxe	eG dye	eG d;ee!d<e"f B dje>dB d=e	e# e#B dB d?eeef d+e	eH fdzd{ZIdxe	eG dye	eG d;ee!d<e"f B dje>dB d=e	e# e#B dB d?eeef d+e	eH fd|d}ZJdxe	eG dye	eG d;ee!d<e"f B dje>dB d=e	e# e#B dB d?eeef d~edB d+e	eH fddZKd0ddddddxeLe eL B eMB e	eM B dyeLe eL B eMB e	eM B d;ee!d<e"f B dje>dB d=e	e# e#B dB d?eeef dB d^edB d+e	eH fddZNdddZOdddZP	ddeded+efddZQdde
fddZRdde	e dB fddZSd+e	d fddZTdSee>B e ee>B  B de
d+e ee>B  fddZUd=e#dB e e#dB  B de
d+e e#dB  fddZVd>e	e
 dB de
d+e e
 fddZWd0dddd8d9ee e B dSee>B e ee>B  B d;ee!d<e"f B d=e	e# e#B dB d>e	e
 dB d?eeef dB fddZXd0dddd0dddddd
dfe	e9 e e	e9  B dSee>B e ee>B  B d;ee!d<e"f B d=e#dB d^edB d_e:daedbedce	eeef  dB d`eeef dB d?eeef dB d"eeef dB fddZYd0dddd9e e&e'B  dSee>B e ee>B  B d;ee!d<e"f B d=e e#dB  e#B dB d?eeef dB d>e	e
 dB d+dfddZZ			ddDee&B e'B dSee>B d=e#dB d?eeef dB d>e
d+efddZ[d0dd;ee!d<e"f B d+e	e$e@B  fddZ\de]eB d+dfddZ^de_eB d+dfddZ`d+efddZadS )LLMa  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.
        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.
        allowed_media_domains: If set, only media URLs that belong to this
            domain can be used for multi-modal inputs.
        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 `dtype` attribute of the Transformers model's config. However,
            if the `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.
        kv_cache_memory_bytes: 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
        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.
            Noting that `best_of` is only supported in V0. 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.
        enable_return_routed_experts: Whether to return routed experts.
        disable_custom_all_reduce: See
            [ParallelConfig][vllm.config.ParallelConfig].
        hf_token: The token to use as HTTP bearer authorization for remote files
            . If `True`, will use the token generated when running
            `hf auth login` (stored in `~/.cache/huggingface/token`).
        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.
        mm_processor_kwargs: 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: Initialize non-default pooling config for the pooling model,
            e.g., `PoolerConfig(seq_pooling_type="MEAN", use_activation=False)`.
        compilation_config: 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: 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.
        **kwargs: Arguments for [`EngineArgs`][vllm.EngineArgs].

    Note:
        This class is intended to be used for offline inference. For online
        serving, use the [AsyncLLMEngine][vllm.AsyncLLMEngine] class instead.
    autoNF    r   g?   )runnerconvert	tokenizertokenizer_modeskip_tokenizer_inittrust_remote_codeallowed_local_media_pathallowed_media_domainstensor_parallel_sizedtypequantizationrevisiontokenizer_revisionseedgpu_memory_utilization
swap_spacecpu_offload_gbenforce_eagerenable_return_routed_expertsdisable_custom_all_reducehf_tokenhf_overridesmm_processor_kwargspooler_configstructured_outputs_configprofiler_configattention_configkv_cache_memory_bytescompilation_configlogits_processorsmodelrS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   kwargsreturnc          .   
   K   s  d| vrd| d< d| v r| d }!t |!trt|!| d< d| v rXt | d trXddlm}" | d }#z|"d7i |#| d< W n tyW }$ zt	d|#|$ t
d|$ |$d	}$~$ww |d	u r^i }d
tdtt dtfdd}%t |trxtt|d}&n|%|t}&|%|t}'|%|t}(|%|t})t| dd}*| d}+|*dkr|+dkst st
d|* dtd7i d|d|d|d|d|d|d|d|d|	d|
d |d!|d"|d#|d$|d%|d&|d'|d(|d)|d*|d+|d,|d-|d.|d/|d0|'d1|(d2|)d3|&d4|| },t|, tj|,tjd5| _t| j| _t | _d	| _ | j! }-t"d6|- |-| _#| jj$| _$| jj%| _%| jj&| _&d	| _'d	S )8zLLM constructor.disable_log_statsT
worker_clskv_transfer_configr   )KVTransferConfigz[Failed to convert 'kv_transfer_config' dict to KVTransferConfig object. Dict: %s. Error: %sz'Invalid 'kv_transfer_config' provided: Nvalueclsrs   c                    s<   | du r  S t | tr di  fdd|  D S | S )z0Convert dict/None/instance to a config instance.Nc                    s    i | ]\}}t  |r||qS  )r   ).0kvry   rz   H/home/ubuntu/.local/lib/python3.10/site-packages/vllm/entrypoints/llm.py
<dictcomp>  s     z6LLM.__init__.<locals>._make_config.<locals>.<dictcomp>rz   )
isinstancedictitems)rx   ry   rz   r~   r   _make_config  s
   
 z"LLM.__init__.<locals>._make_config)modedata_parallel_sizerQ   distributed_executor_backendexternal_launcherzLLM(data_parallel_size=z) is not supported for single-process usage and may hang. Please use the explicit multi-process data-parallel example at 'examples/offline_inference/data_parallel.py'.rq   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rn   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   ro   rp   )engine_argsusage_contextzSupported tasks: %srz   )(r   typecloudpickledumpsr   vllm.config.kv_transferrw   r   loggererror
ValueErrorr   rL   intr   r   r   r   r   getr4   is_tpur   r&   rI   from_engine_argsrE   	LLM_CLASS
llm_engineengine_classrH   request_counterdefault_sampling_paramsget_supported_tasksinfosupported_tasksmodel_configinput_processorio_processor_cached_repr).selfrq   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rr   ru   rw   raw_config_dicter   compilation_config_instancestructured_outputs_instanceprofiler_config_instanceattention_config_instance_dp_size_distributed_executor_backendr   r   rz   rz   r   __init__   s   (






	
#




zLLM.__init__c                 C   
   | j  S N)r   get_tokenizerr   rz   rz   r   r   m  s   
zLLM.get_tokenizerT
include_dpc                 C   s   | j jj}|r
|jS |jS )a  Get the world size from the parallel config.

        Args:
            include_dp: If True (default), returns the world size including
                data parallelism (TP * PP * DP). If False, returns the world
                size without data parallelism (TP * PP).

        Returns:
            The world size (tensor_parallel_size * pipeline_parallel_size),
            optionally multiplied by data_parallel_size if include_dp is True.
        )r   vllm_configparallel_configworld_size_across_dp
world_size)r   r   r   rz   rz   r   get_world_sizep  s   
zLLM.get_world_sizec                 C   s   | j   | j  d S r   )r   clear_mm_cacher   reset_mm_cacher   rz   rz   r   r     s   
zLLM.reset_mm_cachec                 C   s4   | j d u r| j | _ | j rtjdi | j S t S )Nrz   )r   r   get_diff_sampling_paramrA   from_optionalr   rz   rz   r   get_default_sampling_params  s
   
zLLM.get_default_sampling_params)use_tqdmlora_requestprioritytokenization_kwargspromptssampling_paramsr   .r   r   r   c          
      C   sP   | j }|j}|dkrtd|du r|  }| j||||||d}	| j|	tS )a  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.

        Args:
            prompts: The prompts to the LLM. You may pass a sequence of prompts
                for batch inference. See [PromptType][vllm.inputs.PromptType]
                for more details about the format of each prompt.
            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: 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.
                If `False`, no progress bar is created.
            lora_request: LoRA request to use for generation, if any.
            priority: The priority of the requests, if any.
                Only applicable when priority scheduling policy is enabled.
                If provided, must be a list of integers matching the length
                of `prompts`, where each priority value corresponds to the prompt
                at the same index.
            tokenization_kwargs: Overrides for `tokenizer.encode`.

        Returns:
            A list of `RequestOutput` objects containing the
            generated completions in the same order as the input prompts.
        generatezLLM.generate() is only supported for generative models. Try passing `--runner generate` to use the model as a generative model.Nr   paramsr   r   r   r   )r   runner_typer   r   _run_completionr   validate_outputsr2   )
r   r   r   r   r   r   r   r   r   outputsrz   rz   r   r     s"   )	zLLM.generatec                    sb   j jj  d u sjjr r jd u r|S t|ts"|gt| n|} fddt	||D S )Nc                    s    g | ]\}} || jqS rz   )_resolve_single_prompt_mm_loradefault_mm_loras)r{   promptopt_lora_reqlora_configr   rz   r   
<listcomp>  s    z8LLM._get_modality_specific_lora_reqs.<locals>.<listcomp>)
r   r   r   r   is_multimodal_modelr   r   r   lenzip)r   r   r   optional_lorasrz   r   r    _get_modality_specific_lora_reqs  s   

z$LLM._get_modality_specific_lora_reqsr   r   c           	      C   s   |r| dpi  }s|S t| | }|s|S t|dkr*td| |S | }|| }t|	|d }|rI|j
|krGtd |S t|||S )Nmulti_modal_datarQ   zMultiple modality specific loras were registered and would be used by a single prompt consuming several modalities;  currently we only support one lora per request; as such, lora(s) registered with modalities: %s will be skippedzA modality with a registered lora and a lora_request with a different ID were provided; falling back to the lora_request as we only apply one LoRARequest per prompt)r   setkeysintersectionr   r   warningpopsortedindexlora_int_idr-   )	r   r   r   r   mm_datar   modality_namemodality_lora_pathmodality_lora_idrz   rz   r   r     s>   

z"LLM._resolve_single_prompt_mm_lorarz   methodtimeoutargsc                 C   s   | j ||||S )a  
        Execute an RPC call on all workers.

        Args:
            method: 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
                `self` argument, in addition to the arguments passed in `args`
                and `kwargs`. The `self` argument will be the worker object.
            timeout: Maximum time in seconds to wait for execution. Raises a
                [`TimeoutError`][] on timeout. `None` means wait indefinitely.
            args: Positional arguments to pass to the worker method.
            kwargs: Keyword arguments to pass to the worker method.

        Returns:
            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.
        )r   collective_rpc)r   r   r   r   rr   rz   rz   r   r      s   zLLM.collective_rpcfuncc                 C   s   | j |S )a  
        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!
        )r   apply_model)r   r   rz   rz   r   r   @  s   zLLM.apply_modelc                 C   sT   t |trt|t|krtd|du st |tr!|gt| S tdt| )z;Get the optional lora request corresponding to each prompt.z:Lora request list should be the same length as the promptsNzInvalid lora_request type )r   r   r   r   r-   	TypeErrorr   )r   r   r   rz   rz   r   _get_beam_search_lora_requestsM  s   z"LLM._get_beam_search_lora_requestsr   concurrency_limitc           .         sV  |j }|j}|j}|j}	|j}
| ||}|  }t|j|
}|r,|dur,t	
d d}|du r4t|}dtdtfdd td| d	|d
d}g }t||D ]=\}}i }d|v r^|d |d< d|v rh|d |d< d|v rvtt|}|d }n||d }|t|f|dd| qNtdt||D ]}||||  }t|}|rt|dddd}t	
d |D ]}ttdd |D g }dgttdd |D  }tt|dd |d	d }t|dkr nt fdd|D  \}}| j||d|d}t||D ]r\\}}} g }!t||D ]U}"||" }#||" }$|$jd jdurc|$jd jd }%|% D ]4\}&}'t|#j|&g |#j|%g |#j|#j |'j! |#j"|#j#d}(|&|jkr\|	s\| j$|( q.|!|( q.qt%|!|d
d})|)d| | _&qqqg }*|D ]-} | j$'| j& t%| j$|d
d}+|+d| },|,D ]
}-|(|-j|-_)q|*t*|,d q{|*S ) a  
        Generate sequences using beam search.

        Args:
            prompts: A list of prompts. Each prompt can be a string or a list
                of token IDs.
            params: The beam search parameters.
            lora_request: LoRA request to use for generation, if any.
            use_tqdm: Whether to use tqdm to display the progress bar.
            concurrency_limit: The maximum number of concurrent requests.
                If None, the number of concurrent requests is unlimited.
        NzSProgress bar is not supported when using concurrency_limit. Disabling progress bar.Fbeamrs   c                 S   s@   d| j i}| jd ur| j|d< | jd ur| j|d< tdi |S )Nprompt_token_idsr   ri   rz   )tokensr   ri   r+   )r   token_prompt_kwargsrz   rz   r   create_tokens_prompt_from_beam  s   




z7LLM.beam_search.<locals>.create_tokens_prompt_from_beam   rQ   T)logprobs
max_tokenstemperature
skip_cloner   ri   r   r   )r   r   r   zBeam searchtoken)descunit
unit_scalezThe progress bar shows the upper bound on token steps and may finish early due to stopping conditions. It does not reflect instance-level progress.c                 s   s    | ]}|j V  qd S r   )beamsr{   instancerz   rz   r   	<genexpr>  s    z"LLM.beam_search.<locals>.<genexpr>c                 s       | ]}t |jV  qd S r   )r   r   r   rz   rz   r   r         

c                    s   g | ]	} ||j fqS rz   )r   )r{   r   r   rz   r   r     s    z#LLM.beam_search.<locals>.<listcomp>)r   r   r   )r   r   r   cum_logprobr   ri   )keyreverse)	sequences)+
beam_widthr   r   
ignore_eoslength_penaltyr   r   r   eos_token_idr   r   r   r   r+   rA   r   r   encodeappendr
   ranger   listsum	itertools
accumulater   r   r   r   r   r   r   logprobr   ri   	completedr   r   extenddecodetextr   ).r   r   r   r   r   r   r  r   r   r  r  lora_requestsrU   sort_beams_keybeam_search_params	instanceslora_reqr   	mm_kwargsprompt_tokensprompt_startinstances_batch
token_iter_	all_beamsposinstance_start_and_endprompts_batchlora_req_batchoutputstartendr   instance_new_beamsicurrent_beamresultr   token_idlogprob_objnew_beamsorted_beamsr   sorted_completed
best_beamsr   rz   r   r   beam_search]  s   

	

	

%zLLM.beam_searchc                 C   s2   | j }|jpi }t|j|dd|j d|S Ndo_lower_caseF)max_total_tokensr3  add_special_tokens)r   encoder_configr7   max_model_lenr   is_encoder_decoderwith_kwargsr   r   r   r6  rz   rz   r   _get_cmpl_tok_params  s   

zLLM._get_cmpl_tok_paramsc                    s6   | j j}| j  fdd|D }| |}|||S )a  
        Convert prompt inputs from LLM APIs (other than [LLM.chat][]) into
        a format that can be passed to `_add_request`.

        Refer to [LLM.generate][] for a complete description of the arguments.

        Returns:
            A list of `TokensPrompts` objects containing the tokenized prompt
            after chat template interpolation, and the raw multi-modal inputs.
        c                    s   g | ]}t  |qS rz   )r=   )r{   r   r   rz   r   r   6  s    
z.LLM._preprocess_completion.<locals>.<listcomp>)r   rendererr   r;  render_cmpl)r   r   r   r=  parsed_prompts
tok_paramsrz   r<  r   _preprocess_completion$  s   

zLLM._preprocess_completionc                 C   s.   | j }|jpi }t|j|dddd|S r2  )r   r6  r7   r7  r   r9  r:  rz   rz   r   _get_chat_tok_params=  s   

zLLM._get_chat_tok_paramsconversationschat_templatechat_template_content_formatchat_template_kwargsadd_generation_promptcontinue_final_messagetoolsc
                 C   sX   | j j}
t||t|t|||t|
jtdd}| |}|
j	|||d|	id\}}|S )a|  
        Convert a list of conversations into prompts so that they can then
        be used as input for other LLM APIs.

        Refer to [LLM.chat][] for a complete description of the arguments.

        Returns:
            A list of `TokensPrompts` objects containing the tokenized prompt
            after chat template interpolation, and the raw multi-modal inputs.
        )rG  rH  rI  tokenize)rD  rE  rF  ri   )prompt_extras)
r   r=  r6   r8   r   r   rU   rD   rB  render_chat)r   rC  rD  rE  rF  rG  rH  rI  r   ri   r=  chat_paramsr@  r  engine_promptsrz   rz   r   _preprocess_chatG  s,   


zLLM._preprocess_chatmessagesc                 C   s\   | j }|j}|dkrtd|du r|  }| j|||||||
|||	||d}| j|tS )a	  
        Generate responses for a chat conversation.

        The chat conversation is converted into a text prompt using the
        tokenizer and calls the [generate][vllm.LLM.generate] method to generate
        the responses.

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

        Args:
            messages: 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: 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: 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.
                If `False`, no progress bar is created.
            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`.
            chat_template_kwargs: Additional kwargs to pass to the chat
                template.
            tokenization_kwargs: Overrides for `tokenizer.encode`.
            mm_processor_kwargs: Overrides for `processor.__call__`.

        Returns:
            A list of `RequestOutput` objects containing the generated
            responses in the same order as the input messages.
        r   z{LLM.chat() is only supported for generative models. Try passing `--runner generate` to use the model as a generative model.N)rP  r   r   r   rD  rE  rF  rG  rH  rI  r   ri   )r   r   r   r   	_run_chatr   r   r2   )r   rP  r   r   r   rD  rE  rG  rH  rI  rF  r   ri   r   r   r   rz   rz   r   chatw  s.   BzLLM.chat)truncate_prompt_tokensr   r   pooling_taskr   pooling_paramsrS  rT  c                C   s  |du rt d| j}|j}	|	dkrt d|dur*tjdtdd t|t|d}d	}
t|trMd
|v rMd}
| j	du r@t d| j	
|}| j	j|d}|
r}| j	dusVJ t|trpg }t|D ]}|| j	| qa|}nt|trwJ | j	|}|du rt }t|D ]}|jdu r||_q|j|krd|jd|d}t |q| j|||||d}| j|t}|
r| j	dusJ | j	j|d}tt d|t|ddg ddgS |S )a  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.

        Args:
            prompts: The prompts to the LLM. You may pass a sequence of prompts
                for batch inference. See [PromptType][vllm.inputs.PromptType]
                for more details about the format of each prompt.
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            use_tqdm: 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.
                If `False`, no progress bar is created.
            lora_request: LoRA request to use for generation, if any.
            pooling_task: Override the pooling task to use.
            tokenization_kwargs: Overrides for `tokenizer.encode`.

        Returns:
            A list of `PoolingRequestOutput` objects containing the
            pooled hidden states in the same order as the input prompts.
        Na  pooling_task required for `LLM.encode`
Please use one of the more specific methods or set the pooling_task when using `LLM.encode`:
  - For embeddings, use `LLM.embed(...)` or `pooling_task="embed"`.
  - For classification logits, use `LLM.classify(...)` or `pooling_task="classify"`.
  - For similarity scores, use `LLM.score(...)`.
  - For rewards, use `LLM.reward(...)` or `pooling_task="token_classify"`
  - For token classification, use `pooling_task="token_classify"`
  - For multi-vector retrieval, use `pooling_task="token_embed"`poolingzvLLM.encode() is only supported for pooling models. Try passing `--runner pooling` to use the model as a pooling model.zThe `truncate_prompt_tokens` parameter in `LLM.encode()` is deprecated and will be removed in v0.16. Please pass it via `tokenization_kwargs` instead.r   
stacklevelrS  FdataTzNo IOProcessor plugin installed. Please refer to the documentation and to the 'prithvi_geospatial_mae_io_processor' offline inference example for more details.)r   z You cannot overwrite param.task=z with pooling_task=!r   r   r   r   r   )model_outputrP   num_cached_tokensr   )
request_idr   r^  r   finished)r   r   r   warningswarnDeprecationWarningr8   r   r   r   parse_requestpre_processrG   r5   rF   r	  validate_or_generate_paramsr   taskr   r   r   r1   post_processr   getattr)r   r   rU  rS  r   r   rT  r   r   r   io_processor_promptvalidated_promptvalidated_pooling_paramsparammsgr   model_outputsprocessed_outputsrz   rz   r   r    s   %




z
LLM.encode)rS  r   rU  r   r   c                C   sN   d| j vr	td|durt|t|d}| j||||d|d}dd |D S )a  
        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.

        Args:
            prompts: The prompts to the LLM. You may pass a sequence of prompts
                for batch inference. See [PromptType][vllm.inputs.PromptType]
                for more details about the format of each prompt.
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            use_tqdm: 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.
                If `False`, no progress bar is created.
            lora_request: LoRA request to use for generation, if any.
            tokenization_kwargs: Overrides for `tokenizer.encode`.

        Returns:
            A list of `EmbeddingRequestOutput` objects containing the
            embedding vectors in the same order as the input prompts.
        embedz_Embedding API is not supported by this model. Try converting the model using `--convert embed`.NrY  r   rU  r   rT  r   c                 S      g | ]}t |qS rz   )r0   	from_baser{   itemrz   rz   r   r         zLLM.embed.<locals>.<listcomp>)r   r   r8   r   r  )r   r   rS  r   rU  r   r   r   rz   rz   r   rq  o  s$   
"	z	LLM.embed)rU  r   r   r   c                C   s6   d| j vr	td| j||||d|d}dd |D S )a  
        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.

        Args:
            prompts: The prompts to the LLM. You may pass a sequence of prompts
                for batch inference. See [PromptType][vllm.inputs.PromptType]
                for more details about the format of each prompt.
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            use_tqdm: 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.
                If `False`, no progress bar is created.
            lora_request: LoRA request to use for generation, if any.
            tokenization_kwargs: Overrides for `tokenizer.encode`.

        Returns:
            A list of `ClassificationRequestOutput` objects containing the
            embedding vectors in the same order as the input prompts.
        classifyzgClassification API is not supported by this model. Try converting the model using `--convert classify`.rr  c                 S   rs  rz   )r/   rt  ru  rz   rz   r   r     rw  z LLM.classify.<locals>.<listcomp>)r   r   r  )r   r   rU  r   r   r   r   rz   rz   r   rx    s   
!	zLLM.classify)rU  rS  r   r   r   c            	   C   s   | j |||||d|dS )a  
        Generate rewards for each prompt.

        Args:
            prompts: The prompts to the LLM. You may pass a sequence of prompts
                for batch inference. See [PromptType][vllm.inputs.PromptType]
                for more details about the format of each prompt.
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            use_tqdm: 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.
                If `False`, no progress bar is created.
            lora_request: LoRA request to use for generation, if any.
            tokenization_kwargs: Overrides for `tokenizer.encode`.

        Returns:
            A list of `PoolingRequestOutput` objects containing the
            pooled hidden states in the same order as the input prompts.
        token_classify)r   r   rU  rS  rT  r   )r  )r   r   rU  rS  r   r   r   rz   rz   r   reward  s    z
LLM.rewarddata_1data_2c                C   s   |   }g }|| D ]}	t|	tstd||	 q
| j||||d|d}
|
dt| }|
t|d  }t|dkrB|t| }t|||d}| j	|t
}dd |D S )	Nz;Embedding scores currently do not support multimodal input.rq  r   r   rU  rT  r   r   rQ   )rU   embed_1embed_2c                 S   rs  rz   r3   rt  ru  rz   rz   r   r   .  rw  z(LLM._embedding_score.<locals>.<listcomp>)r   r   strNotImplementedErrorr	  r  r   r!   r   r   r1   )r   r{  r|  r   rU  r   r   rU   input_textsr  encoded_outputencoded_output_1encoded_output_2scoresr   rz   rz   r   _embedding_score  s6   

	zLLM._embedding_scorec             
   C   sd  ddl m} |  }g }	|D ]}
t|
tstd|	|
 qg }|D ]}
t|
ts.td||
 q#| j|	| |||d|d}|dt|	 }|t|	d }t|dkr]|t| }g }g }|j	 }durk|g}t
||D ]3\}}|jj}|jj}t||}|j| |j }|t|j d|j ||d	||j|j d
d qp| j|t}dd |D S )z
        Late interaction scoring (ColBERT MaxSim).

        Encodes queries and documents into per-token embeddings, then computes
        MaxSim: sum over query tokens of max similarity to any document token.
        r   )PoolingOutputzBLate interaction scores currently do not support multimodal input.token_embedr}  NrQ   r  )rZ  T)r_  r   r   r^  r`  c                 S   rs  rz   r  ru  rz   rz   r   r     rw  z/LLM._late_interaction_score.<locals>.<listcomp>)vllm.outputsr  r   r   r  r  r	  r  r   pad_token_idr   r   rZ  r#   r   r1   r_  r^  r   r   )r   r{  r|  r   rU  r   r   r  rU   text_1r  text_2r  r  r  r  paddingr  emb_1emb_2q_embd_embmaxsim_scorer   r   rz   rz   r   _late_interaction_score0  s`   

	


zLLM._late_interaction_scorescore_templatec             	   C   s"  | j }|  }	t|	trtdt|dkr|t| }|d u r&tdd}n|jd u r.d|_tt  }
tt	  }dd t
||D }|D ]5\}}t||||	||d\}}|dd  }ro| }t|}d	|i|_|
| n|
| || qD| j||
||d
}| j|t}dd |D S )Nz0Score API is not supported for Mistral tokenizerrQ   score)rg  c                 S   s   g | ]\}}||fqS rz   rz   )r{   t1t2rz   rz   r   r     s    z-LLM._cross_encoding_score.<locals>.<listcomp>)r   r{  r|  rU   r   r  token_type_idscompressed_token_type_ids)r   r   r   r   c                 S   rs  rz   r  ru  rz   rz   r   r     rw  )r   r   r   rD   r   r   r5   rg  r  r(   r   r$   r   cloner"   extra_kwargsr	  r   r   r   r1   )r   r{  r|  r   rU  r   r   r  r   rU   pooling_params_listr   input_pairsqdr  engine_promptr  r   
compressedr   r   rz   rz   r   _cross_encoding_score  sJ   




	

zLLM._cross_encoding_score)r   rU  r   r   rD  c            	      s   | j }|j}	|	dkrtd| j |j}
|
s%t fdddD r%td|jr5t|jddd	kr5td
|js@|dur@td|j	}|j
}t||||d\}}| |}| }|jrh| j|||||||dS |
ru| j||||||dS | j||||||dS )a]  Generate similarity scores for all pairs `<text,text_pair>` or
          `<multi-modal data, multi-modal data pair>`.

        The inputs can be `1 -> 1`, `1 -> N` or `N -> N`.
        In the `1 - N` case the `data_1` input will be replicated `N`
        times to pair with the `data_2` inputs.
        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 inputs into a single list and pass it to this method.

        Supports both text and multi-modal data (images, etc.) when used with
        appropriate multi-modal models. For multi-modal inputs, ensure the
        prompt structure matches the model's expected input format.

        Args:
            data_1: Can be a single prompt, a list of prompts or
                `ScoreMultiModalParam`, which can contain either text or
                multi-modal data. When a list, it must have the same length as
                the `data_2` list.
            data_2: The data to pair with the query to form the input to
                the LLM. Can be text or multi-modal data. See [PromptType]
                [vllm.inputs.PromptType] for more details about the format of
                each prompt.
            pooling_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            use_tqdm: 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.
                If `False`, no progress bar is created.
            lora_request: LoRA request to use for generation, if any.
            chat_template: The chat template to use for the scoring. If None, we
                use the model's default chat template.
            tokenization_kwargs: Overrides for `tokenizer.encode`.
        Returns:
            A list of `ScoringRequestOutput` objects containing the
            generated scores in the same order as the input prompts.
        rV  zuLLM.score() is only supported for pooling models. Try passing `--runner pooling` to use the model as a pooling model.c                 3   s    | ]}| vV  qd S r   rz   )r{   tr   rz   r   r     s    
zLLM.score.<locals>.<genexpr>)rq  rx  zsScore API is not supported by this model. Try converting the model using `--convert embed` or `--convert classify`.
num_labelsr   rQ   z.Score API is only enabled for num_labels == 1.Nz9chat_template is only supported for cross-encoder models.)r   architecture)r   rU  r   r   r  )r   rU  r   r   )r   r   r   r   is_late_interactionallis_cross_encoderri  	hf_configr   r  r%   r;  get_encode_kwargsr  r  r  )r   r{  r|  r   rU  r   r   rD  r   r   r  r   r  score_data_1score_data_2r@  encode_kwargsrz   r  r   r    sv   8

		z	LLM.scorec                 C      | j   d S r   )r   start_profiler   rz   rz   r   r  B     zLLM.start_profilec                 C   r  r   )r   stop_profiler   rz   rz   r   r  E  r  zLLM.stop_profilereset_running_requestsreset_connectorc                 C   s   | j ||S r   )r   reset_prefix_cache)r   r  r  rz   rz   r   r  H  s   zLLM.reset_prefix_cachelevelc                 C   s   |    | jj|d dS )a'  
        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.

        Args:
            level: The sleep level. Level 1 sleep will offload the model
                weights and discard the kv cache. The content of kv cache
                is forgotten. Level 1 sleep is good for sleeping and waking
                up the engine to run the same model again. The model weights
                are backed up in CPU memory. Please make sure there's enough
                CPU memory to store the model weights. Level 2 sleep will
                discard both the model weights and the kv cache. The content
                of both the model weights and kv cache is forgotten. Level 2
                sleep is good for sleeping and waking up the engine to run a
                different model or update the model, where previous model
                weights are not needed. It reduces CPU memory pressure.
        )r  N)r  r   sleep)r   r  rz   rz   r   r  O  s   z	LLM.sleeptagsc                 C   s   | j | dS )a  
        Wake up the engine from sleep mode. See the [sleep][vllm.LLM.sleep]
        method for more details.

        Args:
            tags: An optional list of tags to reallocate the engine memory
                for specific memory allocations. Values must be in
                `("weights", "kv_cache")`. If None, all memory is reallocated.
                wake_up should be called with all tags (or None) before the
                engine is used again.
        N)r   wake_up)r   r  rz   rz   r   r  e  s   zLLM.wake_uprK   c                 C   r   )a  Return a snapshot of aggregated metrics from Prometheus.

        Returns:
            A `MetricSnapshot` instance capturing the current state
            of all aggregated metrics from Prometheus.

        Note:
            This method is only available with the V1 LLM engine.
        )r   get_metricsr   rz   rz   r   r  s  s   

zLLM.get_metricsnum_requestsc                 C   s>   t |trt||krtd| dt| d|S |g| S )NThe lengths of prompts (z) and params () must be the same.r   r   r   r   )r   r   r  rz   rz   r   _params_to_seq  s   

zLLM._params_to_seqc                 C   s>   t |trt||krtd| dt| d|S |g| S )Nr  z) and lora_request (r  r  )r   r   r  rz   rz   r   _lora_request_to_seq  s   

zLLM._lora_request_to_seqc                 C   s<   |d urt ||krtd| dt | d|S dg| S )Nr  z) and priority (r  r   )r   r   )r   r   r  rz   rz   r   _priority_to_seq  s   
zLLM._priority_to_seqc          
         s~   t |} |t|}tdd |D r# fddt||D }	n j|d}	 j|	|| |	||d  j|dS )Nc                 s   s    | ]}|j d uV  qd S r   rY  )r{   rm  rz   rz   r   r     s    z&LLM._run_completion.<locals>.<genexpr>c              	      s8   g | ]\}} j |gtt|jd dD ]}|qqS )rY  r   )rA  r8   r   rS  )r{   r   rm  r  r   r   rz   r   r     s    
z'LLM._run_completion.<locals>.<listcomp>r  r   r   )	r>   r  r   anyr   rA  _validate_and_add_requestsr   _run_engine)
r   r   r   r   r   r   r   seq_prompts
seq_paramsrN  rz   r  r   r     s*   zLLM._run_completion)
r   r   rD  rE  rG  rH  rI  rF  r   ri   c       
         C   sH   | j t||||
|||	||d	}| j|||| |||d | j|dS )N)rD  rE  rF  rG  rH  rI  r   ri   r\  r  )rO  r;   r  r   r  )r   rP  r   r   r   rD  rE  rG  rH  rI  rF  r   ri   rN  rz   rz   r   rQ    s*   
zLLM._run_chat)r   r   r   c             
   C   s   t |}| ||}| ||}	| ||}
|D ]}t|tr#tj|_q|}|r6t	|r.|nt
}||dd}g }z!t|D ]\}}| j||| |	| ||
| d}|| q=W d S  tyq } z|rk| jj|dd |d }~ww )NzAdding requests)r   )r   r   r   T)internal)r   r  r  r  r   rA   r@   
FINAL_ONLYoutput_kindcallabler   	enumerate_add_requestr	  	Exceptionr   abort_request)r   r   r   r   r   r   r   r  r  seq_lora_requestsseq_priorityspit	tqdm_funcadded_request_idsr(  r   r_  r   rz   rz   r   r    s<   
	zLLM._validate_and_add_requestsc              	   C   s   t | j|\}}}tt| j}|jd ur/t|j}	tj	d|	 dt
dd t|t|jd}| |}
|
 }| jj||||||| jd}| jj|||||||d |jS )Nz+The `truncate_prompt_tokens` parameter in `z_` is deprecated and will be removed in v0.16. Please pass it via `tokenization_kwargs` instead.r   rW  rY  )r   r   r   r   )r   r   r   prompt_text)r<   r   r  nextr   rS  r   __name__ra  rb  rc  r8   r   r;  r  r   process_inputsr   r   add_requestr_  )r   r   r   r   r   r   r  r  r_  params_typer@  engine_requestrz   rz   r   r  :  sD   





	zLLM._add_requestr  c             	   C   sL  |r | j  }t|r|nt}||dddddddddd}g }d}d}| j  r| j  }|D ]`}	|	jr||	 |rt|	t	rt
|	j}
|	jd usOJ |t
|	j|
 7 }||jd	  }|td
d |	jD 7 }||jd	  }d|dd|dd|_||
 n|d |j|kr|  q2| j  s+|r|  t|dd dS )NzProcessed promptsTzest. speed input: r   z.2fz toks/s, output: z toks/s)totalr   dynamic_ncolspostfixelapsedc                 s   r   r   )r   	token_ids)r{   stprz   rz   r   r     r   z"LLM._run_engine.<locals>.<genexpr>rQ   c                 S   s
   t | jS r   )r   r_  )xrz   rz   r   <lambda>  s   
 z!LLM._run_engine.<locals>.<lambda>)r  )r   get_num_unfinished_requestsr  r   has_unfinished_requestsstepr`  r	  r   r2   r   r   r   format_dictr  r  updatenrefreshcloser   )r   r   r  r  pbarr   total_in_tokstotal_out_toksstep_outputsr$  r  in_spdout_spdrz   rz   r   r  l  sP   











zLLM._run_enginerequestc                 C   0   t |tr	|d n|j}| jjdd|id dS )z
        Initialize weight transfer for RL training.

        Args:
            request: Weight transfer initialization request with backend-specific info
        	init_infoinit_weight_transfer_enginerr   N)r   r   r  r   r   )r   r  init_info_dictrz   rz   r   r    s
   

zLLM.init_weight_transfer_enginec                 C   r  )z
        Update the weights of the model.

        Args:
            request: Weight update request with backend-specific update info
        update_infoupdate_weightsr  N)r   r   r  r   r   )r   r  update_info_dictrz   rz   r   r    s
   
zLLM.update_weightsc                 C   sB   | j du r| jd}|r|d | _ | j S d| jjd| _ | j S )z;Return a transformers-style hierarchical view of the model.Nget_model_inspectionr   z
LLM(model=))r   r   r   r   rq   )r   resultsrz   rz   r   __repr__  s   

zLLM.__repr__)T)rs   Nr   )Nrz   N)NFN)NrO   NTFNNN)NTNNrO   TFNNNN)FF)rQ   )NNr   )br  
__module____qualname____doc__r  r   r   r   boolr  r   r   r.   floatr   r   r   r   r   r   r   r   r   rJ   r   rC   r   r   r   rA   r   r(   r   r   r   r-   r2   r   r9   r:   r   r   rL   tupler   nnModuler   r+   r*   r   r?   r   r1  r;  rA  rB  r   r   rO  rR  r'   r5   rB   r1   r  r0   rq  r/   rx  rz  r   r3   r  r  r  r)   r    r  r  r  r  r  r  r  r  r  r  r   rQ  r  r  r  r   r  r   r  r  rz   rz   rz   r   rN   e   s|   e	



 !"#$%
 '



	
@

!
6
" 




 ;


	

4
	

b	

 
	
=

7
	

*
	
,
	
Q
	

J
 












	

9

	

2

	


1

3

3
rN   )ur  ra  collections.abcr   r   typingr   r   r   r   torch.nnr
  pydanticr   	tqdm.autor   typing_extensionsr	   vllm.beam_searchr
   r   r   r   vllm.configr   r   r   r   r   r   vllm.config.compilationr   vllm.config.modelr   r   r   r   r   %vllm.distributed.weight_transfer.baser   r   vllm.engine.arg_utilsr   vllm.entrypoints.chat_utilsr   r   $vllm.entrypoints.pooling.score.utilsr   r    r!   r"   r#   r$   r%   vllm.entrypoints.utilsr&   vllm.inputs.datar'   r(   r)   r*   r+   vllm.loggerr,   vllm.lora.requestr-   'vllm.model_executor.layers.quantizationr.   r  r/   r0   r1   r2   r3   vllm.platformsr4   vllm.pooling_paramsr5   vllm.renderersr6   r7   r8   vllm.renderers.inputsr9   r:    vllm.renderers.inputs.preprocessr;   r<   r=   r>   vllm.sampling_paramsr?   r@   rA   
vllm.tasksrB   vllm.tokenizersrC   vllm.tokenizers.mistralrD   vllm.usage.usage_librE   vllm.utils.collection_utilsrF   rG   vllm.utils.counterrH   vllm.v1.engine.llm_enginerI   vllm.v1.sample.logits_processorrJ   vllm.v1.metrics.readerrK   r  r   rL   rN   rz   rz   rz   r   <module>   sT    $	