a
    ßñh* ã                   @   sØ  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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 ddlmZ ddlmZmZ d dlmZmZ d dlmZ ejd	kZeee  ee d
œdd„Zee dœdd„Z ee dœdd„Z!edœdd„Z"dZ#dZ$dZ%dZ&e!ƒ Z'e'�r<e"dƒndZ(e'du�r\ej)j*du�r\dndZ+dZ,ej)j*du�r–e-dd„ ej)j* .d¡dd… D ƒƒZ,e ƒ Z/ej0 1d¡�p´ej0 1d ¡Z2e 3d!¡Z4g d"¢Z5g d#¢Z6g d$¢Z7g d%¢Z8eƒ Z9d&d'd(œZ:e;dœd)d*„Z<ee dœd+d,„Z=edœd-d.„Z>ee;d/œd0d1„Z?e;dœd2d3„Z@G d4d5„ d5eeAƒZBd6d7„ ZCd8d9„ ZDdke;ee d:œd;d<„ZEdle;ee d:œd=d>„ZFdmee ee; d?œd@dA„ZGdndBdC„ZHdoee;ee; ddDœdEdF„ZIee ee;ee; ddGœdHdI„ZJee ee;ee; ddGœdJdK„ZKdLdM„ ZLdNdO„ ZMdPdQ„ ZNdpeee  ee dRœdSdT„ZOdqeee  ee dRœdUdV„ZPee;edWœdXdY„ZQe;eeR dZœd[d\„ZSee;edd]œd^d_„ZTd`da„ ZUddœdbdc„ZVddœddde„ZWedœdfdg„ZXee;dhœdidj„ZYdS )ré    Né   )Ú	FileBaton)ÚExtensionVersioner)Úhipify_python)Úget_hip_file_pathÚGeneratedFileCleaner)ÚListÚOptional)Ú	build_extÚwin32)ÚargsÚreturnc                 C   s   | sg S dd„ | D ƒS )zªQuote command-line arguments for DOS/Windows conventions.

    Just wraps every argument which contains blanks in double quotes, and
    returns a new argument list.
    c                 S   s$   g | ]}d |v rd|› d�n|‘qS )ú ú"© )Ú.0Úargr   r   úY/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/utils/cpp_extension.pyÚ
<listcomp>&   ó    z"_nt_quote_args.<locals>.<listcomp>r   )r   r   r   r   Ú_nt_quote_args   s    r   ©r   c                  C   sþ   t j d¡pt j d¡} | du rÞzltr*dnd}tt jdƒ�@}tj|dg|d� ¡  	d	¡}t j
 t j
 |¡¡} W d  ƒ n1 s€0    Y  W nP tyÜ   trÄt d
¡}t|ƒdkrºd} qÈ|d } nd} t j
 | ¡sØd} Y n0 | rútj ¡ sútd | ¡ƒ | S )zFinds the CUDA install path.Ú	CUDA_HOMEZ	CUDA_PATHNÚwhereÚwhichÚwÚnvcc©Ústderrú
z7C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v*.*r   Ú z/usr/local/cudaz.No CUDA runtime is found, using CUDA_HOME='{}')ÚosÚenvironÚgetÚ
IS_WINDOWSÚopenÚdevnullÚ
subprocessÚcheck_outputÚdecodeÚrstripÚpathÚdirnameÚ	ExceptionÚglobÚlenÚexistsÚtorchÚcudaZis_availableÚprintÚformat)Z	cuda_homer   r&   r   Z
cuda_homesr   r   r   Ú_find_cuda_home(   s2    
ÿ
ÿ6ÿ

r5   c                  C   s¼   t j d¡pt j d¡} | du ršzRtjddgtjd� ¡  d¡}t j 	t j 	|¡¡} t j 
| ¡dkrpt j 	| ¡} W n& ty˜   d	} t j | ¡s”d} Y n0 | r¸tjjdu r¸td
 | ¡ƒ | S )zFinds the ROCm install path.Ú	ROCM_HOMEZ	ROCM_PATHNr   Úhipccr   r   Úhipz	/opt/rocmz.No ROCm runtime is found, using ROCM_HOME='{}')r!   r"   r#   r'   r(   ÚDEVNULLr)   r*   r+   r,   Úbasenamer-   r0   r1   Úversionr8   r3   r4   )Z	rocm_homer7   r   r   r   Ú_find_rocm_homeE   s$    
ÿ
ÿ
r<   c                  G   s2   t du rtdƒ‚ntrtdƒ‚tjjt g| ¢R Ž S )zÖ
    Joins paths with ROCM_HOME, or raises an error if it ROCM_HOME is not set.

    This is basically a lazy way of raising an error for missing $ROCM_HOME
    only once we need to get any ROCm-specific path.
    NzSROCM_HOME environment variable is not set. Please set it to your ROCm install root.zDBuilding PyTorch extensions using ROCm and Windows is not supported.)r6   ÚEnvironmentErrorr$   r!   r+   Újoin©Úpathsr   r   r   Ú_join_rocm_home\   s
    
rA   )é   r   r   )é   r   i—^  a8  

                               !! WARNING !!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Your compiler ({}) may be ABI-incompatible with PyTorch!
Please use a compiler that is ABI-compatible with GCC 5.0 and above.
See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html.

See https://gist.github.com/goldsborough/d466f43e8ffc948ff92de7486c5216d6
for instructions on how to install GCC 5 or higher.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                              !! WARNING !!
aÒ  

                               !! WARNING !!

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Your compiler ({user_compiler}) is not compatible with the compiler Pytorch was
built with for this platform, which is {pytorch_compiler} on {platform}. Please
use {pytorch_compiler} to to compile your extension. Alternatively, you may
compile PyTorch from source using {user_compiler}, and then you can also use
{user_compiler} to compile your extension.

See https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md for help
with compiling PyTorch from source.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

                              !! WARNING !!
ZmiopenTFc                 c   s   | ]}t |ƒV  qd S ©N)Úint)r   Úvr   r   r   Ú	<genexpr>“   r   rG   Ú.é   Ú
CUDNN_HOMEZ
CUDNN_PATHz\d+\.\d+\.\d+\w+\+\w+)	z/MDz/wd4819z/wd4251z/wd4244z/wd4267z/wd4275z/wd4018z/wd4190z/EHsc)Z&base_class_has_different_dll_interfaceZfield_without_dll_interfaceZ#dll_interface_conflict_none_assumedZ(dll_interface_conflict_dllexport_assumed)z-D__CUDA_NO_HALF_OPERATORS__z-D__CUDA_NO_HALF_CONVERSIONS__z-D__CUDA_NO_HALF2_OPERATORS__z--expt-relaxed-constexpr)ú-fPICz-D__HIP_PLATFORM_HCC__=1z-DCUDA_HAS_FP16=1z-D__HIP_NO_HALF_OPERATORS__=1z-D__HIP_NO_HALF_CONVERSIONS__=1Úx86Z	x86_amd64)r   z	win-amd64c                   C   s   t  tjj¡ S rD   )Ú!BUILT_FROM_SOURCE_VERSION_PATTERNÚmatchr1   r;   Ú__version__r   r   r   r   Ú_is_binary_build¼   s    rP   c                   C   s   t j d¡rddgS g d¢S )NÚdarwinzclang++Zclang)zg++Zgcczgnu-c++zgnu-cc)ÚsysÚplatformÚ
startswithr   r   r   r   Ú _accepted_compilers_for_platformÀ   s    rU   c                   C   s   t j tjjdd�¡S )aÚ  
    Returns the path to the root folder under which extensions will built.

    For each extension module built, there will be one folder underneath the
    folder returned by this function. For example, if ``p`` is the path
    returned by this function and ``ext`` the name of an extension, the build
    folder for the extension will be ``p/ext``.

    This directory is **user-specific** so that multiple users on the same
    machine won't meet permission issues.
    Ztorch_extensions)Úappname)r!   r+   Úrealpathr1   Ú_appdirsÚuser_cache_dirr   r   r   r   Úget_default_build_rootÅ   s    rZ   )Úcompilerr   c                    sà   t rdS tjd| gtjd�}tj | ¡  ¡ ¡‰ t	‡ fdd„t
ƒ D ƒƒrLdS tj| dgtjd� ¡ }tj d¡rÆt dtj¡}t ||¡}t|ƒd	kršd
S tj |d  ¡ ¡‰ t	‡ fdd„t
ƒ D ƒƒS tj d¡rÜ| d¡S d
S )a  
    Verifies that the compiler is the expected one for the current platform.

    Arguments:
        compiler (str): The compiler executable to check.

    Returns:
        True if the compiler is gcc/g++ on Linux or clang/clang++ on macOS,
        and always True for Windows.
    Tr   r   c                 3   s   | ]}|ˆ v V  qd S rD   r   ©r   Úname©Zcompiler_pathr   r   rG   å   r   z1check_compiler_ok_for_platform.<locals>.<genexpr>ú-vÚlinuxz^COLLECT_GCC=(.*)$r   Fr   c                 3   s   | ]}|ˆ v V  qd S rD   r   r\   r^   r   r   rG   ð   r   rQ   zApple clang)r$   r'   r(   ÚSTDOUTr!   r+   rW   r)   ÚstripÚanyrU   rR   rS   rT   ÚreÚcompileÚ	MULTILINEÚfindallr/   )r[   r   Úversion_stringÚpatternÚresultsr   r^   r   Úcheck_compiler_ok_for_platformÔ   s"    
rk   c              	   C   sB  t ƒ s
dS tj d¡dv rdS t| ƒsHt tj| t	ƒ d t
jd�¡ dS t
j d¡rXdS ztt
j d¡rŽt}t | d	d
g¡}| ¡  ¡  d¡}n<t}tj| tjd�}t d| ¡  ¡ ¡}|du rÂdn| ¡ }W n6 t�y   t
 ¡ \}}}t d | |¡¡ Y dS 0 ttt|ƒƒ|k�rdS d | d |¡¡} t t | ¡¡ dS )aE  
    Verifies that the given compiler is ABI-compatible with PyTorch.

    Arguments:
        compiler (str): The compiler executable name to check (e.g. ``g++``).
            Must be executable in a shell process.

    Returns:
        False if the compiler is (likely) ABI-incompatible with PyTorch,
        else True.
    TZTORCH_DONT_CHECK_COMPILER_ABI)ÚONÚ1ZYESÚTRUEÚYr   )Zuser_compilerZpytorch_compilerrS   FrQ   r`   z-dumpfullversionz-dumpversionrH   r   z(\d+)\.(\d+)\.(\d+)N)r   r   r   z*Error checking compiler version for {}: {}z{} {})rP   r!   r"   r#   rk   ÚwarningsÚwarnÚWRONG_COMPILER_WARNINGr4   rU   rR   rS   rT   ÚMINIMUM_GCC_VERSIONr'   r(   r)   rb   ÚsplitÚMINIMUM_MSVC_VERSIONra   rd   ÚsearchÚgroupsr-   Úexc_infoÚtupleÚmaprE   r>   ÚABI_INCOMPATIBILITY_WARNING)r[   Zminimum_required_versionZ
