o
    :/i&                     @  sV  d dl mZ d dlZd dlZd dlZd dlZd dl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 d dlmZ d d	lmZ d
dlmZmZ eeZdZdZdAddZ ej!dBddZ"ej!dd Z#dCddZ$d d! Z%d"d# Z&d$d% Z'd&ej(fdDd+d,Z)dEd2d3Z*dFdGd6d7Z+dHd8d9Z,dIdJd<d=Z-dKd?d@Z.dS )L    )annotationsN)CallableIterator)Path)TextIO)init_logger)current_platform)in_wsl)is_in_ray_actor   )cuda_is_initializedxpu_is_initializedz[0;36mz[0;0m	envs_dictdict[str, str]c                 C  sN   |   D ] \}}|tjv rtj| |krtd|tj| | |tj|< qdS )z3Update multiple environment variables with logging.z5Overwriting environment variable %s from '%s' to '%s'N)itemsosenvironloggerwarning)r   kv r   d/lsinfo/ai/hellotax_ai/llm_service/venv_vllm/lib/python3.10/site-packages/vllm/utils/system_utils.pyupdate_environment_variables"   s   r   keystrvaluereturnIterator[None]c              
   c  sn    t j| }|t j| < zdV  W |du rt j| d dS |t j| < dS |du r1t j| d w |t j| < w )z(Temporarily set an environment variable.N)r   r   getpop)r   r   oldr   r   r   set_env_var/   s   
r"   c               
   c  s    t jdkrdV  dS tj } t| }ttjtj	}z&tj
  t||  dV  W tj
  t||  t| t| dS tj
  t||  t| t| w )a  
    Suppress stdout from C libraries at the file descriptor level.

    Only suppresses stdout, not stderr, to preserve error messages.
    Suppression is disabled when VLLM_LOGGING_LEVEL is set to DEBUG.

    Example:
        with suppress_stdout():
            # C library calls that would normally print to stdout
            torch.distributed.new_group(ranks, backend="gloo")
    DEBUGN)envsVLLM_LOGGING_LEVELsysstdoutfilenor   dupopendevnullO_WRONLYflushdup2close)	stdout_fd
stdout_dup
devnull_fdr   r   r   suppress_stdout=   s&   







r3   fnCallable[[int], Path]r   c                 C  s$   d}	 | |}|  s|S |d7 }q)zGenerate a unique file path by trying incrementing integers.

    Note: This function has a TOCTOU race condition.
    Caller should use atomic operations (e.g., open with 'x' mode)
    when creating the file to ensure thread safety.
    r   Tr   )exists)r4   ipr   r   r   unique_filepatha   s   r9   c                  C  s"   t  sdS ddlm}  |   dS )z>Sync HIP/CUDA visibility env vars before spawning (ROCm only).Nr   _sync_hip_cuda_env_vars)r   is_rocmvllm.platforms.rocmr;   r:   r   r   r   _sync_visible_devices_env_varss   s   
r>   c                  C  s   t jddkr
dS g } t r ddl}| jt jd< | d t r)| d nt	 r1| d t
 r9| d	 | rKtd
d|  dt jd< dS dS )zWCheck if we need to force the use of the `spawn` multiprocessing start
    method.
    VLLM_WORKER_MULTIPROC_METHODspawnNr   RAY_ADDRESSz&In a Ray actor and can only be spawnedzCUDA is initializedzXPU is initializedz4WSL is detected and NVML is not compatible with forkzWe must use the `spawn` multiprocessing start method. Overriding VLLM_WORKER_MULTIPROC_METHOD to 'spawn'. See https://docs.vllm.ai/en/latest/usage/troubleshooting.html#python-multiprocessing for more information. Reasons: %sz; )r   r   r   r
   rayget_runtime_contextgcs_addressappendr   r   r	   r   r   join)reasonsrB   r   r   r   _maybe_force_spawn~   s(   


rH   c                  C  s   t   t  tj} t| S )aJ  Get a multiprocessing context with a particular method (spawn or fork).
    By default we follow the value of the VLLM_WORKER_MULTIPROC_METHOD to
    determine the multiprocessing method (default is fork). However, under
    certain conditions, we may enforce spawn and override the value of
    VLLM_WORKER_MULTIPROC_METHOD.
    )rH   r>   r$   r?   multiprocessingget_context)	mp_methodr   r   r   get_mp_context   s   
