
    -`i9                    t   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& d dl'm(Z(m)Z) d dl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 d dl1m2Z2m3Z3 d dl4m5Z5m6Z6m7Z7m8Z8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZCmDZDmEZEmFZFmGZG d dlHmIZI d dlJmKZK d dlLmMZMmNZNmOZO d dlPmQZQ d dlRmSZS d dlTmUZU d dlVmWZW d dlXmYZYmZZZ d dl[m\Z\ d dl]m^Z^ d dl_m`Z` d d lambZb erd d!lcmdZd  e=ee          Zf ed"e#          Zg G d$ d%          Zhd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)
EngineArgs)ChatCompletionMessageParamChatTemplateContentFormatOption)ScoreContentPartParamScoreMultiModalParam_cosine_similarity_validate_score_input_lenscompress_token_type_idsget_score_prompt)_validate_truncation_sizelog_non_default_args)
DataPrompt
PromptTypeSingletonPrompt
TextPromptTokensPrompt)get_prompt_components)init_logger)LoRARequest)QuantizationMethods)ClassificationRequestOutputEmbeddingRequestOutputPoolingRequestOutputRequestOutputScoringRequestOutput)current_platform)PoolingParams)BeamSearchParamsRequestOutputKindSamplingParams)PoolingTask)TokenizerLike)MistralTokenizer)UsageContext)as_iter
is_list_of)Counter)EngineCoreRequest)	LLMEngine)LogitsProcessor)Metric_R)defaultc            C          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z  deez  dededede	e         dz  de
dededz  dedz  dedz  de
dedededededed eez  dz  d!edz  d"eeef         dz  d#edz  d$eeef         ez  dz  d%eeef         ez  dz  d&eeef         ez  dz  d'e
dz  d(e
eeef         z  ez  dz  d)e	eee         z           dz  d*ed+dfBd,Zd+efd-Zdzd.Zd+efd/Z	 d{d0ddd1d2eee         z  d3eee         z  dz  d4ee d5e!f         z  d6e	e"         e"z  dz  d7e	e
         dz  d+e	e#         fd8Z$d2eee         z  d6e	e"         e"z  dz  fd9Z%d:ed6e"dz  d;eeef         dz  fd<Z&	 	 	 d|d>ee d5e'f         z  d?edz  d@e(d*eeef         dz  d+e	e'         f
dAZ)dBe e*j+        ge'f         d+e	e'         fdCZ,d6e	e"         e"z  dz  d2e	e-e.z           d+e	e"dz           fdDZ/	 	 	 d}d2e	e-e.z           dEe0d6e	e"         e"z  dz  d4edFe
dz  d+e	e1         fdGZ2	 	 	 	 	 	 	 d~dHe	e3         e	e	e3                  z  dIedz  dJe4dKedLedMe	eeef                  dz  dNeeef         dz  d"eeef         dz  d+e	e.e-z           fdOZ5	 	 	 	 	 	 	 	 	 	 ddHe	e3         e	e	e3                  z  d3ee	e         z  dz  d4ee d5e!f         z  d6e"dz  dIedz  dJe4dKedLedMe	eeef                  dz  dNeeef         dz  d"eeef         dz  d+e	e#         fdPZ6	 d{dd0ddddQd2eee         z  e7z  dRe8ee8         z  dz  dSe
dz  d4ee d5e!f         z  d6e	e"         e"z  dz  dTe9dz  dUeeef         dz  d+e	e:         fdVZ;dd0ddddWd2eee         z  dSe
dz  d4ee d5e!f         z  dRe8ee8         z  dz  d6e	e"         e"z  dz  dUeeef         dz  d+e	e<         fdXZ=d0ddddYd2eee         z  d4ee d5e!f         z  dRe8ee8         z  dz  d6e	e"         e"z  dz  dUeeef         dz  d+e	e>         fdZZ?dd0ddddWd2eee         z  dSe
dz  d4ee d5e!f         z  dRe8ee8         z  dz  d6e	e"         e"z  dz  dUeeef         dz  d+e	e:         fd[Z@	 	 	 	 	 dded\e	ee.z  e-z           d]e	ee.z  e-z           dSe
dz  d4ee d5e!f         z  dRe8dz  d6e	e"         e"z  dz  dUeeef         dz  d+e	eA         fd^ZB	 	 	 	 	 	 dded_e	e         e	eC         z  d`e	e         e	eC         z  dSe
dz  d4ee d5e!f         z  dRe8dz  d6e	e"         e"z  dz  dUeeef         dz  daedz  d+e	eA         fdbZDdd0ddddcd_eEeeE         z  eFz  d`eEeeE         z  eFz  dSe
dz  d4ee d5e!f         z  dRe8dz  d6e	e"         e"z  dz  dIedz  d+e	eA         fddZGdzdeZHdzdfZI	 ddgedhed+efdiZJddje
fdkZKd{dle	e         dz  fdmZLd+e	dn         fdoZMd0dddpd2eee         z  e7z  dEeee         z  e8z  ee8         z  d4ee d5e!f         z  d6ee"         e"z  dz  d7e	e
         dz  dUeeef         dz  d+dfdqZNddrdsedtedEee8z  d6e"dz  d7e
dUeeef         dz  d+e(eOeeef         f         fduZP	 	 	 dd:edEee8z  d6e"dz  d7e
dUeeef         dz  d+efdvZQd0dwd4ee d5e!f         z  d+e	e#e:z           fdxZRd+efdyZSd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
            `huggingface-cli login` (stored in `~/.huggingface`).
        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", normalize=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modelrL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   kwargsreturnc                   d| vrd| d<   d| v r4| d         }!t          |!t                    rt          j        |!          | d<   d| v rwt          | d         t                    r\ddlm}" | d         }#	  |"d6i |#| d<   nA# t          $ r4}$t          	                    d|#|$           t          d|$           |$d	}$~$ww xY w|i }d
t          dt          t                   dt          fd}%t          |t                    rt          t          |                    }&n |%|t                    }& |%|t                     }' |%|t"                    }( |%|t$                    })t          |                     dd                    }*|                     d          }+|*dk    r,|+dk    s&t)          j                    st          d|* d          t-          d6i 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/|'d0|(d1|)d2|&d3|| },t/          |,           t1          j        |,t4          j        4          | _        t          | j                  | _        t=                      | _        d	| _         | j        !                                }-t          "                    d5|-           |-| _#        | j        j$        | _$        | j        j%        | _%        | j        j&        | _&        d	| _'        d	S )7z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clsrl   c                     | 
             S t          | t                    r& di fd|                                 D             S | S )z0Convert dict/None/instance to a config instance.Nc                 <    i | ]\  }}t          |          ||S  )r   ).0kvrs   s      h/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/entrypoints/llm.py
<dictcomp>z6LLM.__init__.<locals>._make_config.<locals>.<dictcomp>  s/    VVVtq!cST@U@UVaVVV    rv   )
isinstancedictitems)rr   rs   s    `rz   _make_configz"LLM.__init__.<locals>._make_config  s^    }suu%&& XsWWVVVVu{{}}VVVWWWLr|   )modedata_parallel_sizerJ   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'.rj   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   rg   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rh   ri   )engine_argsusage_contextzSupported tasks: %srv   )(r}   typecloudpickledumpsr~   vllm.config.kv_transferrq   r   loggererror
ValueErrorr   rD   intr   r   r   r   r   getr4   is_tpur   r%   rA   from_engine_argsr<   	LLM_CLASS
llm_engineengine_classr?   request_counterdefault_sampling_paramsget_supported_tasksinfosupported_tasksmodel_configinput_processorio_processor_cached_repr).selfrj   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   ri   rk   ro   rq   raw_config_dicter   compilation_config_instancestructured_outputs_instanceprofiler_config_instanceattention_config_instance_dp_size_distributed_executor_backendr   r   s.                                                 rz   __init__zLLM.__init__   s   P f,,*.F&'6!!-J *d++ E'2'8'D'D|$6))j'($/
 /
) A@@@@@$%9:OW/?/?/R/R//R/R+,," 	W 	W 	WC#	   !!N1!N!NOOUVV	W L	 	$r( 	r 	 	 	 	 (#.. 	*;$%788+ + +'' +7,"$5+ +' '3l%'>'
 '