versionstrr;   Zcompiler_inforN   Ú_Úerrorr   r   r   Ú check_compiler_abi_compatibility÷   s>    ýr~   c                       s~   e Zd ZdZedd„ ƒZddœ‡ fdd„Zddœ‡ fdd	„Zddœd
d„Z‡ fdd„Z	dd„ Z
dd„ Zdd„ Zdd„ Z‡  ZS )ÚBuildExtensiona»  
    A custom :mod:`setuptools` build extension .

    This :class:`setuptools.build_ext` subclass takes care of passing the
    minimum required compiler flags (e.g. ``-std=c++14``) as well as mixed
    C++/CUDA compilation (and support for CUDA files in general).

    When using :class:`BuildExtension`, it is allowed to supply a dictionary
    for ``extra_compile_args`` (rather than the usual list) that maps from
    languages (``cxx`` or ``nvcc``) to a list of additional compiler flags to
    supply to the compiler. This makes it possible to supply different flags to
    the C++ and CUDA compiler during mixed compilation.

    ``use_ninja`` (bool): If ``use_ninja`` is ``True`` (default), then we
    attempt to build using the Ninja backend. Ninja greatly speeds up
    compilation compared to the standard ``setuptools.build_ext``.
    Fallbacks to the standard distutils backend if Ninja is not available.

    .. note::
        By default, the Ninja backend uses #CPUS + 2 workers to build the
        extension. This may use up too many resources on some systems. One
        can control the number of workers by setting the `MAX_JOBS` environment
        variable to a non-negative number.
    c                    s   G ‡ fdd„d| ƒ}|S )z©
        Returns a subclass with alternative constructor that extends any original keyword
        arguments to the original constructor with the given options.
        c                       s   e Zd Z‡ ‡fdd„Z‡  ZS )z5BuildExtension.with_options.<locals>.cls_with_optionsc                    s    |  ˆ¡ tƒ j|i |¤Ž d S rD   )ÚupdateÚsuperÚ__init__)Úselfr   Úkwargs)Ú	__class__Úoptionsr   r   r‚   P  s    
z>BuildExtension.with_options.<locals>.cls_with_options.__init__)Ú__name__Ú
__module__Ú__qualname__r‚   Ú__classcell__r   ©r†   ©r…   r   Úcls_with_optionsO  s   r�   r   )Úclsr†   r�   r   r‹   r   Úwith_optionsI  s    zBuildExtension.with_optionsNr   c                    s\   t t| ƒj|i |¤Ž | dd¡| _| dd¡| _| jrXd}tƒ sXt | 	d¡¡ d| _d S )NÚno_python_abi_suffixFÚ	use_ninjaTznAttempted to use ninja as the BuildExtension backend but {}. Falling back to using the slow distutils backend.zwe could not find ninja.)
r�   r   r‚   r#   r�   r‘   Úis_ninja_availablerp   rq   r4   )rƒ   r   r„   ÚmsgrŒ   r   r   r‚   V  s    zBuildExtension.__init__c                    s   t ƒ  ¡  | jrd| _d S )NT)r�   Úfinalize_optionsr‘   Úforce©rƒ   rŒ   r   r   r”   c  s    
zBuildExtension.finalize_optionsc              
      s”  ˆ  ¡  ˆjD ]f}ˆ |d¡ dD ]<}ttjd|› �ƒ}|d ur"ts"ˆ |d|› d|› d�¡ q"ˆ |¡ ˆ |¡ qˆj	 j
g d¢7  _
ˆj	jdkr¼ˆj	 jd	d
g7  _ˆj	j‰ˆj	j‰nˆj	j‰d dœ‡fdd„‰ dd„ ‰dd„ ‰d dœ‡ ‡‡‡fdd„}d‡ ‡‡‡fdd„	}dd„ ‰d‡‡‡‡fdd„	}d‡ ‡‡‡fdd„	}ˆj	jdk�rlˆj�rb|ˆj	_n|ˆj	_nˆj�r~|ˆj	_n|ˆj	_t ˆ¡ d S ) Nú-DTORCH_API_INCLUDE_EXTENSION_H©ZCOMPILER_TYPEZSTDLIBZ	BUILD_ABIÚ
_PYBIND11_ú-DPYBIND11_z="r   )ú.cuú.cuhú.hipÚmsvcr›   rœ   r   c                    sJ   ˆj jdkrdnd}| d¡‰ ˆ d }t‡ fdd„| D ƒƒsF|  |¡ d S )Nrž   z/{}:z-{}=Zstdzc++14c                 3   s   | ]}|  ˆ ¡V  qd S rD   ©rT   ©r   Úflag©Zcpp_flag_prefixr   r   rG   „  r   zZBuildExtension.build_extensions.<locals>.append_std14_if_no_std_present.<locals>.<genexpr>)r[   Úcompiler_typer4   rc   Úappend)ÚcflagsZcpp_format_prefixZcpp_flagr–   r¢   r   Úappend_std14_if_no_std_present~  s
    
