o
    Ơi+                     @   s0  d dl Z d dlZd dl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
 d dlmZmZ d dlZd dlZeeZdZdZdefddZdefd	d
ZdedefddZdefddZdefddZdefddZde
fddZdedede
fddZdee fddZ dedefddZ!defdd Z"dS )!    N)Path)AnyOptionalcp310z0.17.0.post1returnc                   C   s    dt jvrt jS t jdd S )Nz.nvr   )torch__version__split r
   r
   I/home/ubuntu/.local/lib/python3.10/site-packages/torch_tensorrt/_utils.pysanitized_torch_version   s
   
r   c                     sD   t jdr dd l dd l} |  }dt fdd|D S dS )Nlinuxr   z&.*libnvinfer_builder_resource_win.so.*c                 3   s    | ]	}  |V  qd S )N)match).0libre
target_libr
   r   	<genexpr>'   s    z2check_cross_compile_trt_win_lib.<locals>.<genexpr>F)sysplatform
startswithr   dllistany)r   loaded_libsr
   r   r   check_cross_compile_trt_win_lib   s   r   min_versionc              	   C   s   z<t jdkr	W dS ddlm} tjd }|dur)t|dr)t||j|| kW S ddl	m
} t||d|| kW S  ttfyH   Y d	S w )
at  
    Check if the installed TensorRT version supports the specified minimum version.
    Args:
        min_version (str): Minimum required TensorRT version
    Returns:
        bool: True if TensorRT version is >= min_version, False otherwise
    Example:
        >>> if is_tensorrt_version_supported("10.8.0"):
        ...     # Use FP4 features
        ...     pass
    tensorrt_rtxTr   )VersiontensorrtNr   )metadataF)trt_package_namepackaging.versionr   r   moduleshasattrboolr   	importlibr    versionImportError
ValueError)r   r   moduler    r
   r
   r   is_tensorrt_version_supported+   s   

r,   c                   C      t j dv r	dS dS )N))      )r/      TFr   cudaget_device_capabilityr
   r
   r
   r   is_tegra_platformI      r4   c                   C   r-   )N))   r   TFr1   r
   r
   r
   r   is_thorO   r5   r7   c               
   C   s   t   } t   }t   }d| v rtd dS |dkr%d|v s(t r/td dS z)tj	j
}|du r@td W dS tt|d	\}}|d
krVtd W dS W dS  tys } ztd|  W Y d}~dS d}~ww )aS  
    Checks if the current platform supports TensorRT-LLM plugins for the NCCL backend.

    Returns:
        bool: True if supported, False otherwise.

    Unsupported:
        - Windows platforms
        - Jetson/Orin/Xavier (aarch64 architecture + 'tegra' in platform release)
        - Thor devices
        - CUDA 13 not supported
    windowszCTensorRT-LLM plugins for NCCL backend are not supported on Windows.Faarch64tegrazfTensorRT-LLM plugins for NCCL backend are not supported on Jetson/Orin/Xavier (Tegra) or Thor devices.NzTThis pytorch build does not support CUDA, please reinstall pytorch with CUDA support.   zeCUDA 13 is not currently supported for TRT-LLM plugins. Please install pytorch with CUDA 12.x supportTzFailed to detect CUDA version: )r   systemlowermachinereleaseloggerinfor7   r   r(   r2   errormapintr	   	Exceptionwarning)r=   r?   r@   cuda_versionmajorminorer
   r
   r    is_platform_supported_for_trtllmU   s@   rL   c                  C   s   t  } tt d|   S )Ntorch_tensorrt_)getpassgetuserr   tempfile
gettempdir)usernamer
   r
   r   _cache_root   s   rS   platform_systemplatform_machinec                 C   s   t  d t d|  d|  S )Ntrtllm_)rS   _TENSORRT_LLM_VERSION_)rT   rU   r
   r
   r   _extracted_dir_trtllm   s   rY   c                  C   s>  t   } t   }dt dt dt d|  d| d}t | }t| |}d| v r.dnd}|d d	 | }| r@t	|S |j
