o
    	TiVq                  
   @   s"  d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
 d dlmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d dlZd d
lmZ d dlmZ d dlmZmZmZmZm Z  e rkd dl!m"Z" e rtd dl#m$Z$ e r{d dl%Z%e rd dl&m'Z' e  rd dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0 d dl1m2Z2 d dl3m4Z4 e rd dl5m6Z, e7e8Z9dej:d< G dd dZ;e	G dd dZ<de<de=de=d ed!df
d"d#Z>d$e?d%e=d!e?e? fd&d'Z@de<fd(d)ZAd.d*e jBfd+d,ZCe8d-kreC ZDeDE \ZFeAeF dS dS )/    N)Sequence)asynccontextmanager)	dataclassfield)BytesIO)chain)PipeProcess)
Connection)Optional)is_vision_available)	TrlParser)is_fastapi_availableis_pydantic_availableis_uvicorn_availableis_vllm_ascend_availableis_vllm_available)FastAPI)	BaseModel)Image)LLMSamplingParams)PyNcclCommunicator)get_world_group)StatelessProcessGroup)GuidedDecodingParams)get_open_port)PyHcclCommunicatorspawnVLLM_WORKER_MULTIPROC_METHODc                
   @   s^   e Zd ZdZdZdZdededededdf
dd	Zd
edede	e ddfddZ
dddZdS )WeightSyncWorkerExtensiona  
    A vLLM worker extension that enables weight synchronization between a client and multiple server workers.

    This worker uses a `StatelessProcessGroup` to establish communication and a `PyNcclCommunicator` to handle
    efficient GPU-based communication using NCCL. The primary purpose of this class is to receive updated model weights
    from a client process and distribute them to all worker processes participating in model inference.
    Nhostport
world_sizeclient_device_uuidreturnc                 C   sr   | j dur	td|ttj| jjkrtd| dt j	}t
j||||d}t|| jd| _ |d | _dS )a  
        Initializes the weight update communicator using a stateless process group.

        This method creates a `StatelessProcessGroup` that allows external training processes to communicate with vLLM
        workers without interfering with the global torch distributed group.

        Args:
            host (`str`):
                Hostname or IP address of the master node.
            port (`int`):
                Port number to be used for communication.
            world_size (`int`):
                Total number of participating processes in the update group.
            client_device_uuid (`str`):
                UUID of the device of client main process. Used to assert that devices are different from vllm workers devices.
        NzGWeight update group already initialized. Call close_communicator first.z.Attempting to use the same CUDA device (UUID: z) for multiple distinct roles/ranks within the same communicator. This setup is unsupported and will likely lead to program hangs or incorrect behavior. Ensure that trainer is using different devices than vLLM server.)r!   r"   rankr#   )device   )pynccl_commRuntimeErrorstrtorchcudaget_device_propertiesr'   uuidr   r&   r   creater   client_rank)selfr!   r"   r#   r$   r&   pg r4   J/home/ubuntu/.local/lib/python3.10/site-packages/trl/scripts/vllm_serve.pyinit_communicatorZ   s   

z+WeightSyncWorkerExtension.init_communicatornamedtypeshapec                 C   sp   | j du r	tdtt|dd }tj||| jd}| j j|| jd | j j	
  | jjj||fgd dS )a  
        Receives updated weights from the client process and updates the named parameter in the model.

        Args:
            name (`str`):
                Name of the weight tensor being updated.
            dtype (`str`):
                Data type of the weight tensor as a string (e.g., `"torch.float32"`).
            shape (`Sequence[int]`):
                Shape of the weight tensor.
        Nz=Communicator not initialized. Call `init_communicator` first..)r8   r'   )src)weights)r)   r*   getattrr,   splitemptyr'   	broadcastr1   groupbarriermodel_runnermodelload_weights)r2   r7   r8   r9   weightr4   r4   r5   update_named_param   s   
z,WeightSyncWorkerExtension.update_named_paramc                 C   s"   | j dur| ` d| _ d| _dS dS )z
        Closes the communicator when weight synchronization is no longer needed.

        This method deletes the NCCL communicator to release associated resources.
        N)r)   r1   )r2   r4   r4   r5   close_communicator   s
   