# $0<#P#P $0L1A?$S$S! vzz"6::;;(.

3Q(R(R%qLL15HHH$+-- I A( A A A   ! !
 !
 !
%!
6!
 G!
  i	!

 *>!
 !4 3!
 0/!
 &>%=!
 #8"7!
 "6!5!
 %!
 &!
 X!
  21!
 !
  $:#9!!
" #8"7#!
$ "z%!
& *>'!
( (-)!
* *F)E+!
, '@&?-!
. X/!
0 &1!
2 !4 33!
4 (-5!
6 'B&A7!
8 549!
: 76;!
<  ;:=!
> 0/A!
 !
F 	[)))#4#<3I
 
 
 !11&yy>B$/==??)?;;;. O8#> O8 )-s   0A< <
B:/B55B:c                 4    | j                                         S N)r   get_tokenizerr   s    rz   r   zLLM.get_tokenizera  s    ,,...r|   c                 j    | j                                          | j                                         d S r   )r   clear_mm_cacher   reset_mm_cacher   s    rz   r   zLLM.reset_mm_cached  s1    ++---&&(((((r|   c                     | j         | j                                        | _         | j         rt          j        di | j         S t                      S )Nrv   )r   r   get_diff_sampling_paramr8   from_optionalr   s    rz   get_default_sampling_paramszLLM.get_default_sampling_paramsh  sT    '/+/+<+T+T+V+VD(' 	P!/OO$2NOOOr|   T)use_tqdmlora_requestprioritypromptssampling_paramsr   .r   r   c                @   | j         }|j        }|dk    rt          d          ||                                 }|                     ||          }|                     |||||           |                     |          }| j                            |t                    S )ad  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.

        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.
        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    _get_modality_specific_lora_reqs_validate_and_add_requests_run_enginer   validate_outputsr2   )	r   r   r   r   r   r   r   r   outputss	            rz   r   zLLM.generateo  s    X (".*$$$   "">>@@O <<WlSS''"% 	( 	
 	
 	
 ""H"55 11'=IIIr|   c                 B     j         j        j         j        j        r	r	j        |S t          |t                    rt          |t                    r|g}t          |t                    s|gt          |          z  n|} fdt          ||          D             S )Nc                 N    g | ]!\  }}                     ||j                  "S rv   )_resolve_single_prompt_mm_loradefault_mm_loras)rw   promptopt_lora_reqlora_configr   s      rz   