zGBuildExtension.build_extensions.<locals>.append_std14_if_no_std_presentc                 S   s6   t  d¡}tddg |  t| ƒ |d ur0d|gng  S )NÚCCú--compiler-optionsú'-fPIC'ú-ccbin)r!   ÚgetenvÚCOMMON_NVCC_FLAGSÚ_get_cuda_arch_flags)r¥   Z_ccbinr   r   r   Úunix_cuda_flags‡  s    
ÿþþýz8BuildExtension.build_extensions.<locals>.unix_cuda_flagsc                 S   sB   | d ur>t t| ƒƒD ](}tj | | ¡stj | | ¡| |< qd S rD   )Úranger/   r!   r+   ÚisabsÚabspath)r@   Úir   r   r   Ú!convert_to_absolute_paths_inplaceŽ  s    zJBuildExtension.build_extensions.<locals>.convert_to_absolute_paths_inplacec           	   
      sÐ   t  |¡}z°ˆjj}t|ƒrrtr*tddƒntddƒg}ˆj d|¡ t	|t
ƒrV|d }trh|t|ƒ }q„ˆ|ƒ}nt	|t
ƒr„|d }tr�|t }ˆ |ƒ ˆ| |||||ƒ W ˆj d|¡ nˆj d|¡ 0 d S )NÚbinr7   r   Úcompiler_soÚcxx)ÚcopyÚdeepcopyr[   rµ   Ú_is_cuda_fileÚIS_HIP_EXTENSIONrA   Ú_join_cuda_homeZset_executableÚ
isinstanceÚdictÚ_get_rocm_arch_flagsÚCOMMON_HIPCC_FLAGS)	ÚobjÚsrcÚextZcc_argsÚextra_postargsÚpp_optsr¥   Zoriginal_compilerr   )r¦   Úoriginal_compilerƒ   r®   r   r   Úunix_wrap_single_compile•  s$    



zABuildExtension.build_extensions.<locals>.unix_wrap_single_compiler   c                    s@  t j |¡}ˆˆjjƒ ˆj |||| ||¡\}}	}}
}ˆj |
||¡}ˆjjdd… }tt	t
| ƒƒ}t|tƒrz|d }nt|ƒ}trŽ|t7 }ˆ |ƒ d}d}|�r
|}t|tƒr¼|d }nt|ƒ}trÞ|t|ƒ }|t }nˆ|ƒ}ˆ |ƒ dd„ |D ƒ}dd„ |D ƒ}t| |	dd„ || D ƒd	d„ |D ƒ|||d
|d�	 |	S )z;Compiles sources by outputting a ninja file and running it.r   Nr¶   r   c                 S   s   g | ]}t  |¡‘qS r   ©ÚshlexÚquote©r   Úfr   r   r   r   è  r   zTBuildExtension.build_extensions.<locals>.unix_wrap_ninja_compile.<locals>.<listcomp>c                 S   s   g | ]}t  |¡‘qS r   rÇ   rÊ   r   r   r   r   é  r   c                 S   s   g | ]}t  |¡‘qS r   rÇ   rÊ   r   r   r   r   î  r   c                 S   s   g | ]}t  |¡‘qS r   rÇ   rÊ   r   r   r   r   ï  r   T©	ÚsourcesÚobjectsr¥   Úpost_cflagsÚcuda_cflagsÚcuda_post_cflagsÚbuild_directoryÚverboseÚ	with_cuda)r!   r+   r±   r[   Úinclude_dirsÚ_setup_compileZ_get_cc_argsrµ   rc   rz   r¹   r¼   r½   Úlistrº   r¿   r¾   Ú%_write_ninja_file_and_compile_objects)rÍ   Ú
output_dirÚmacrosrÕ   ÚdebugÚextra_preargsrÃ   Údependsr|   rÎ   rÄ   Úcommon_cflagsZextra_cc_cflagsrÔ   rÏ   rÑ   rÐ   )r¦   r³   rƒ   r®   r   r   Úunix_wrap_ninja_compile®  sT    
þÿ




÷z@BuildExtension.build_extensions.<locals>.unix_wrap_ninja_compilec                 S   s   t |  t| ƒ S rD   )r¬   r­   )r¥   r   r   r   Úwin_cuda_flagsù  s
    ÿÿz7BuildExtension.build_extensions.<locals>.win_cuda_flagsc           	   	      sX   t  |¡ˆ_d }‡‡‡fdd„}z(|ˆj_ˆ | |||||||ƒW ˆˆj_S ˆˆj_0 d S )Nc           
         sˆ  t  d¡‰dd„ ‡fdd„| D ƒD ƒ}t  d¡‰dd„ ‡fdd„| D ƒD ƒ}t  d	¡‰ d