jd
d
d |jd
d
d | sd}|| }ztd| d tj|| td W n\ tjjy }	 ztd|	j d| d|	j  W Y d}	~	n=d}	~	w tjjy }	 ztd| d|	j  W Y d}	~	nd}	~	w ty }	 ztd|	  W Y d}	~	nd}	~	ww zddl}
W n ty }	 ztdd}	~	ww z%|
|}|| td|  W d   n	1 sw   Y  W nS ty) }	 ztd| d|	  td| |	d}	~	w |
jyC }	 ztd|	  td|	d}	~	w ty\ }	 ztd|	  td|	d}	~	ww z|jd
d td |  W n ty }	 zt d!| d|	  W Y d}	~	nd}	~	ww | std"|  dS t	|S )#u  
    Returns the path to the TensorRT‑LLM shared library, downloading and extracting if necessary.

    Args:
        platform (str): Platform identifier (e.g., 'linux_x86_64')

    Returns:
        Optional[str]: Path to shared library or None if operation fails.
    ztensorrt_llm--rW   z.whlr   z!libnvinfer_plugin_tensorrt_llm.soz"libnvinfer_plugin_tensorrt_llm.dlltensorrt_llmlibsT)parentsexist_okz%https://pypi.nvidia.com/tensorrt-llm/zDownloading z ...z3Download succeeded and TRT-LLM wheel is now presentzHTTP error z when trying to download z: Nz"URL error when trying to download zLocal file write error: r   z@zipfile module is required but not found. Please install zipfilezExtracted wheel to zWheel file not found at z(Failed to find downloaded wheel file at z!Invalid or corrupted wheel file: z=Downloaded wheel file is corrupted or not a valid zip archivez)Unexpected error while extracting wheel: z8Unexpected error during extraction of TensorRT-LLM wheel)
missing_okzDeleted wheel file: zCould not delete wheel file z/Plugin library not found at expected location: )!r   r=   r>   r?   rX   _WHL_CPYTHON_VERSIONrS   rY   existsstrparentmkdirrA   debugurllibrequesturlretrieverC   	HTTPErrorcodereasonURLErrorOSErrorzipfiler)   ZipFile
extractallFileNotFoundErrorRuntimeError
BadZipFilerF   unlinkrG   )rT   rU   wheel_filename
wheel_pathextract_dirlib_filenameplugin_lib_pathbase_urldownload_urlrK   rn   zip_refr
   r
   r    download_and_get_plugin_lib_path   s   



"
r}   ry   c              
   C   s<  zt | }td|   W n3 tyB } z'dt|v r,tjd|  d| d|d ntjd|  d|d W Y d}~d	S d}~ww zt jt jg|j	_
t j|j	_W n tyl } ztjd
|d W Y d}~d	S d}~ww z|	ddr|td W dS td W d	S  ty } ztjd|d W Y d}~d	S d}~ww )z
    Loads and initializes the TensorRT-LLM plugin from the given shared library path.

    Args:
        plugin_lib_path (str): Path to the shared TensorRT-LLM plugin library.

    Returns:
        bool: True if successful, False otherwise.
    z$Successfully loaded plugin library: libmpiz6Failed to load libnvinfer_plugin_tensorrt_llm.so from z, got error zf (hint: libmpi.so is a necessary dependency; ensure that OpenMPI or MPICH is installed on your system))exc_infoz;. Ensure the path is correct and the library is compatible.NFz4Unable to initialize the TensorRT-LLM plugin librarys   tensorrt_llmz,TensorRT-LLM plugin successfully initializedTz4TensorRT-LLM plugin library failed in initializationzDException occurred during TensorRT-LLM plugin library initialization)ctypesCDLLrA   rB   rm   rb   rG   c_void_pc_char_pinitTrtLlmPluginsargtypesc_boolrestypeAttributeErrorrF   )ry   handle
e_os_errore_plugin_unavailablee_initialization_errorr
   r
   r   !load_and_initialize_trtllm_plugin   sR   




r   c                  C   sX   t  sdS tjd} | rt| S tjdd dv }|s%td dS t } t| S )as  
    Attempts to load the TensorRT-LLM plugin and initialize it.
    Either the env variable TRTLLM_PLUGINS_PATH can specify the path
    Or the user can specify USE_TRTLLM_PLUGINS as either of (1, true, yes, on) to download the TRT-LLM distribution and load it

    Returns:
        bool: True if the plugin was successfully loaded and initialized, False otherwise.
    FTRTLLM_PLUGINS_PATHUSE_TRTLLM_PLUGINS0)1trueyesonzNeither TRTLLM_PLUGIN_PATH is set nor is it directed to download the shared library. Please set either of the two to use TRT-LLM libraries in torchTRT)	rL   osenvirongetr   r>   rA   rG   r}   )ry   use_trtllm_pluginr
   r
   r   load_tensorrt_llm_for_nccl(  s   	r   )#r   rN   loggingr   r   r   rP   urllib.requestrf   pathlibr   typingr   r   r   r!   r   	getLogger__name__rA   r`   rX   r   r&   r   rb   r,   r4   r7   rL   rS   rY   r}   r   r   r
   r
   r
   r   <module>   s4    
5\5