<listcomp>z8LLM._get_modality_specific_lora_reqs.<locals>.<listcomp>  sK     
 
 
 % //, 
 
 
r|   )r   vllm_configr   r   is_multimodal_modelr   r}   r   strlenzip)r   r   r   optional_lorasr   s   `   @rz   r   z$LLM._get_modality_specific_lora_reqs  s     o1=
 $8     + < D'8,, 	 
7C0H0H 	 iG lH55\NS\\)) 	
 
 
 
 
 ),G^(D(D
 
 
 	
r|   r   r   c                 P   |r.t          |t                    r|                    d          pi x}s|S t          |                                                              |                                          }|s|S t          |          dk    rt                              d|           |S |	                                }||         }t          |                              |          dz   }|r'|j        |k    rt                              d           |S t          |||          S )Nmulti_modal_datarJ   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}   r~   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_ids	            rz   r   z"LLM._resolve_single_prompt_mm_lora  sa    !	 fd++	   &zz*<==CCG	 
  LLNN
 

,',,..
/
/ 	  	 |q  NN#
      %((**-m<!"23399-HH1L  	 '+;;;O  
  
 
 	
r|   rv   methodtimeoutargsc                 <    | 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   rk   s        rz   r   zLLM.collective_rpc  s     < --fgtVLLLr|   funcc                 6    | 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   s     rz   r   zLLM.apply_model/  s     **4000r|   c                    t          |t                    r/t          |          t          |          k    rt          d          |t          |t                    r|gt          |          z  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   s      rz   _get_beam_search_lora_requestsz"LLM._get_beam_search_lora_requests<  s     lH-- 	#l2C2Cs7||2S2SL   :lK#H#H >CLL00IT,5G5GIIJJJr|   r   concurrency_limitc                   . |j         }|j        }|j        }|j        }	|j        }
|                     ||          }|                                 }t          |j        |
          }|r|t          
                    d           d}|t          |          }dt          dt          fd.t          d|z  d|d	
          }g }t          ||          D ]\  }}i }d|v r|d         |d<   d|v r|d         |d<   d|v rt!          t          |          }|d         }n|                    |d                   }|                    t'          |f|dd|           t)          dt          |          |          D ]D}||||z            }t)          |          }|r-t+          |ddd          }t          
                    d           |D ]}t-          t/          d |D             g                     }dgt-          t1          j        d |D                                 z   }t-          t          |dd         |dd                             }t          |          dk    r nXt          .fd|D              \  }}|                     ||d|          }t          ||          D ]\  \  }}} g }!t)          ||          D ]}"||"         }#||"         }$|$j        d         j        |$j        d         j        d         }%|%                                D ]\  }&}'t          |#j        |&gz   |#j        |%gz   |#j        |#j         |'j!        z   |#j"        |#j#                  }(|&|j        k    r|	s| j$                            |(           p|!                    |(           tK          |!|d	          })|)d|         | _&        Fg }*|D ]} | j$        '                    | j&                   tK          | j$        |d	          }+|+d|         },|,D ]!}-|(                    |-j                  |-_)        "|*                    tU          |,                     |*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beamrl   c                 p    d| j         i}| j        
| j        |d<   | j        
| j        |d<   t          di |S )Nprompt_token_idsr   rb   rv   )tokensr   rb   r*   )r   token_prompt_kwargss     rz   create_tokens_prompt_from_beamz7LLM.beam_search.<locals>.create_tokens_prompt_from_beamz  sT    1CT[0Q$0:>:O#$67'3=A=U#$9:66"5666r|      rJ   T)logprobs
max_tokenstemperature
skip_cloner   rb   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              3   $   K   | ]}|j         V  d S r   )beamsrw   instances     rz   	<genexpr>z"LLM.beam_search.<locals>.<genexpr>  s$      HHHHHHHHHr|   c              3   >   K   | ]}t          |j                  V  d S r   )r   r   r   s     rz   r   z"LLM.beam_search.<locals>.<genexpr>  s=       ) )08HN++) ) ) ) ) )r|   c                 4    g | ]} |          |j         fS rv   )r   )rw   r   r   s     rz   r   z#LLM.beam_search.<locals>.<listcomp>  s<         87==t?PQ  r|   r   r   r   )r   r   r   cum_logprobr   rb   )keyreverse)	sequences)+
beam_widthr   r   
ignore_eoslength_penaltyr   r   r   eos_token_idr   r   r   r   r*   r8   r   r   encodeappendr   ranger	   listsum	itertools
accumulater   r   r   r   r   r   r  logprobr   rb   	completedr   r   extenddecodetextr   )/r   r   r   r   r   r   r  r   r   r  r	  lora_requestsrN   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   r   s/                                                 @rz   beam_searchzLLM.beam_searchL  s   , &
&
(&
.;;L'RR&&((	7"
 

  	)5NN*   H$ #G	71C 	7 	7 	7 	7 	7 ,^#	
 
 
 /1	 #M7 ; ; 	 	HfI!V++067I0J	,-$..39:O3P	/0!V++lF33 &'9 : ) 0 01A B B"!!)!   	     "!S\\3DEE Q	? Q	?L'|FW7W(WXOz**J !]U  
 7  
   D? D?6:HHHHH"MM7 7	 cD( ) )<K) ) )    
 AECRC#abb'**A A& y>>Q&&E 14   $-  1-~ !$6"!/	 '   /2*O/ / #? #?*LUC( *,&"5#.. H H'0|!'!>!,5A
 (.~a'8'A!'DH9A9I9I H H 5++=+7+>(+K-9-BhZ-O1=1J0<0H&1&91:5A5R8D8X," ," ," %-	0F$F$F,6 %G %-$6$=$=h$G$G$G$G$6$=$=h$G$G$G$G#)*$ $ $L &2+:+%>HNNG#?J ! 		C 		CH%%hn555%"      *+:+6J" : :%,,T[99		NN+jAAABBBBr|   messageschat_templatechat_template_content_formatadd_generation_promptcontinue_final_messagetoolschat_template_kwargsc	                    t          |t                    r,t          t          t          t                            |          }	n!t          t          t                   |          g}	| j        j        }
||||d|pi }t          t          t          z                       }|	D ]1} |
j        |fd|i|\  }}|||d<   |	                    |           2|S )a  
        Generate prompt for a chat conversation. The pre-processed
        prompt can then be used as input for the other LLM methods.

        Refer to `chat` for a complete description of the arguments.
        Returns:
            A list of `TokensPrompts` objects containing the tokenized
            prompt after chat template interpolation, and the
            pre-processed multi-modal inputs.
        )r6  r8  r9  r:  r7  Nrb   )
r>   r  r   r   r   rendererr)   r*   render_messagesr  )r   r5  r6  r7  r8  r9  r:  r;  rb   list_of_messagesr=  r   msgsr!  r   s                  rz   preprocess_chatzLLM.preprocess_chat  s   2 h%% 	R#D.H)I$JHUU !%T*D%Ex P PQ?+ +%:&<	 
  

 $)r 
 zL0133$ 	# 	#D 10 -I ' IAv
 #.0C,-NN6""""r|   c           
      n    |                      ||||||	|
|          }|                     ||||          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 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: 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.
            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.
        )r5  r6  r7  r8  r9  r:  r;  rb   r  )rA  r   )r   r5  r   r   r   r6  r7  r8  r9  r:  r;  rb   r   s                rz   chatzLLM.chatB  s`    D &&')E"7#9!5 3 ' 	
 	
 }}+%	  
 
 	