d„ ‡ fdd„| D ƒD ƒ}t|ƒdk�r€t|ƒdk�r€|d }|d }t|ƒ�r:tddƒ}tˆjtƒrÊˆjd }ntˆjtƒrÞˆj}ng }ˆ|ƒdg }t	D ]}d|g| }qôt
D ]}	dd|	 g| }�q
|d|d|g| | } nFtˆjtƒ�r`t	ˆjd  }| |7 } n tˆjtƒ�r€t	ˆj }| |7 } ˆ| ƒS )Nz/T(p|c)(.*)c                 S   s   g | ]}|r|  d ¡‘qS )rI   ©Úgroup©r   Úmr   r   r   r     s   ÿzcBuildExtension.build_extensions.<locals>.win_wrap_single_compile.<locals>.spawn.<locals>.<listcomp>c                 3   s   | ]}ˆ   |¡V  qd S rD   ©rN   ©r   Úelem)Ú	src_regexr   r   rG     r   zbBuildExtension.build_extensions.<locals>.win_wrap_single_compile.<locals>.spawn.<locals>.<genexpr>z/Fo(.*)c                 S   s   g | ]}|r|  d ¡‘qS ©r   rá   rã   r   r   r   r     s   ÿc                 3   s   | ]}ˆ   |¡V  qd S rD   rå   ræ   )Ú	obj_regexr   r   rG     r   z((\-|\/)I.*)c                 S   s   g | ]}|r|  d ¡‘qS ré   rá   rã   r   r   r   r     s   ÿc                 3   s   | ]}ˆ   |¡V  qd S rD   rå   ræ   )Úinclude_regexr   r   rG     r   r   r   r´   r   ú--use-local-envú
-Xcompilerú-Xcudafeú--diag_suppress=z-cz-or¶   )rd   re   r/   r¹   r»   r¼   r¥   r½   r×   ÚCOMMON_MSVC_FLAGSÚMSVC_IGNORE_CUDAFE_WARNINGS)
ÚcmdZsrc_listZobj_listÚinclude_listrÁ   rÀ   r   r¥   r¡   Úignore_warning)Úoriginal_spawnrƒ   rà   )rë   rê   rè   r   Úspawn	  sF    
ÿ
ÿ
þ



zOBuildExtension.build_extensions.<locals>.win_wrap_single_compile.<locals>.spawn)r·   r¸   r¥   r[   rö   )	rÍ   rÙ   rÚ   rÕ   rÛ   rÜ   rÃ   rÝ   rö   )rÅ   rõ   rƒ   rà   r   r   Úwin_wrap_single_compileý  s    	/þüz@BuildExtension.build_extensions.<locals>.win_wrap_single_compilec                    sˆ  ˆj jsˆj  ¡  tj |¡}ˆˆj jƒ ˆj  |||| ||¡\}}	}}
}|pPg }g }|rj| ˆj j	¡ n| ˆj j
¡ | t¡ || |
 }ttt| ƒƒ}t|tƒr°|d }nt|ƒ}ˆ |ƒ d }d }|�rDdg}|D ]}| d¡ | |¡ qØtD ]}| d¡ | d| ¡ qö| |
¡ t|tƒ�r4|d }nt|ƒ}ˆ|ƒ}t|ƒ}t|ƒ}|�rjt|ƒ}t|ƒ}t| |	|||||d|d�	 |	S )	Nr¶   rì   rí   rî   rï   r   TrÌ   )r[   ZinitializedZ
initializer!   r+   r±   rÕ   rÖ   ÚextendZcompile_options_debugZcompile_optionsrð   rc   rz   r¹   r¼   r½   r×   r¤   rñ   r   rØ   )rÍ   rÙ   rÚ   rÕ   rÛ   rÜ   rÃ   rÝ   r|   rÎ   rÄ   rÞ   r¥   rÔ   rÏ   rÑ   rÐ   Zcommon_cflagrô   )r¦   r³   rƒ   rà   r   r   Úwin_wrap_ninja_compile@  sj    	

þÿ






÷z?BuildExtension.build_extensions.<locals>.win_wrap_ninja_compile)NNNr   NNN)NNNr   NNN)NNNr   NNN)Ú
_check_abiÚ
extensionsÚ_add_compile_flagÚgetattrr1   Ú_Cr$   Ú_define_torch_extension_nameÚ_add_gnu_cpp_abi_flagr[   Zsrc_extensionsr£   Z_cpp_extensionsre   rö   Ú_compiler‘   r
   Úbuild_extensions)rƒ   Ú	extensionr]   ÚvalrÆ   rß   r÷   rù   r   )r¦   r³   rÅ   rõ   rƒ   r®   rà   r   r  h  sh    


	       ùK       ùD       ùS


zBuildExtension.build_extensionsc                    sF   t t| ƒ |¡}| jrB| d¡}|d d… |dd …  }d |¡}|S )NrH   éþÿÿÿéÿÿÿÿ)r�   r   Úget_ext_filenamer�   rt   r>   )rƒ   Zext_nameZext_filenameZext_filename_partsZwithout_abirŒ   r   r   r     s    

zBuildExtension.get_ext_filenamec                 C   sl   t | jdƒr| jjd }n"tr.tj dd¡}ntj dd¡}t|ƒ trhdtjv rhdtjvrhd}t|ƒ‚d S )	NÚcompiler_cxxr   ÚCXXÚclúc++ÚVSCMD_ARG_TGT_ARCHZDISTUTILS_USE_SDKz²It seems that the VC environment is activated but DISTUTILS_USE_SDK is not set.This may lead to multiple activations of the VC env.Please set `DISTUTILS_USE_SDK=1` and try again.)	Úhasattrr[   r  r$   r!   r"   r#   r~   ÚUserWarning)rƒ   r[   r“   r   r   r   rú   °  s    zBuildExtension._check_abic                 C   sF   t  |j¡|_t|jtƒr6|j ¡ D ]}| |¡ q$n|j |¡ d S rD   )r·   r¸   Úextra_compile_argsr¼   r½   Úvaluesr¤   )rƒ   r  r¡   r   r   r   r   rü   À  s
    z BuildExtension._add_compile_flagc                 C   s.   |j  d¡}|d }d |¡}|  ||¡ d S )NrH   r  ú-DTORCH_EXTENSION_NAME={})r]   rt   r4   rü   )rƒ   r  Únamesr]   Zdefiner   r   r   rÿ   È  s    
z+BuildExtension._define_torch_extension_namec                 C   s    |   |dtttjjƒƒ ¡ d S )Nú-D_GLIBCXX_USE_CXX11_ABI=)rü   ÚstrrE   r1   rþ   Ú_GLIBCXX_USE_CXX11_ABI)rƒ   r  r   r   r   r   Ò  s    z$BuildExtension._add_gnu_cpp_abi_flag)r‡   rˆ   r‰   Ú__doc__Úclassmethodr�   r‚   r”   r  r  rú   rü   rÿ   r   rŠ   r   r   rŒ   r   r   /  s   
  :
r   c                 O   sš   |  dg ¡}|tƒ 7 }||d< |  dg ¡}|tƒ 7 }||d< |  dg ¡}| d¡ | d¡ | d¡ | d¡ ||d< d|d	< tj| |g|¢R i |¤ŽS )
a(  
    Creates a :class:`setuptools.Extension` for C++.

    Convenience method that creates a :class:`setuptools.Extension` with the
    bare minimum (but often sufficient) arguments to build a C++ extension.

    All arguments are forwarded to the :class:`setuptools.Extension`
    constructor.

    Example:
        >>> from setuptools import setup
        >>> from torch.utils.cpp_extension import BuildExtension, CppExtension
        >>> setup(
                name='extension',
                ext_modules=[
                    CppExtension(
                        name='extension',
                        sources=['extension.cpp'],
                        extra_compile_args=['-g']),
                ],
                cmdclass={
                    'build_ext': BuildExtension
                })
    rÕ   Úlibrary_dirsÚ	librariesÚc10r1   Ú	torch_cpuÚtorch_pythonr  Úlanguage)r#   Úinclude_pathsÚlibrary_pathsr¤   Ú
setuptoolsÚ	Extension)r]   rÍ   r   r„   rÕ   r  r  r   r   r   ÚCppExtension×  s    





r"  c                 O   sü   |  dg ¡}|tdd�7 }||d< |  dg ¡}| d¡ | d¡ | d¡ | d¡ tr’td	usfJ ‚| td
krvdnd¡ | d¡ | d¡ n| d¡ | d¡ | d¡ ||d< |  dg ¡}|tdd�7 }||d< d|d< tj| |g|¢R i |¤ŽS )aù  
    Creates a :class:`setuptools.Extension` for CUDA/C++.

    Convenience method that creates a :class:`setuptools.Extension` with the
    bare minimum (but often sufficient) arguments to build a CUDA/C++
    extension. This includes the CUDA include path, library path and runtime
    library.

    All arguments are forwarded to the :class:`setuptools.Extension`
    constructor.

    Example:
        >>> from setuptools import setup
        >>> from torch.utils.cpp_extension import BuildExtension, CUDAExtension
        >>> setup(
                name='cuda_extension',
                ext_modules=[
                    CUDAExtension(
                            name='cuda_extension',
                            sources=['extension.cpp', 'extension_kernel.cu'],
                            extra_compile_args={'cxx': ['-g'],
                                                'nvcc': ['-O2']})
                ],
                cmdclass={
                    'build_ext': BuildExtension
                })
    r  T)r2   r  r  r1   r  r  N©é   rB   Zamdhip64Zhip_hccZc10_hipZ	torch_hipZcudartZc10_cudaZ
torch_cudarÕ   r  r  )r#   r  r¤   rº   ÚROCM_VERSIONr  r   r!  )r]   rÍ   r   r„   r  r  rÕ   r   r   r   ÚCUDAExtension  s,    







r&  )r2   r   c                 C   sä   t j t¡}t j t j |¡¡}t j |d¡}|t j |dddd¡t j |d¡t j |d¡g}| r¦tr¦| t j |d¡¡ | tdƒ¡ t	durà| t j t	d¡¡ n:| ràt
dƒ}|d	krÄ| |¡ tdurà| t j td¡¡ |S )
zÊ
    Get the include paths required to build a C++ or CUDA extension.

    Args:
        cuda: If `True`, includes CUDA-specific include paths.

    Returns:
        A list of include path strings.
    Úincluder1   ZcsrcÚapiZTHZTHCZTHHNz/usr/include)r!   r+   r±   Ú__file__r,   r>   rº   r¤   rA   ÚMIOPEN_HOMEr»   rJ   )r2   ÚhereÚ
torch_pathZlib_includer@   Zcuda_home_includer   r   r   r  <  s(    
ù	
r  c                 C   s¼   g }t j t¡}t j t j |¡¡}t j |d¡}| |¡ | rXtrXd}| t|ƒ¡ n`| r¸t	rfd}n(d}t j 
t|ƒ¡sŽt j 
tdƒ¡rŽd}| t|ƒ¡ tdur¸| t j t|¡¡ |S )zÊ
    Get the library paths required to build a C++ or CUDA extension.

    Args:
        cuda: If `True`, includes CUDA-specific library paths.

    Returns:
        A list of library path strings.
    Úlibúlib/x64Úlib64N)r!   r+   r±   r)  r,   r>   r¤   rº   rA   r$   r0   r»   rJ   )r2   r@   r+  r,  Úlib_pathÚlib_dirr   r   r   r  b  s(    

ÿr  )rÍ   rÔ   c                 C   s8   t | t|tƒr|gn||||||p*t| |ƒ|||	|
d�S )að  
    Loads a PyTorch C++ extension just-in-time (JIT).

    To load an extension, a Ninja build file is emitted, which is used to
    compile the given sources into a dynamic library. This library is
    subsequently loaded into the current Python process as a module and
    returned from this function, ready for use.

    By default, the directory to which the build file is emitted and the
    resulting library compiled to is ``<tmp>/torch_extensions/<name>``, where
    ``<tmp>`` is the temporary folder on the current platform and ``<name>``
    the name of the extension. This location can be overridden in two ways.
    First, if the ``TORCH_EXTENSIONS_DIR`` environment variable is set, it
    replaces ``<tmp>/torch_extensions`` and all extensions will be compiled
    into subfolders of this directory. Second, if the ``build_directory``
    argument to this function is supplied, it overrides the entire path, i.e.
    the library will be compiled into that folder directly.

    To compile the sources, the default system compiler (``c++``) is used,
    which can be overridden by setting the ``CXX`` environment variable. To pass
    additional arguments to the compilation process, ``extra_cflags`` or
    ``extra_ldflags`` can be provided. For example, to compile your extension
    with optimizations, pass ``extra_cflags=['-O3']``. You can also use
    ``extra_cflags`` to pass further include directories.

    CUDA support with mixed compilation is provided. Simply pass CUDA source
    files (``.cu`` or ``.cuh``) along with other sources. Such files will be
    detected and compiled with nvcc rather than the C++ compiler. This includes
    passing the CUDA lib64 directory as a library directory, and linking
    ``cudart``. You can pass additional flags to nvcc via
    ``extra_cuda_cflags``, just like with ``extra_cflags`` for C++. Various
    heuristics for finding the CUDA install directory are used, which usually
    work fine. If not, setting the ``CUDA_HOME`` environment variable is the
    safest option.

    Args:
        name: The name of the extension to build. This MUST be the same as the
            name of the pybind11 module!
        sources: A list of relative or absolute paths to C++ source files.
        extra_cflags: optional list of compiler flags to forward to the build.
        extra_cuda_cflags: optional list of compiler flags to forward to nvcc
            when building CUDA sources.
        extra_ldflags: optional list of linker flags to forward to the build.
        extra_include_paths: optional list of include directories to forward
            to the build.
        build_directory: optional path to use as build workspace.
        verbose: If ``True``, turns on verbose logging of load steps.
        with_cuda: Determines whether CUDA headers and libraries are added to
            the build. If set to ``None`` (default), this value is
            automatically determined based on the existence of ``.cu`` or
            ``.cuh`` in ``sources``. Set it to `True`` to force CUDA headers
            and libraries to be included.
        is_python_module: If ``True`` (default), imports the produced shared
            library as a Python module. If ``False``, loads it into the process
            as a plain dynamic library.

    Returns:
        If ``is_python_module`` is ``True``, returns the loaded PyTorch
        extension as a Python module. If ``is_python_module`` is ``False``
        returns nothing (the shared library is loaded into the process as a side
        effect).

    Example:
        >>> from torch.utils.cpp_extension import load
        >>> module = load(
                name='extension',
                sources=['extension.cpp', 'extension_kernel.cu'],
                extra_cflags=['-O2'],
                verbose=True)
    ©Úkeep_intermediates)Ú_jit_compiler¼   r  Ú_get_build_directory)r]   rÍ   Úextra_cflagsÚextra_cuda_cflagsÚextra_ldflagsÚextra_include_pathsrÒ   rÓ   rÔ   Úis_python_moduler3  r   r   r   Úload‰  s    Qõr;  c                 C   sÜ  |pt | |	ƒ}t|tƒr|g}|p$g }t|tƒr6|g}| dd¡ |durðg }| d¡ t|tƒrh|g}t|tƒr†tdd„ |D ƒƒ}nt|tƒs¢td t	|ƒ¡ƒ‚| 
¡ D ]2\}}|rÊ| d ||¡¡ qª| d	 ||¡¡ qª| d
¡ ||7 }tj |d¡}t|dƒ� }| d |¡¡ W d  ƒ n1 �s00    Y  |g}|�r¾| dd¡ | dd¡ | dd¡ tj |d¡}t|dƒ� }| d |¡¡ W d  ƒ n1 �sª0    Y  | |¡ t| |||||||	|
||d�S )a  
    Loads a PyTorch C++ extension just-in-time (JIT) from string sources.

    This function behaves exactly like :func:`load`, but takes its sources as
    strings rather than filenames. These strings are stored to files in the
    build directory, after which the behavior of :func:`load_inline` is
    identical to :func:`load`.

    See `the
    tests <https://github.com/pytorch/pytorch/blob/master/test/test_cpp_extensions.py>`_
    for good examples of using this function.

    Sources may omit two required parts of a typical non-inline C++ extension:
    the necessary header includes, as well as the (pybind11) binding code. More
    precisely, strings passed to ``cpp_sources`` are first concatenated into a
    single ``.cpp`` file. This file is then prepended with ``#include
    <torch/extension.h>``.

    Furthermore, if the ``functions`` argument is supplied, bindings will be
    automatically generated for each function specified. ``functions`` can
    either be a list of function names, or a dictionary mapping from function
    names to docstrings. If a list is given, the name of each function is used
    as its docstring.

    The sources in ``cuda_sources`` are concatenated into a separate ``.cu``
    file and  prepended with ``torch/types.h``, ``cuda.h`` and
    ``cuda_runtime.h`` includes. The ``.cpp`` and ``.cu`` files are compiled
    separately, but ultimately linked into a single library. Note that no
    bindings are generated for functions in ``cuda_sources`` per  se. To bind
    to a CUDA kernel, you must create a C++ function that calls it, and either
    declare or define this C++ function in one of the ``cpp_sources`` (and
    include its name in ``functions``).

    See :func:`load` for a description of arguments omitted below.

    Args:
        cpp_sources: A string, or list of strings, containing C++ source code.
        cuda_sources: A string, or list of strings, containing CUDA source code.
        functions: A list of function names for which to generate function
            bindings. If a dictionary is given, it should map function names to
            docstrings (which are otherwise just the function names).
        with_cuda: Determines whether CUDA headers and libraries are added to
            the build. If set to ``None`` (default), this value is
            automatically determined based on whether ``cuda_sources`` is
            provided. Set it to ``True`` to force CUDA headers
            and libraries to be included.
        with_pytorch_error_handling: Determines whether pytorch error and
            warning macros are handled by pytorch instead of pybind. To do
            this, each function ``foo`` is called via an intermediary ``_safe_foo``
            function. This redirection might cause issues in obscure cases
            of cpp. This flag should be set to ``False`` when this redirect
            causes issues.

    Example:
        >>> from torch.utils.cpp_extension import load_inline
        >>> source = \'\'\'
        at::Tensor sin_add(at::Tensor x, at::Tensor y) {
          return x.sin() + y.sin();
        }
        \'\'\'
        >>> module = load_inline(name='inline_extension',
                                 cpp_sources=[source],
                                 functions=['sin_add'])

    .. note::
        By default, the Ninja backend uses #CPUS + 2 workers to build the
        extension. This may use up too many resources on some systems. One
        can control the number of workers by setting the `MAX_JOBS` environment
        variable to a non-negative number.
    r   z#include <torch/extension.h>Nz*PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {c                 s   s   | ]}||fV  qd S rD   r   rÊ   r   r   r   rG   P  r   zload_inline.<locals>.<genexpr>z5Expected 'functions' to be a list or dict, but was {}z6m.def("{0}", torch::wrap_pybind_function({0}), "{1}");zm.def("{0}", {0}, "{1}");Ú}zmain.cppr   Ú