rL    namesuffixprefixNonec                 C  sL   zddl }W n
 ty   Y dS w |r|  d| } | | d|   dS )z3Set the current process title with optional suffix.r   N_z::)setproctitleImportError)rN   rO   rP   rS   r   r   r   set_process_title   s   rU   filer   worker_namepidintc                   s   t  do  }tjstjdkstjdkr"|s"d| d| dnt d| d| dt dt d	 jd fdd}d _	 _
| _dS )z5Add colored prefix to file output for log decoration.isatty01(z pid=z) ) _original_writesr   c                   s   | sd S  j r d}| d| }dkr>|d7 }| ||  |t| kr.d _ d S  |}| d| }dks| |d   d _ d S )Nr   
r   TF)start_new_linefindlen)ra   idxnext_idxrV   
file_writerP   r   r   write_with_prefix   s    
z&_add_prefix.<locals>.write_with_prefixTN)ra   r   )hasattrrZ   r$   NO_COLORVLLM_LOGGING_COLORCYANRESETgetattrwriterd   r`   )rV   rW   rX   is_ttyrk   r   ri   r   _add_prefix   s   

rt   process_name
str | Nonec                 C  sF   t jsdS | du rt  j} t }ttj	| | ttj
| | dS )z8Decorate stdout/stderr with process name and PID prefix.N)r$   VLLM_CONFIGURE_LOGGINGrL   current_processrN   r   getpidrt   r&   r'   stderr)ru   rX   r   r   r   decorate_logs   s   r{   c              	   C  s   zt | }W n t jy   Y dS w |jdd}|D ]}tt t|j	t
j W d   n1 s5w   Y  qtt t| t
j W d   dS 1 sSw   Y  dS )z
    Kills all descendant processes of the given pid by sending SIGKILL.

    Args:
        pid (int): Process ID of the parent process
    NT)	recursive)psutilProcessNoSuchProcesschildren
contextlibsuppressProcessLookupErrorr   killrX   signalSIGKILL)rX   parentr   childr   r   r   kill_process_tree   s   "r     target_soft_limitc              
   C  s   t jdrtd d S dd l}|j}||\}}|| k rEz||| |f W d S  t	yD } zt
d|| W Y d }~d S d }~ww d S )Nwinz-Windows detected, skipping ulimit adjustment.r   zFound ulimit of %s and failed to automatically increase with error %s. This can cause fd limit errors like `OSError: [Errno 24] Too many open files`. Consider increasing with ulimit -n)r&   platform
startswithr   inforesourceRLIMIT_NOFILE	getrlimit	setrlimit
ValueErrorr   )r   r   resource_typecurrent_softcurrent_harder   r   r   
set_ulimit  s$   
r   lib_namec                 C  s   d}t d}|D ]
}| |v r|} nq	W d   n1 sw   Y  |du r)dS |d}||d  }|dd }|dd | sQJ d| d|  |S )	a'  
    According to according to https://man7.org/linux/man-pages/man5/proc_pid_maps.5.html,
    the file `/proc/self/maps` contains the memory maps of the process, which includes the
    shared libraries loaded by the process. We can use this file to find the path of the
    loaded library.
    Nz/proc/self/maps/rc   z.sor   zUnexpected filename: z for library )r*   indexstripsplit
rpartitionr   )r   
found_lineflinestartpathfilenamer   r   r   find_loaded_library+  s$   

r   )r   r   )r   r   r   r   r   r   )r4   r5   r   r   )rN   r   rO   r   rP   r   r   rQ   )rV   r   rW   r   rX   rY   r   rQ   )N)ru   rv   r   rQ   )rX   rY   )r   )r   rY   )r   r   r   rv   )/
__future__r   r   rI   r   r   r&   collections.abcr   r   pathlibr   typingr   r}   	vllm.envsr$   vllm.loggerr   vllm.platformsr   vllm.platforms.interfacer	   vllm.ray.lazy_utilsr
   platform_utilsr   r   __name__r   ro   rp   r   contextmanagerr"   r3   r9   r>   rH   rL   VLLM_PROCESS_NAME_PREFIXrU   rt   r{   r   r   r   r   r   r   r   <module>   sH   


#%
$