r|   )truncate_prompt_tokensr   r   pooling_tasktokenization_kwargspooling_paramsrD  rE  rF  c          	      |   d}|t          |          | j        }	|	j        }
|
dk    rt          d          d}t          |t                    rQd|v rMd}| j        t          d          | j                            |          }| j                            |	          }|r| j        J t          |t                    rDg }t          |          D ]/}|                    | j                            |                     0|}nBt          |t                    rJ | j                            |          }n|t                      }|| j        vrt          d
| j         d          t          |          D ]!}|                    ||	           |||_        "|                     |||||           |                     |          }| j                            |t*                    }|rS| j        J | j                            |          }t+          t.                   d|t1          |dd          g 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 tokenization_kwargs set in
                pooling_params

        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.
        a  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"`NpoolingzvLLM.encode() is only supported for pooling models. Try passing `--runner pooling` to use the model as a pooling model.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pooling_task must be one of .)r   r   r   r   rF  r   )model_outputrI   num_cached_tokensr   )
request_idr   rM  r   finished)r   r   r   r}   r~   r   parse_requestpre_processr>   r5   r=   r  validate_or_generate_paramsr   r   verifyrD  r   r   r   r   r1   post_processr   getattr)r   r   rG  rD  r   r   rE  rF  	error_strr   r   io_processor_promptvalidated_promptvalidated_pooling_paramsparamr   model_outputsprocessed_outputss                     rz   r  z
LLM.encode  s   XO 	  Y'''(".)##!   $gt$$ 	M7):):"& ( B    $0>>wGG '33;K3LLG 	1$000.-88 @B($^44  E,33)EEeLL    ":%nh?????!%!2!N!N"" " %!.t333SD<PSSSTTT^,, 	F 	FELL|444%1/E,''!% 3 	( 	
 	
 	
 ""H"55)::)
 
  	!$000 $ 1 > >* !? ! !
 %S)!-&-)+>' ' &(!  
 
 ! r|   )rD  r   rG  r   rF  c          	          d| j         vrt          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.

        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`.)rD  r   rG  r   rE  rF  c                 6    g | ]}t          j        |          S rv   )r0   	from_baserw   items     rz   r   zLLM.embed.<locals>.<listcomp>^  s$    III4&066IIIr|   r   r   r  )r   r   rD  r   rG  r   rF  r   s           rz   r^  z	LLM.embed-  sq    B $...D  
 #9)%  3  
 
 JI5IIIIr|   )r   rG  r   rF  c                    d| j         vrt          d          |                     ||||d|          }d |D             S )aY  
        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.
            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_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
        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`.)r   rG  r   rE  rF  c                 6    g | ]}t          j        |          S rv   )r/   r`  ra  s     rz   r   z LLM.classify.<locals>.<listcomp>  s$    NNN+5d;;NNNr|   rc  )r   r   r   rG  r   rF  r   s          rz   re  zLLM.classify`  sm    > T111G  
 )%# 3  
 
 ONNNNNr|   c         	      :    |                      |||||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.
            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_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
        Returns:
            A list of `PoolingRequestOutput` objects containing the
            pooled hidden states in the same order as the input prompts.
        token_classify)r   r   rG  rD  rE  rF  )r  )r   r   rD  r   rG  r   rF  s          rz   rewardz
LLM.reward  s4    < {{%)#9) 3  
 
 	
r|   text_1text_2c	           	      b   |                      ||z   ||||d|          }	|	dt          |                   }
|	t          |          d          }t          |
          dk    r|
t          |          z  }
t          ||
|          }| j                            |t
                    }d |D             S )Nr^  )rD  r   r   rG  rE  rF  r   rJ   )rN   embed_1embed_2c                 6    g | ]}t          j        |          S rv   r3   r`  ra  s     rz   r   z(LLM._embedding_score.<locals>.<listcomp>  $    GGG$.t44GGGr|   )r  r   r    r   r   r1   )r   rN   rj  rk  rD  r   rG  r   rF  encoded_outputencoded_output_1encoded_output_2scoresr   s                 rz   _embedding_scorezLLM._embedding_score  s     6:[[VO#9%)  3 6A 6
 6
 8Fa#f++o7V7Ec&kkmm7T  A%%/#6F2G2GG#)9CS
 
 
 !226;OPPGGGGGGr|   data_1data_2score_templatec
           	         | j         }
t          |t                    rt          d          t	          |          dk    r|t	          |          z  }|t          d          }|                    d|
           t          t
                               }|pi }|                                }t          |
j
        ||           t          t                               }d t          ||          D             }|D ]\  }}t          |
|||||	          \  }}|                    dd           x}rB|                                }t!          |          }d|i|_        |                    |           n|                    |           |                    |           |                     ||||	           |                     |
          }| j                            |t.                    }d |D             S )Nz0Score API is not supported for Mistral tokenizerrJ   score)taskc                     g | ]	\  }}||f
S rv   rv   )rw   t1t2s      rz   r   z-LLM._cross_encoding_score.<locals>.<listcomp>  s     BBBFBBxBBBr|   )r   rw  rx  rN   rF  ry  token_type_idscompressed_token_type_ids)r   r   r   r   r   c                 6    g | ]}t          j        |          S rv   rp  ra  s     rz   r   z-LLM._cross_encoding_score.<locals>.<listcomp>  rq  r|   )r   r}   r;   r   r   r5   rS  r  copyr$   max_model_lenr'   r   r#   r   cloner"   extra_kwargsr  r   r   r   r   r1   )r   rN   rw  rx  rD  r   rG  r   rF  ry  r   pooling_params_listlocal_kwargsr   input_pairsqdr!  engine_promptr  r   
compressedr   r   s                           rz   _cross_encoding_scorezLLM._cross_encoding_score  s-    (i!122 	QOPPPv;;!c&kk)F!*888Ng|444"=133*0b*//11!&(>@S	
 	
 	
 z"$$BBc&&.A.ABBB 	* 	*DAq/)#$7-     A} "/!2!23CT!J!JJ~ ;'--//4^DD
'BJ&O##**62222#**>:::NN=))))''&%	 	( 	
 	
 	
 ""H"55!227<PQQGGGGGGr|   )rD  r   rG  r   r6  c         
      |  
 | j         j        }|dk    rt          d          | j        t	          fddD                       rt          d          j        r)t          j        dd          dk    rt          d	          j        s|t          d          |                                 j	        sdt          t          t                   z  t          z  ffd}	 |	|            |	|           dt          ffd
t          |t          t          f          r|g}
fd|D             }t          |t          t          f          r|g}
fd|D             }t          |t                    rd|v r|                    d          }nt          |t                    r|g}t          |t                    rd|v r|                    d          }nt          |t                    r|g}t#          ||           j        r|                     |||||||          S |                     ||||||          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.
            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_params: The pooling parameters for pooling. If None, we
                use the default pooling parameters.
            chat_template: The chat template to use for the scoring. If None, we
                use the model's default chat template.
        Returns:
            A list of `ScoringRequestOutput` objects containing the
            generated scores in the same order as the input prompts.
        rI  zuLLM.score() is only supported for pooling models. Try passing `--runner pooling` to use the model as a pooling model.c              3       K   | ]}|vV  	d S r   rv   )rw   tr   s     rz   r   zLLM.score.<locals>.<genexpr>Z  s(      GGAq'GGGGGGr|   )r^  re  zsScore API is not supported by this model. Try converting the model using `--convert embed` or `--convert classify`.
num_labelsr   rJ   z.Score API is only enabled for num_labels == 1.Nz9chat_template is only supported for cross-encoder models.rJ  c                 l    t          | t                    rd| v rt          dj                   d S d S )Ncontentz*ScoreMultiModalParam is not supported for )r}   r~   r   architecture)rJ  r   s    rz   check_data_typez"LLM.score.<locals>.check_data_types  sX    
 dD)) i4.?.?$;+8; ;   .?.?r|   r   c                 ,   t          | t                    red| v rt          d          d| v r/                    t	          t
          |           d                   } nd| v rt	          t          |           d         } t          |           t          u sJ | S )Nr   z/Multi-modal prompt is not supported for scoringr   r   )	r}   r~   r   r  r   r*   r)   r   r   )r   rN   s    rz   
ensure_strzLLM.score.<locals>.ensure_str  s    fd++ 
D)V33(M   ,v55!*!1!1 v667IJ" " "V++!%j&!9!9(!CF||s****r|   c                 &    g | ]} |          S rv   rv   rw   r  r  s     rz   r   zLLM.score.<locals>.<listcomp>  !    444jjmm444r|   c                 &    g | ]} |          S rv   rv   r  s     rz   r   zLLM.score.<locals>.<listcomp>  r  r|   r  )ry  )r   r   r   r   allis_cross_encoderrU  	hf_configr   r   r(   r   r   r}   r   r~   r   r!   r  rv  )r   rw  rx  rD  r   rG  r   r6  r   r  r  r   r   rN   s             @@@@rz   r{  z	LLM.score  s   b (".)##!   .GGGG1FGGGGG 	=   )	O.a@@AEEMNNN, 	1JK   &&((	/ )	5	%?+,&'	 	 	 	 	 	 OF###OF###?       &3+.. " 4444V444F&3+.. " 4444V444Ffd## 		V(;(;ZZ	**FF$$ 	XFfd## 		V(;(;ZZ	**FF$$ 	XF"66222( 	--&, . 	 	 	 ((&  r|   c                 8    | j                                          d S r   )r   start_profiler   s    rz   r  zLLM.start_profile  s    %%'''''r|   c                 8    | j                                          d S r   )r   stop_profiler   s    rz   r  zLLM.stop_profile  s    $$&&&&&r|   reset_running_requestsreset_connectorc                 8    | j                             ||          S r   )r   reset_prefix_cache)r   r  r  s      rz   r  zLLM.reset_prefix_cache  s#     11"O
 
 	
r|   levelc                 d    |                                   | j                            |           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  s     rz   r  z	LLM.sleep  s5    & 	!!!E*****r|   tagsc                 :    | 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  s     rz   r  zLLM.wake_up  s      	%%%%%r|   rC   c                 4    | j                                         S )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   s    rz   r  zLLM.get_metrics  s     **,,,r|   )r   r   rF  c          	          t          |t          t          f          r|g}t          |          }t          |t                    r"t          |          |k    rt          d          t          |t                    r"t          |          |k    rt          d          |6t          |          |k    r#t          d| dt          |           d          t          |t                    r|n|fD ](}t          |t                    rt          j        |_	        )|}	|r%t          |          r|nt          }
 |