z#include <torch/types.h>r   z#include <cuda.h>rI   z#include <cuda_runtime.h>zcuda.cur2  )r5  r¼   r  Úinsertr¤   r×   r½   Ú
ValueErrorr4   ÚtypeÚitemsr!   r+   r>   r%   Úwriter4  )r]   Zcpp_sourcesZcuda_sourcesZ	functionsr6  r7  r8  r9  rÒ   rÓ   rÔ   r:  Zwith_pytorch_error_handlingr3  Z
module_defZfunction_nameÚ	docstringZcpp_source_pathZcpp_source_filerÍ   Zcuda_source_pathZcuda_source_filer   r   r   Úload_inlineè  sn    T





ÿÿÿÿ
00
õrD  )rÒ   rÓ   rÔ   r   c                 C   s¢  |d u rt tt|ƒƒ}t dd„ |p$g D ƒƒ}t | ¡}tj| |||||g||d�}|dkrŒ||kr€|r€td | ¡d || ¡ ƒ d | |¡} ||k�rltt	j
 |d¡ƒ}| ¡ �rbz¢t|
d	��z}trø|sÌ|røtj||t	j
 |d
¡dd„ |D ƒ|d|d� t| ||�pg |�pg |�pg |�pg |||d�	 W d   ƒ n1 �s@0    Y  W | ¡  n
| ¡  0 n| ¡  n|�r€td | ¡ƒ |�r–td| › d�ƒ t| ||	ƒS )Nc                 S   s   g | ]}d |v ‘qS )Zcudnnr   rÊ   r   r   r   r   ‹  r   z _jit_compile.<locals>.<listcomp>)Zbuild_argumentsrÒ   rÔ   r   z;The input conditions for extension module {} have changed. z5Bumping to version {0} and re-building as {1}_v{0}...z{}_v{}Úlockr2  Ú*c                 S   s   g | ]}t j |¡‘qS r   ©r!   r+   r±   ©r   Úsr   r   r   r   ¤  r   T)Zproject_directoryZoutput_directoryZincludesZextra_filesZshow_detailedZis_pytorch_extensionÚ	clean_ctx)	r]   rÍ   r6  r7  r8  r9  rÒ   rÓ   rÔ   zSNo modifications detected for re-loaded extension module {}, skipping build step...zLoading extension module ú...)rc   rz   r¹   ÚJIT_EXTENSION_VERSIONERÚget_versionZbump_version_if_changedr3   r4   r   r!   r+   r>   Ztry_acquirer   rº   r   ÚhipifyÚ#_write_ninja_file_and_build_libraryÚreleaseÚwaitÚ_import_module_from_library)r]   rÍ   r6  r7  r8  r9  rÒ   rÓ   rÔ   r:  r3  Z
with_cudnnZold_versionr;   ZbatonrJ  r   r   r   r4  ~  sh    