z,WeightSyncWorkerExtension.close_communicator)r%   N)__name__
__module____qualname____doc__r)   r1   r+   intr6   r   rH   rI   r4   r4   r4   r5   r    M   s    	&r    c                   @   s  e Zd ZU dZeddidZeed< edddidZe	e ed	< ed
ddidZ
eed< ed
ddidZeed< edddidZeed< edddidZeed< edddidZeed< edddidZeed< edddidZe	e ed< edddidZe	e ed< eddd idZe	e ed!< eddd"idZeed#< eddd$idZeed%< ed&dd'idZeed(< ed)dd*idZeed+< dS ),ScriptArgumentsa  
    Arguments for the script.

    Args:
        model (`str`):
            Model name or path to load the model from.
        revision (`str` or `None`, *optional*, defaults to `None`):
            Revision to use for the model. If not specified, the default branch will be used.
        tensor_parallel_size (`int`, *optional*, defaults to `1`):
            Number of tensor parallel workers to use.
        data_parallel_size (`int`, *optional*, defaults to `1`):
            Number of data parallel workers to use.
        host (`str`, *optional*, defaults to `"0.0.0.0"`):
            Host address to run the server on.
        port (`int`, *optional*, defaults to `8000`):
            Port to run the server on.
        gpu_memory_utilization (`float`, *optional*, defaults to `0.9`):
            Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache on the
            device dedicated to generation powered by vLLM. 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
            during initialization.
        dtype (`str`, *optional*, defaults to `"auto"`):
            Data type to use for vLLM generation. If set to `"auto"`, the data type will be automatically determined
            based on the model configuration. Find the supported values in the vLLM documentation.
        max_model_len (`int` or `None`, *optional*, defaults to `None`):
            If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced
            `vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model
            context size, which might be much larger than the KV cache, leading to inefficiencies.
        enable_prefix_caching (`bool` or `None`, *optional*, defaults to `None`):
            Whether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the hardware support
            this feature.
        enforce_eager (`bool`, *optional*, defaults to `False`):
            Whether to enforce eager execution. If set to `True`, we will disable CUDA graph and always execute the
            model in eager mode. If `False` (default behavior), we will use CUDA graph and eager execution in hybrid.
        vllm_model_impl (`str`, *optional*, defaults to `"vllm"`):
            Model implementation to use for vLLM. Must be one of `"transformers"` or `"vllm"`. `"transformers"`: Use
            the `transformers` backend for model implementation. `"vllm"`: Use the `vllm` library for model
            implementation.
        kv_cache_dtype (`str`, *optional*, defaults to `"auto"`):
            Data type to use for KV cache. If set to `"auto"`, the dtype will default to the model data type.
        trust_remote_code (`bool`, *optional*, defaults to `False`):
            Whether to trust remote code when loading models. Set to `True` to allow executing code from model
            repositories. This is required for some custom models but introduces security risks.
        log_level (`str`, *optional*, defaults to `"info"`):
            Log level for uvicorn. Possible choices: `"critical"`, `"error"`, `"warning"`, `"info"`, `"debug"`,
            `"trace"`.
    helpz*Model name or path to load the model from.)metadatarE   NzQRevision to use for the model. If not specified, the default branch will be used.)defaultrQ   revisionr(   z)Number of tensor parallel workers to use.tensor_parallel_sizez'Number of data parallel workers to use.data_parallel_sizez0.0.0.0z"Host address to run the server on.r!   i@  zPort to run the server on.r"   g?aQ  Ratio (between 0 and 1) of GPU memory to reserve for the model weights, activations, and KV cache on the device dedicated to generation powered by vLLM. 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 during initialization.gpu_memory_utilizationautozData type to use for vLLM generation. If set to 'auto', the data type will be automatically determined based on the model configuration. Find the supported values in the vLLM documentation.r8   a  If set, the `max_model_len` to use for vLLM. This can be useful when running with reduced `vllm_gpu_memory_utilization`, leading to a reduced KV cache size. If not set, vLLM will use the model context size, which might be much larger than the KV cache, leading to inefficiencies.max_model_lenzxWhether to enable prefix caching in vLLM. If set to `True`, ensure that the model and the hardware support this feature.enable_prefix_cachingFzWhether to enforce eager execution. If set to `True`, we will disable CUDA graph and always execute the model in eager mode. If `False` (default behavior), we will use CUDA graph and eager execution in hybrid.enforce_eagerz_Data type to use for KV cache. If set to 'auto', the dtype will default to the model data type.kv_cache_dtypezWhether to trust remote code when loading models. Set to True to allow executing code from model repositories. This is required for some custom models but introduces security risks.trust_remote_codeinfozbLog level for uvicorn. Possible choices: 'critical', 'error', 'warning', 'info', 'debug', 'trace'.	log_levelvllmzModel implementation to use for vLLM. Must be one of `transformers` or `vllm`. `transformers`: Use the `transformers` backend for model implementation. `vllm`: Use the `vllm` library for model implementation.vllm_model_impl)rJ   rK   rL   rM   r   rE   r+   __annotations__rS   r   rT   rN   rU   r!   r"   rV   floatr8   rX   rY   boolrZ   r[   r\   r^   r`   r4   r4   r4   r5   rO      s   
 0	rO   script_argsdata_parallel_rankmaster_port