|	d          }	g }	 t          |	          D ]x\  }}|                     |t          |t                    r||         n|t          |t                    r||         n||r||         nd|	          }|                    |           yd S # t          $ r%}|r| j                            |d
           |d }~ww xY w)Nz3The lengths of prompts and params must be the same.z9The lengths of prompts and lora_request must be the same.zThe lengths of prompts (z) and priority (z) must be the same.zAdding requests)r   r   r   r   rF  T)internal)r}   r   r~   r   r   r   r8   r7   
FINAL_ONLYoutput_kindcallabler	   	enumerate_add_requestr  	Exceptionr   abort_request)r   r   r   r   r   r   rF  num_requestsspit	tqdm_funcadded_request_idsr+  r   rN  r   s                   rz   r   zLLM._validate_and_add_requests  sa    gT{++ 	 iG7||fh'' 	TCKK<,G,GRSSSlH-- 	#l2C2C|2S2SK   CMM\$A$A$ $ $25h--$ $ $   'vx88G&&vi 	> 	>B"n-- >!2!=  	7$,X$6$6@DI2$5666B')	&r]] 
5 
5	6!..!+FH!=!=IF1II6!,99"&a%,4;Xa[[!(; /  
 "((4444
5 
5  	 	 	  P--.?$-OOOG	s   BG 
G= G88G=)rF  rN  r  c                    |pi }|                                 }t          | j        j        |j        |           | j                            ||||||          }||fS )z2Use the Processor to process inputs for LLMEngine.)r   rF  r   )r  r$   r   r  rD  r   process_inputs)	r   rN  r  r   r   r   rF  r  engine_requests	            rz   _process_inputszLLM._process_inputs8  s     +0b*//11!+)	
 	
 	
 -<<% 3 = 
 
 222r|   c           	          t          |          \  }}}t          t          | j                            }|                     ||||||          \  }	}| j                            ||	|||||           |	j        S )Nr  )r   rF  r   prompt_text)r+   r   nextr   r  r   add_requestrN  )