û

ÿ

ù	÷(
ÿr4  )rÍ   rÒ   rÓ   rÔ   r   c	                 C   s¢   t ƒ  trtj dd¡}	ntj dd¡}	t|	ƒ |d u rFttt| ƒƒ}tj	 
|d¡}
|rhtd|
› d�ƒ t|
||||| |d d |d�
 |r�tdƒ t||d	d
� d S )Nr	  r
  r  úbuild.ninjaúEmitting ninja build file rK  ©
r+   r¥   rÏ   rÐ   rÑ   rÍ   rÎ   ÚldflagsÚlibrary_targetrÔ   zCompiling objects...z%Error compiling objects for extension©Úerror_prefix)Úverify_ninja_availabilityr$   r!   r"   r#   r~   rc   rz   r¹   r+   r>   r3   Ú_write_ninja_fileÚ_run_ninja_build)rÍ   rÎ   r¥   rÏ   rÐ   rÑ   rÒ   rÓ   rÔ   r[   Úbuild_file_pathr   r   r   rØ   À  s:    
öûrØ   c	              
   C   sÊ   t ƒ  trtj dd¡}	ntj dd¡}	t|	ƒ |d u rFttt|ƒƒ}t	|pNg ||ƒ}tj
 |d¡}
|rxtd|
› d�ƒ t|
| ||p†g |pŒg |p’g |p˜g |d� |r²td | ¡ƒ t||d	 | ¡d
� d S )Nr	  r
  r  rS  rT  rK  )r+   r]   rÍ   r6  r7  r8  r9  rÔ   zBuilding extension module {}...zError building extension '{}'rX  )rZ  r$   r!   r"   r#   r~   rc   rz   r¹   Ú_prepare_ldflagsr+   r>   r3   Ú"_write_ninja_file_to_build_libraryr4   r\  )r]   rÍ   r6  r7  r8  r9  rÒ   rÓ   rÔ   r[   r]  r   r   r   rO  ê  s@    
ýø
ýrO  c               	   C   sx   t tjdƒ�X} ztjd ¡ | d� W n  tyD   Y W d  ƒ dS 0 W d  ƒ dS W d  ƒ n1 sj0    Y  dS )z‡
    Returns ``True`` if the `ninja <https://ninja-build.org/>`_ build system is
    available on the system, ``False`` otherwise.
    Úwbzninja --version)ÚstdoutNFT)r%   r!   r&   r'   Ú
check_callrt   ÚOSError)r&   r   r   r   r’     s    r’   c                   C   s   t ƒ stdƒ‚dS )z‘
    Raises ``RuntimeError`` if `ninja <https://ninja-build.org/>`_ build system is not
    available on the system, does nothing otherwise.
    z(Ninja is required to load C++ extensionsN)r’   ÚRuntimeErrorr   r   r   r   rZ  %  s    rZ  c                 C   s  t j t¡}t j t j |¡¡}t j |d¡}tr¾t j tj¡}t j |d¡}|  	d¡ |rf|  	d¡ |  	d¡ |rˆ|  	d¡ |  	d¡ |  	d¡ |  	d	¡ |  	d
 
|¡¡ |  	d
 
|¡¡ nh|  	d 
|¡¡ |  	d¡ |rî|  	trèdnd¡ |  	d¡ |�r|  	t�rdnd¡ |  	d¡ |  	d¡ |�r|�r:tdƒ t�r~|  	d
 
tdƒ¡¡ |  	d¡ td u�r|  	t j td¡¡ nŠt�sÈ|  	d 
tdƒ¡¡ |  	d¡ td u�r|  	d 
t j td¡¡¡ n@t�rtd u�sÜJ ‚|  	d 
tdƒ¡¡ |  	tdk�rdnd¡ | S )Nr-  Zlibszc10.libzc10_cuda.libztorch_cpu.libztorch_cuda.libz"-INCLUDE:?warp_size@cuda@at@@YAHXZz	torch.libztorch_python.libz/LIBPATH:{}z-L{}z-lc10z	-lc10_hipz
-lc10_cudaz-ltorch_cpuz-ltorch_hipz-ltorch_cudaz-ltorchz-ltorch_pythonz%Detected CUDA files, patching ldflagsr.  z
cudart.libr/  z-lcudartr#  z
-lamdhip64z	-lhip_hcc)r!   r+   r±   r)  r,   r>   r$   rR   Ú
executabler¤   r4   rº   r3   r»   rJ   r%  rA   )r8  rÔ   rÓ   r+  r,  r0  Zpython_pathZpython_lib_pathr   r   r   r^  .  s\    