connectionr%   c                 C   s  t |tjd< t |tjd< t | jtjd< t |tjd< t| j| j| j| j| j	| j
| j| j| jd| j| jd}|ddi 	 z| }W n tyV   |jd
d Y d S w |d dv r|d }|dd|di }}t||}	|	|i |}
|d dkr||
 n|d dkrd S q@)NVLLM_DP_RANKVLLM_DP_RANK_LOCALVLLM_DP_SIZEVLLM_DP_MASTER_PORTz0trl.scripts.vllm_serve.WeightSyncWorkerExtension)rE   rS   rT   rV   rZ   r8   rY   r[   rX   worker_extension_clsr\   
model_implstatusreadyTrI   )methodtype)callfire_and_forgetrp   argsr4   kwargsrr   shutdown)r+   osenvironrU   r   rE   rS   rT   rV   rZ   r8   rY   r[   rX   r\   r`   sendrecvKeyboardInterruptcollective_rpcgetr>   )rd   re   rf   rg   llmcommandmethod_namert   ru   rp   resultr4   r4   r5   
llm_worker5  sJ   

r   lstnc                    s,   t t|\  fddt|D S )aI  
    Split list `lst` into `n` evenly distributed sublists.

    Example:
    ```python
    >>> chunk_list([1, 2, 3, 4, 5, 6], 2)
    [[1, 2, 3], [4, 5, 6]]

    >>> chunk_list([1, 2, 3, 4, 5, 6], 4)
    [[1, 2], [3, 4], [5], [6]]

    >>> chunk_list([1, 2, 3, 4, 5, 6], 8)
    [[1], [2], [3], [4], [5], [6], [], []]
    ```
    c                    s<   g | ]}|  t | |d    t |d    qS )r(   )min).0ikr   rr4   r5   
<listcomp>x  s   < zchunk_list.<locals>.<listcomp>)divmodlenrange)r   r   r4   r   r5   
chunk_listg  s   r   c                    s  t  stdt stdt stdt stdt }g  g tjD ]}t \}}t	t
|||fd}|   | | q(tdtf fdd}t|d	}|d
dd }|dfdd}	G dd dt}
G dd dt}|jd|dd|
f fdd}G dd dt}|dd|f fdd}G dd dt}|d d|f fd!d"}|d# fd$d%}|d& fd'd(}tj|jjjd) d S )*Nz`FastAPI is required to run the vLLM serve script. Please install it using `pip install fastapi`.zbPydantic is required to run the vLLM serve script. Please install it using `pip install pydantic`.z`Uvicorn is required to run the vLLM serve script. Please install it using `pip install uvicorn`.zZvLLM is required to run the vLLM serve script. Please install it using `pip install vllm`.)targetrt   appc                   s   t  }t|jk r, D ]}| }t|tr$|ddkr$|| qt|jk sd V  D ]}|jdd |	 rNt
d| d |  |  q1d S )Nrn   ro   
   )timeoutzProcess z< is still alive after 10 seconds, attempting to terminate...)setr   rU   rz   
isinstancedictr}   addjoinis_aliveloggerwarning	terminate)r   ready_connectionsrg   msgprocessconnections	processesrd   r4   r5   lifespan  s$   
zmain.<locals>.lifespan)r   z/health/c                      s
   ddiS )zM
        Health check endpoint to verify that the server is running.
        rn   okr4   r4   r4   r4   r5   health  s   zmain.<locals>.healthz/get_world_size/c                      s   d j  j iS )a"  
        Retrieves the world size of the LLM engine, which is `tensor_parallel_size * data_parallel_size`.

        Returns:
            `dict`:
                A dictionary containing the world size.

        Example response:
        ```json
        {"world_size": 8}
        ```
        r#   )rT   rU   r4   )rd   r4   r5   get_world_size  s   zmain.<locals>.get_world_sizec                   @   s   e Zd ZU ee ed< dZeee  ed< dZe	ed< dZ
eed< dZeed< dZeed	< d
Ze	ed< dZeed< dZe	ed< dZee ed< eedZeed< dS )zmain.<locals>.GenerateRequestpromptsNimagesr(   r   g      ?repetition_penaltytemperaturetop_pr;   top_kg        min_p   
max_tokensguided_decoding_regex)default_factorygeneration_kwargs)rJ   rK   rL   listr+   ra   r   r   r   rN   r   rb   r   r   r   r   r   r   r   r   r   r4   r4   r4   r5   GenerateRequest  s   
 r   c                   @   s   e Zd ZU eee  ed< dS )zmain.<locals>.GenerateResponsecompletion_idsN)rJ   rK   rL   r   rN   ra   r4   r4   r4   r5   GenerateResponse  s   
 r   z
/generate/)response_modelrequestc              	      sT  | j pdgt| j | _ g }t| j| j D ]\}}d|i}|dur0dttt|i|d< |	| q| j
durCtd| j
d}nd}| j| j| j| j| j| j| j|d}|| j tdi |}t|j}t |D ]\}	}|sxdg}||d	}
|	d
d|
d qodd  D }dd t||D }tt|}dd |D }d|iS )a`  
        Generates completions for the provided prompts.

        Args:
            request (`GenerateRequest`):
                - `prompts` (list of `str`): A list of prompts (text strings) for the model to generate completions.
                - `images` (list of `str`, *optional*, default to `None`): A list of base64 encoded images to process along with prompts.
                - `n` (`int`, *optional*, defaults to `1`): Number of completions to generate for each prompt.
                - `repetition_penalty` (`float`, *optional*, defaults to `1.0`): Repetition penalty to apply during generation.
                - `temperature` (`float`, *optional*, defaults to `1.0`): Temperature for sampling. Higher values lead to more random outputs.
                - `top_p` (`float`, *optional*, defaults to `1.0`): Top-p (nucleus) sampling parameter. It controls the diversity of the generated text.
                - `top_k` (`int`, *optional*, defaults to `-1`): Top-k sampling parameter. If set to `-1`, it disables top-k sampling.
                - `min_p` (`float`, *optional*, defaults to `0.0`): Minimum probability threshold for sampling.
                - `max_tokens` (`int`, *optional*, defaults to `16`): Maximum number of tokens to generate for each completion.
                - `guided_decoding_regex` (`str`, *optional*): A regex pattern for guided decoding. If provided, the model will only generate tokens that match this regex pattern.
                - `generation_kwargs` (`dict`, *optional*): Additional generation parameters to pass to the vLLM `SamplingParams`. This can include parameters like `seed`, `frequency_penalty`, etc. If it contains keys that conflict with the other parameters, they will override them.

        Returns:
            `GenerateResponse`:
                - `completion_ids` (list of list of `int`): A list of lists of token IDs for each generated completion.

        Example request:
        ```json
        {"prompts": ["Hello world", "What is AI?"]}
        ```

        Example response:
        ```json
        {"completion_ids": [[101, 102, 103], [201, 202, 203]]}
        ```
        Npromptimagemulti_modal_dataoutlines)backendregex)r   r   r   r   r   r   r   guided_decodingz<placeholder>)r   sampling_paramsrr   generaterq   rp   ru   c                 S      g | ]}|  qS r4   rz   r   rg   r4   r4   r5   r   "      z*main.<locals>.generate.<locals>.<listcomp>c                 S   s   g | ]\}}|r|qS r4   r4   )r   outputr   r4   r4   r5   r   %  s    c                 S   s"   g | ]}|j D ]}t|jqqS r4   )outputsr   	token_ids)r   r   r   r4   r4   r5   r   )  s   " r   r4   )r   r   r   zipr   openr   base64	b64decodeappendr   r   r   r   r   r   r   r   r   updater   r   r   rU   ry   r   r   from_iterable)r   r   r   r   rowr   r   r   chunked_promptsrg   ru   all_outputsr   r   rd   r4   r5   r     sB   !