r   r   r   r   r   rF  r  r!  rN  r  s
             rz   r  zLLM._add_requestV  s     2&99Qd23344
.2.B.B% 3 /C /
 /
++ 	##% 3# 	$ 	
 	
 	
 ((r|   r   c          
         |rI| j                                         }t          |          r|nt          } ||ddddddddd          }g }d}d}| j                                         r?| j                                         }|D ]}	|	j        r|                    |	           |rt          |	t                    rt          |	j                  }
|	j        J |t          |	j                  |
z  z  }||j        d	         z  }|t          d
 |	j        D                       z  }||j        d	         z  }d|dd|dd|_        |                    |
           n|                    d           |j        |k    r|                                 
| j                                         ?|r|                                 t)          |d           S )NzProcessed promptsTzest. speed input: r   z.2fz toks/s, output: z toks/s)totalr   dynamic_ncolspostfixelapsedc              3   >   K   | ]}t          |j                  V  d S r   )r   	token_ids)rw   stps     rz   r   z"LLM._run_engine.<locals>.<genexpr>  s=       2 27:CM 2 22 2 2 2 2 2r|   rJ   c                 *    t          | j                  S r   )r   rN  )xs    rz   <lambda>z!LLM._run_engine.<locals>.<lambda>  s    S->-> r|   )r  )r   get_num_unfinished_requestsr  r	   has_unfinished_requestssteprO  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_spds                rz   r   zLLM._run_engineu  s=     	?FFHHL$,X$6$6@DI9"("TaTTTaTTTT	  D ?Ao5577 	+?//11L& + +? +NN6*** +%fm<< + #FN 3 3A#)#:#F#F#F)S1H-I-IA-MMM%2T5Ei5P%PF*c 2 2>Dn2 2 2 / / N '5t7G	7R&RG!@V J !@ !@+2 ?!@ !@ !@ !L !KKNNNN KKNNN6\11 LLNNN1 o5577 	+4  	JJLLL g#>#>????r|   c                     | j         ?| j                            d          }|r|d         | _         n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   rj   )r   resultss     rz   __repr__zLLM.__repr__  s_     $o445KLLG  N$+AJ!!$M1B1H$M$M$M!  r|   )rl   Nr   )Nrv   N)NFN)NrH   TFNNN)
NTNNrH   TFNNN)NTNNN)NTNNNN)FF)rJ   )Nr   N)T__name__
__module____qualname____doc__r   r   r   r   boolr  r   r   r.   floatr   r~   r   r   r   r   r   r   r   rB   r   r:   r   r   r8   r   r'   r   r   r	   r-   r2   r   r   r   rD   tupler   nnModuler   r*   r)   r   r6   r   r4  r   r   rA  rC  r&   r5   r9   r1   r  r0   r^  r/   re  ri  r3   rv  r   r  r(   r   r{  r  r  r  r  r  r  r   r@   r  r  r   r  rv   r|   rz   rG   rG   Y   s+       _ _J  &!' $.4$)"'(*26$%"37#)-(+ !#-2*/&*+/59-1 BFDH,0NRFJGd- d- d-d- 	d-
 d- :d- &+d- "d-  d- #&d-  $Cy4/d- "d- d- *D0d- *d-   $J!d-" #d-$ !&%d-& 'd-( )d-* +d-, '+-d-. $(/d-0 *t#1d-2 "D(3d-4 "#s(^d25d-6 $d*7d-8 $(S>
!$"
$9d-> c3h.84??d-@ sCx.?:TAAd-B  #TzCd-D  $sCx.03DDtKEd-F  d?&; ;<tCGd-H Id-J 
Kd- d- d- d-L/} / / / /) ) ) ) ^         MQEJ
 04?C%)EJ EJ EJhz22EJ ((>*BBTIEJ
 #t),,EJ ;'+5<EJ s)d"EJ 
m	EJ EJ EJ EJN"
hz22"
 ;'+5<"
 "
 "
 "
H3
3
 "D(3
 sCx.4/	3
 3
 3
 3
p !%(,M MhsBw''M M 	M
 S#X%M 
bM M M M@1")b 9 1d2h 1 1 1 1K;'+5<K lZ/0K 
kD 	!	K K K K( @D(,x xlZ/0x !x ;'+5<	x
 x :x 
	x x x x| %)HN&*',-16:59: :12
t./
01: Tz	:
 'F:  $: !%: DcN#d*: #38nt3: "#s(^d2: 
j<'	(: : : :@ IM/3+/$(HN&*',-16:59R
 R
12
t./
01R
 ($~*>>E	R

 #t),,R
 "D(R
 TzR
 'FR
  $R
 !%R
 DcN#d*R
 #38nt3R
 "#s(^d2R
 
m	R
 R
 R
 R
n JNU!
 .2/3?C+/59U! U! U!hz22Z?U! &(??$FU!
 !$d
U! #t),,U! ;'+5<U! "D(U! "#s(^d2U! 
"	#U! U! U! U!v .2/3IM?C591J 1J 1Jhz221J !$d
	1J
 #t),,1J &(??$F1J ;'+5<1J "#s(^d21J 
$	%1J 1J 1J 1Jn 04IM?C59.O .O .Ohz22.O #t),,	.O
 &(??$F.O ;'+5<.O "#s(^d2.O 
)	*.O .O .O .Oj .2/3IM?C59&
 &
 &
hz22&

 !$d
&
 #t),,&
 &(??$F&
 ;'+5<&
 "#s(^d2&
 
"	#&
 &
 &
 &
Z .2/3/3?C59 H  H  H S:%45 H S:%45	 H
 !$d
 H #t),, H &, H ;'+5< H "#s(^d2 H 
"	# H  H  H  HN .2/3/3?C59%)CH CH CH S	D!677CH S	D!677	CH
 !$d
CH #t),,CH &,CH ;'+5<CH "#s(^d2CH d
CH 
"	#CH CH CH CHV .2/3/3?C$(] ] ](?";;>RR]  (?";;>RR] !$d
] #t),,] &,] ;'+5<] Tz] 
"	#] ] ] ]~( ( ( (' ' ' ' MR
 
&*
EI
	
 
 
 
+ +3 + + + +,& &DI, & & & &
-T(^ 
- 
- 
- 
-( 04%)59; ; ;hz22Z?; 
>
"#
 =
!"; #t),,; {+k9D@; s)d"; "#s(^d2; 
; ; ; ;J 6:3 3 33 "3 .	3 "D(3 3 "#s(^d23 
 $sCx.0	13 3 3 3D ,059) )) .) "D(	)
 ) "#s(^d2) 
) ) ) )@ 9=1@ 1@ 1@(39"551@	m22	31@ 1@ 1@ 1@f!# ! ! ! ! ! !r|   rG   )ir  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.engine.arg_utilsr   vllm.entrypoints.chat_utilsr   r   $vllm.entrypoints.pooling.score.utilsr   r   r    r!   r"   r#   vllm.entrypoints.utilsr$   r%   vllm.inputsr&   r'   r(   r)   r*   vllm.inputs.parser+   vllm.loggerr,   vllm.lora.requestr-   'vllm.model_executor.layers.quantizationr.   vllm.outputsr/   r0   r1   r2   r3   vllm.platformsr4   vllm.pooling_paramsr5   vllm.sampling_paramsr6   r7   r8   
vllm.tasksr9   vllm.tokenizersr:   vllm.tokenizers.mistralr;   vllm.usage.usage_libr<   vllm.utils.collection_utilsr=   r>   vllm.utils.counterr?   vllm.v1.enginer@   vllm.v1.engine.llm_enginerA   vllm.v1.sample.logits_processorrB   vllm.v1.metrics.readerrC   r  r   rD   rG   rv   r|   rz   <module>r     se       . . . . . . . . + + + + + + + + + +           $ $ $ $ $ $       % % % % % %                           4 3 3 3 3 3              - , , , , ,                       S R R R R R R R              4 3 3 3 3 3 # # # # # # ) ) ) ) ) ) G G G G G G              , + + + + + - - - - - - T T T T T T T T T T " " " " " " ) ) ) ) ) ) 4 4 4 4 4 4 - - - - - - ; ; ; ; ; ; ; ; & & & & & & , , , , , , / / / / / / ; ; ; ; ; ; .------	X		WT3Z! Z! Z! Z! Z! Z! Z! Z! Z! Z!r|   