ÿ



r^  )r¥   r   c                 C   s"  | dur"| D ]}d|v rg   S qt  g d¢¡}g d¢}|dd„ |D ƒ }tj dd¡}|s~tj ¡ }d |d	 |d
 ¡g}n4| 	dd¡}| 
¡ D ]\}}	| 	||	¡}q’| d¡}g }
|D ]Z}||vrÖtd |¡ƒ‚qº|d	 |d  }|
 d ||¡¡ | d¡rº|
 d ||¡¡ qºtt|
ƒƒS )ad  
    Determine CUDA arch flags to use.

    For an arch, say "6.1", the added compile flag will be
    ``-gencode=arch=compute_61,code=sm_61``.
    For an added "+PTX", an additional
    ``-gencode=arch=compute_xx,code=compute_xx`` is added.

    See select_compute_arch.cmake for corresponding named and supported arches
    when building with CMake.
    NÚarch))zKepler+Teslaú3.7)ZKeplerz3.5+PTX)zMaxwell+Tegraú5.3)ZMaxwellz5.0;5.2+PTX)ZPascalz6.0;6.1+PTX)ZVoltaz7.0+PTX)ZTuringz7.5+PTX)ZAmperez8.0;8.6+PTX)z3.5rg  z5.0z5.2rh  z6.0z6.1z6.2z7.0z7.2z7.5z8.0z8.6c                 S   s   g | ]}|d  ‘qS )ú+PTXr   rH  r   r   r   r   †  r   z(_get_cuda_arch_flags.<locals>.<listcomp>ZTORCH_CUDA_ARCH_LISTú{}.{}r   r   r   ú;z+Unknown CUDA arch ({}) or GPU not supportedrI   z#-gencode=arch=compute_{},code=sm_{}ri  z(-gencode=arch=compute_{},code=compute_{})ÚcollectionsÚOrderedDictr!   r"   r#   r1   r2   Zget_device_capabilityr4   ÚreplacerA  rt   r?  r¤   Úendswithr×   Úset)r¥   r¡   Znamed_archesZsupported_archesZvalid_arch_stringsZ
_arch_listZ
capabilityZ	arch_listZ
named_archZarchvalÚflagsrf  Únumr   r   r   r­   d  s0    



r­   c                 C   s,   | d ur$| D ]}d|v rdg  S qg d¢S )Nzamdgpu-targetú-fno-gpu-rdc)z--amdgpu-target=gfx803z--amdgpu-target=gfx900z--amdgpu-target=gfx906z--amdgpu-target=gfx908rs  r   )r¥   r¡   r   r   r   r¾   ¨  s
    r¾   )r]   rÓ   r   c                 C   sl   t j d¡}|d u rtƒ }|r,td |¡ƒ t j || ¡}t j |¡sh|rZtd|› d�ƒ t j	|dd� |S )NZTORCH_EXTENSIONS_DIRz&Using {} as PyTorch extensions root...zCreating extension directory rK  T)Úexist_ok)
r!   r"   r#   rZ   r3   r4   r+   r>   r0   Úmakedirs)r]   rÓ   Zroot_extensions_directoryrÒ   r   r   r   r5  ¸  s    ÿr5  )rÓ   r   c                 C   sF   t j d¡}|d ur6| ¡ r6| r.td |¡ƒ t|ƒS | rBtdƒ d S )NZMAX_JOBSz6Using envvar MAX_JOBS ({}) as the number of workers...zqAllowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N))r!   r"   r#   Úisdigitr3   r4   rE   )rÓ   Zmax_jobsr   r   r   Ú_get_num_workersË  s    rw  )rÒ   rÓ   rY  r   c              
   C   s~  ddg}t |ƒ}|d ur*| dt|ƒg¡ tj ¡ }tr®d|vr®ddlm} ddl	m
} |ƒ }t| }	||	ƒ}
dd	„ |
 ¡ D ƒ}
| ¡ D ] \}}| ¡ }||
vrˆ||
|< qˆ|
}z^tj ¡  tj ¡  tjd
kröd}tj||rà|ntjtj| d|d� ntj|tj| |d� W nl tj�yx } zPt ¡ \}}}|}t|dƒ�rZ|j�rZ|d |j ¡ ¡7 }t|ƒ|‚W Y d }~n
d }~0 0 d S )NZninjar_   z-jr  r   )Úget_platform)Ú_get_vc_envc                 S   s   i | ]\}}|  ¡ |“qS r   )Úupper)r   ÚkrF   r   r   r   Ú
<dictcomp>æ  r   z$_run_ninja_build.<locals>.<dictcomp>r#  r   T)ra  r   ÚcwdÚcheckÚenv)r   r}  r  Úoutputz: {})rw  rø   r  r!   r"   r·   r$   Údistutils.utilrx  Zdistutils._msvccompilerry  ÚPLAT_TO_VCVARSrA  rz  rR   ra  Úflushr   Úversion_infor'   ÚrunÚPIPEra   r(   ÚCalledProcessErrorrx   r  r€  r4   r)   rd  )rÒ   rÓ   rY  ÚcommandZnum_workersr  rx  ry  Ú	plat_nameZ	plat_specZvc_envr{  rF   ÚukZstdout_filenoÚer|   r}   Úmessager   r   r   r\  ×  sT    




úü
r\  c                 C   sj   t  | |g¡\}}}|�> |r<t  | |||¡W  d   ƒ S tj |¡ W d   ƒ n1 s\0    Y  d S rD   )ÚimpÚfind_moduleÚload_moduler1   ÚopsZload_library)Úmodule_namer+   r:  ÚfileÚdescriptionr   r   r   rR    s
    rR  c                    sÔ  dd„ |D ƒ}dd„ |D ƒ}dd„ |D ƒ}dd„ |D ƒ}dd„ |D ƒ}t ˆƒ}	|	 t ¡ d ¡ trt||	7 }|	 ¡  d |¡g}
|
 d	¡ d
D ]:}ttj	d|› �ƒ}|d urŽtsŽ|
 d|› d|› d�¡ qŽ|
dd„ |D ƒ7 }
|
dd„ |	D ƒ7 }
|
dt
ttj	jƒƒ g7 }
t�r$|
t | }t|ƒ}n|
ddg | }ˆ�rvt�rvdg| t }||7 }|t|ƒ7 }‡ fdd„|D ƒ}n¾ˆ�r0|
t tƒ  }t�rÚtD ]}d|g| }�q”tD ]}dd| g| }�q¬t|ƒ}|t|ƒ7 }nT|ddg7 }||7 }tdd„ |D ƒƒ�s| d¡ t d¡d u�r4dt d¡g| }nd }t
t
dœ‡fd d!„}tt||ƒƒ}t�rhd"g| }n
d#g| }tj d$¡�rŒ| d%¡ nt�ršt|ƒ}t�r¤d&nd'}d( ||¡}tˆ |d |d ||||ˆd)�
 d S )*Nc                 S   s   g | ]}|  ¡ ‘qS r   ©rb   r    r   r   r   r   )  r   z6_write_ninja_file_to_build_library.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r   r”  r    r   r   r   r   *  r   c                 S   s   g | ]}|  ¡ ‘qS r   r”  r    r   r   r   r   +  r   c                 S   s   g | ]}|  ¡ ‘qS r   r”  r    r   r   r   r   ,  r   c                 S   s   g | ]}t j |¡‘qS r   rG  ©r   r’  r   r   r   r   0  r   r'  r  r—   r˜   r™   rš   z=\"z\"c                 S   s   g | ]}d |› �‘qS )z-Ir   ©r   r'  r   r   r   r   P  r   c                 S   s   g | ]}d |› �‘qS )z	-isystem r   r–  r   r   r   r   Q  r   r  rK   z