zmain.<locals>.generatec                   @   s.   e Zd ZU eed< eed< eed< eed< dS )z%main.<locals>.InitCommunicatorRequestr!   r"   r#   r$   N)rJ   rK   rL   r+   ra   rN   r4   r4   r4   r5   InitCommunicatorRequest,  s
   
 r   z/init_communicator/c                    sN   j j d }d| j| j|| jfd} D ]}|dd|d qddiS )	ae  
        Initializes the communicator for synchronizing model weights between a client and multiple server workers.

        Args:
            request (`InitCommunicatorRequest`):
                - `host` (`str`): Hostname or IP address of the master node.
                - `port` (`int`): Port number to be used for communication.
                - `world_size` (`int`): Total number of participating processes in the group.
                - `client_device_uuid` (`str`): UUID of the device of client main process. Used to assert that devices
                  are different from vLLM workers devices.
        r(   r6   rp   rt   rs   r|   r   messagez+Request received, initializing communicator)rT   rU   r!   r"   r$   ry   )r   r#   ru   rg   r   r4   r5   r6   2  s   zmain.<locals>.init_communicatorc                   @   s*   e Zd ZU eed< eed< ee ed< dS )z"main.<locals>.UpdateWeightsRequestr7   r8   r9   N)rJ   rK   rL   r+   ra   r   rN   r4   r4   r4   r5   UpdateWeightsRequestM  s   
 r   z/update_named_param/c                    s@   d| j | jt| jfd} D ]}|dd|d qddiS )a  
        Updates the model weights with the provided tensor.

        Once this endpoint is called, the client process should broadcast the updated weights to all server workers.

        Args:
            request (`UpdateWeightsRequest`):
                - `name` (`str`): Name of the weight tensor being updated.
                - `dtype` (`str`): Data type of the weight tensor (e.g., `"torch.float32"`).
                - `shape` (list of `int`): Shape of the weight

        rH   r   rs   r|   r   r   z*Request received, updating named parameter)r7   r8   tupler9   ry   )r   ru   rg   r   r4   r5   rH   R  s
   z main.<locals>.update_named_paramz/reset_prefix_cache/c                     sL    D ]
} |  ddd qdd  D }tdd |D }dd	t| iS )
z8
        Resets the prefix cache for the model.
        rr   reset_prefix_cache)rq   rp   c                 S   r   r4   r   r   r4   r4   r5   r   q  r   z4main.<locals>.reset_prefix_cache.<locals>.<listcomp>c                 s   s    | ]}|V  qd S Nr4   )r   r   r4   r4   r5   	<genexpr>r  s    z3main.<locals>.reset_prefix_cache.<locals>.<genexpr>r   z1Request received, resetting prefix cache status: )ry   allr+   )rg   r   successr   r4   r5   r   i  s   z main.<locals>.reset_prefix_cachez/close_communicator/c                     s.   ddi}  D ]}| dd| d qddiS )zT
        Closes the weight update group and cleans up associated resources.
        rp   rI   rs   r|   r   r   z&Request received, closing communicator)ry   )ru   rg   r   r4   r5   rI   u  s
   z main.<locals>.close_communicator)r!   r"   r^   )r   ImportErrorr   r   r   r   r   rU   r   r	   r   startr   r   r   r}   r   postuvicornrunr!   r"   r^   )rd   rf   re   parent_connectionchild_connectionr   r   r   r   r   r   r   r   r   r6   r   rH   r   rI   r4   r   r5   main{  sZ   



T
r   
subparsersc                 C   s(   | d ur| j ddtd}|S tt}|S )Nz
vllm-servezRun the vLLM serve script)rP   dataclass_types)
add_parserrO   r   )r   parserr4   r4   r5   make_parser  s
   r   __main__r   )Gargparser   loggingrw   collections.abcr   
contextlibr   dataclassesr   r   ior   	itertoolsr   multiprocessingr   r	   multiprocessing.connectionr
   typingr   r,   transformersr   trlr   trl.import_utilsr   r   r   r   r   fastapir   pydanticr   r   PILr   r_   r   r   ,vllm.distributed.device_communicators.pyncclr   vllm.distributed.parallel_stater   vllm.distributed.utilsr   vllm.sampling_paramsr   
vllm.utilsr   3vllm_ascend.distributed.device_communicators.pyhcclr   	getLoggerrJ   r   rx   r    rO   rN   r   r   r   r   _SubParsersActionr   r   parse_args_and_configrd   r4   r4   r4   r5   <module>   sx   	

Z 
2  