-std=c++14z
-DWITH_HIPc                    s<   g | ]4}t |ƒs|n"tj tj ˆ ttj |ˆ ¡ƒ¡¡‘qS r   )r¹   r!   r+   r±   r>   r   ÚrelpathrH  )r+   r   r   r   ^  s
   ýÿrí   rî   rï   r¨   r©   c                 s   s   | ]}|  d ¡V  qdS )z-std=NrŸ   r    r   r   r   rG   n  r   z5_write_ninja_file_to_build_library.<locals>.<genexpr>r§   rª   )Úsource_filer   c                    s>   t j t j | ¡¡d }t| ƒr0ˆ r0d |¡}n
d |¡}|S )Nr   z	{}.cuda.oz{}.o)r!   r+   Úsplitextr:   r¹   r4   )r˜  Ú	file_nameÚtarget)rÔ   r   r   Úobject_file_pathu  s
    
z<_write_ninja_file_to_build_library.<locals>.object_file_pathz/DLLz-sharedrQ   z-undefined dynamic_lookupZpydÚsorj  rU  )r  r¤   Ú	sysconfigÚ	get_pathsr$   Úclearr4   rý   r1   rþ   r  rE   r  rð   r   rº   r¿   r¾   r¬   r­   rñ   rc   r!   r«   r×   rz   rR   rS   rT   r[  )r+   r]   rÍ   r6  r7  r8  r9  rÔ   Zuser_includesZsystem_includesrÞ   ZpnameZpvalr¥   Z
cuda_flagsr¡   rô   rœ  rÎ   rV  rÂ   rW  r   )r+   rÔ   r   r_  !  sŠ    


ý

ör_  c
                 C   s:  dd„ }
|
|ƒ}|
|ƒ}|
|ƒ}|
|ƒ}|
|ƒ}t |ƒt |ƒksDJ ‚t |ƒdksTJ ‚trhtj dd¡}ntj dd¡}dg}| d |¡¡ |	rºtr td	d
ƒ}n
t	d	dƒ}| d |¡¡ d d 
|¡¡g}| d d 
|¡¡¡ |	�r| d d 
|¡¡¡ | d d 
|¡¡¡ | d d 
|¡¡¡ dd„ |D ƒ}dg}t�rZ| d¡ | d¡ n| d¡ | d¡ | d¡ |	�rŽdg}| d¡ g }t||ƒD ]p\}}t|ƒ�o°|	}|�r¼dnd}t�rÞ| dd ¡}| dd ¡}| dd!¡}| dd!¡}| d" |||¡¡ �qœ|d#u�rªd$g}t�r~t d%dg¡ ¡  d&¡}t |ƒd'k�rdtj |d ¡ dd ¡}ntd(ƒ‚| d) |¡¡ n
| d*¡ d+ |d 
|¡¡g}d, |¡g}ng g g   }}}|||g}|	�rÔ| |¡ |||||g7 }t| d-ƒ�6}|D ] }d. 
|¡}| d/ |¡¡ �qôW d#  ƒ n1 �s,0    Y  d#S )0aÞ  Write a ninja file that does the desired compiling and linking.

    `path`: Where to write this file
    `cflags`: list of flags to pass to $cxx. Can be None.
    `post_cflags`: list of flags to append to the $cxx invocation. Can be None.
    `cuda_cflags`: list of flags to pass to $nvcc. Can be None.
    `cuda_postflags`: list of flags to append to the $nvcc invocation. Can be None.
    `sources`: list of paths to source files
    `objects`: list of desired paths to objects, one per source.
    `ldflags`: list of flags to pass to linker. Can be None.
    `library_target`: Name of the output library. Can be None; in that case,
                      we do no linking.
    `with_cuda`: If we should be compiling with CUDA.
    c                 S   s   | d u rg S dd„ | D ƒS d S )Nc                 S   s   g | ]}|  ¡ ‘qS r   r”  r    r   r   r   r   ¸  r   z=_write_ninja_file.<locals>.sanitize_flags.<locals>.<listcomp>r   )rq  r   r   r   Úsanitize_flags´  s    z)_write_ninja_file.<locals>.sanitize_flagsr   r	  r
  r  zninja_required_version = 1.3zcxx = {}r´   r7   r   z	nvcc = {}zcflags = {}r   zpost_cflags = {}zcuda_cflags = {}zcuda_post_cflags = {}zldflags = {}c                 S   s   g | ]}t j |¡‘qS r   rG  r•  r   r   r   r   Ü  r   z%_write_ninja_file.<locals>.<listcomp>zrule compilez@  command = cl /showIncludes $cflags -c $in /Fo$out $post_cflagsz  deps = msvczD  command = $cxx -MMD -MF $out.d $cflags -c $in -o $out $post_cflagsz  depfile = $out.dz  deps = gcczrule cuda_compilez?  command = $nvcc $cuda_cflags -c $in -o $out $cuda_post_cflagsZcuda_compilere   ú:z$:z$ zbuild {}: {} {}Nz	rule linkr   r   r   z'MSVC is required to load C++ extensionsz8  command = "{}/link.exe" $in /nologo $ldflags /out:$outz%  command = $cxx $in $ldflags -o $outzbuild {}: link {}z
default {}r   r=  z{}

)r/   r$   r!   r"   r#   r¤   r4   rº   rA   r»   r>   Úzipr¹   rn  r'   r(   r)   rt   r+   r,   rd  r%   rB  )r+   r¥   rÏ   rÐ   rÑ   rÍ   rÎ   rV  rW  rÔ   r¡  r[   Úconfigr   rq  Zcompile_ruleZcuda_compile_ruleÚbuildr˜  Zobject_fileZis_cuda_sourceZruleZ	link_ruleZcl_pathsZcl_pathÚlinkÚdefaultÚblocksZ
build_fileÚblockÚlinesr   r   r   r[  œ  sž    
ÿÿ

ÿ
ÿ
ÿÿÿ



r[  c                  G   s$   t du rtdƒ‚tjjt g| ¢R Ž S )zÖ
    Joins paths with CUDA_HOME, or raises an error if it CUDA_HOME is not set.

    This is basically a lazy way of raising an error for missing $CUDA_HOME
    only once we need to get any CUDA-specific path.
    NzSCUDA_HOME environment variable is not set. Please set it to your CUDA install root.)r   r=   r!   r+   r>   r?   r   r   r   r»     s    r»   )r+   r   c                 C   s*   ddg}t r| d¡ tj | ¡d |v S )Nr›   rœ   r�   r   )rº   r¤   r!   r+   r™  )r+   Z	valid_extr   r   r   r¹   (  s    
r¹   )F)F)	NNNNNFNTT)NNNNNNNFNTTT)T)N)N)Zr·   r.   r�  r!   rd   rÈ   r   r'   rR   rž  rp   rl  r1   Ztorch._appdirsZ
file_batonr   Z_cpp_extension_versionerr   rN  r   Zhipify.hipify_pythonr   r   Útypingr   r	   Zsetuptools.command.build_extr
   rS   r$   r  r   r5   r<   rA   rs   ru   r{   rr   r6   r*  r;   r8   rº   r%  ry   rt   r   r"   r#   rJ   re   rM   rð   rñ   r¬   r¿   rL  r‚  ÚboolrP   rU   rZ   rk   r~   Úobjectr   r"  r&  r  r  r;  rD  r4  rØ   rO  r’   rZ  r^  r­   r¾   r5  rE   rw  r\  rR  r_  r[  r»   r¹   r   r   r   r   Ú<module>   sì   
 $
þ#8   +,9&)         öøa            ó
 ! ööC÷,÷-	6D?ù ÷