a
    hη                     @   s  U d 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 ddlmZ dd	lmZmZ dd
lmZ ddlZddlZG dd deZG dd dZeeef ZdZi Zeed< dddZg dZG dd de Z!dd Z"G dd dZ#G dd dZ$eedddZ%eee&dd d!Z'd"d# Z(dneeeee&e&ee d&d'd(Z)eeeeeee*f e&e&e$e&dd)
d*d+Z+d,d- Z,d.d/ Z-e.d0Z/d1d2 Z0d3d4 Z1d5d6 Z2d7d8 Z3e.d9Z4d:d; Z5e.d<Z6d=d> Z7e.d?Z8d@dA Z9dodBdCZ:dDdE Z;dFdG Z<dHdI Z=dJdK Z>dLdM Z?G dNdO dOZ@G dPdQ dQZAeA ZBi ZCeA ZDi ZEeeeFf edR< i ZGe
D ]ZHeIeHesJ eHJ D ]\ZKZLeLd ZMeLdd ZNejOeNvreDPeK ejQeNv reEReKdSreMeGeK< neMeEeK< ejSeNvrejQeNvreBPeK eMeCeK< qqze.eBT ZUe.dTeDT  dUZVe.dVZWe.dWZXe.dXZYe.dYZZeeeeeee*f e&e&e$e&ed)
dZd[Z[dpd\d]Z\d^d_ Z]d`da Z^e.dbZ_dcdd Z`dedf Zadqee&eeeeeee&ee&e&e&e&ee$ edkdldmZbdS )ra   The Python Hipify script.
##
# Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
#               2017-2018 Advanced Micro Devices, Inc. and
#                         Facebook Inc. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
    N   )	constants)CUDA_TO_HIP_MAPPINGS)MATH_TRANSPILATIONS)Optional)Iterator)MappingIterable)Enumc                   @   s   e Zd ZdZdZdS )CurrentStater      N)__name__
__module____qualname__INITIALIZEDDONE r   r   \/var/www/html/assistant/venv/lib/python3.9/site-packages/torch/utils/hipify/hipify_python.pyr   -   s   r   c                   @   s   e Zd Zdd Zdd ZdS )HipifyResultc                 C   s   || _ || _d| _d S )N current_statehipified_pathstatus)selfr   r   r   r   r   __init__2   s    zHipifyResult.__init__c                 C   s   d| j  d| j d| j S )NzHipifyResult:: current_state: z, hipified_path : z
, status: r   r   r   r   r   __str__7   s    zHipifyResult.__str__N)r   r   r   r   r   r   r   r   r   r   1   s   r   z;// !!! This is a file automatically generated by hipify!!!
HIPIFY_FINAL_RESULTZscalar_t)ZDtypeT)!
InputErroropenfbcolorsGeneratedFileCleanermatch_extensionsmatched_files_iterpreprocess_file_and_save_resultcompute_statsadd_dim3processKernelLaunchesfind_closure_groupfind_bracket_groupfind_parentheses_groupreplace_math_functionship_header_magicreplace_extern_sharedget_hip_file_pathis_out_of_placeis_pytorch_fileis_cusparse_fileis_special_fileis_caffe2_gpu_filer5   Triepreprocessorfile_specific_replacementfile_add_headerfix_static_global_kernelsextract_argumentsstr2boolr   r   hipifyc                       s$   e Zd Z fddZdd Z  ZS )r    c                    s   t  | || _d S N)superr   message)r   r@   	__class__r   r   r   N   s    zInputError.__init__c                 C   s   d| j  S )NzInput error: )r@   r   r   r   r   r   R   s    zInputError.__str__)r   r   r   r   r   __classcell__r   r   rA   r   r    K   s   r    c                 C   s   t | |ddS )Nignore)errors)open)filenamemoder   r   r   r!   V   s    r!   c                   @   s,   e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
r"   z[95mz[94mz[92mz[93mz[91mz[0mz[1mz[4mN)r   r   r   HEADERZOKBLUEOKGREENWARNINGZFAILENDCZBOLDZ	UNDERLINEr   r   r   r   r"   [   s   r"   c                   @   s<   e Zd ZdZdddZdd Zdd Zdd	d
Zdd ZdS )r#   z+Context Manager to clean up generated filesFc                 C   s   || _ t | _g | _d S r>   )keep_intermediatessetfiles_to_cleandirs_to_clean)r   rM   r   r   r   r   p   s    zGeneratedFileCleaner.__init__c                 C   s   | S r>   r   r   r   r   r   	__enter__u   s    zGeneratedFileCleaner.__enter__c                 O   s6   t j|s | jt j| t|g|R i |S r>   )ospathexistsrO   addabspathrF   )r   fnargskwargsr   r   r   rF   x   s    zGeneratedFileCleaner.openc                 C   sx   t j|\}}|s$t j|\}}|rF|rFt j|sF| j|dd t j|rV|stt | | jt j	| d S )NT)exist_ok)
rR   rS   splitrT   makedirsisdirmkdirrP   appendrV   )r   dnrZ   parentnr   r   r   r\   }   s    
zGeneratedFileCleaner.makedirsc                 C   s@   | j s<| jD ]}t| q| jd d d D ]}t| q,d S )N)rM   rO   rR   unlinkrP   rmdir)r   typevalue	tracebackfdr   r   r   __exit__   s
    
zGeneratedFileCleaner.__exit__N)F)F)	r   r   r   __doc__r   rQ   rF   r\   rk   r   r   r   r   r#   n   s   


r#   )rS   returnc                 C   s   |  tjdS )N/)replacerR   sep)rS   r   r   r   _to_unix_path   s    rq   )rG   
extensionsrm   c                    s   t  fdd|D S )z<Helper method to see if filename ends with certain extensionc                 3   s   | ]}  |V  qd S r>   endswith).0erG   r   r   	<genexpr>       z#match_extensions.<locals>.<genexpr>any)rG   rr   r   rw   r   r$      s    r$   c                    s   t  fdd|D S )Nc                 3   s   | ]}t   |V  qd S r>   )fnmatch)ru   patternfilepathr   r   rx      ry   z_fnmatch.<locals>.<genexpr>rz   )r   patternsr   r~   r   _fnmatch   s    r   r   F)	root_pathincludesignoresrr   out_of_place_onlyis_pytorch_extensionrm   c                 c   s   t |}tj| ddD ]\}}}	tj|| }
|
dkrvd|v rH|d d|v rZ|d d|v rv|d |d |	D ]x}ttj||}ttj|
|}t	||rzt	||szt
||s||v rz|st|st|sqz|rt|sqz|V  qzqd S )NT)topdown.z.gitbuildZthird_partyzthird_party/nvfuser)rN   rR   walkrS   relpathremover_   rq   joinr   r$   r2   r5   r1   )r   r   r   rr   r   r   exact_matchesZabs_dirpathdirs	filenamesZrel_dirpathrG   r   rel_filepathr   r   r   r%      s8    



r%   )
output_directoryr   	all_filesheader_include_dirsstatship_clang_launchr   	clean_ctxshow_progressrm   c	              
   C   st   t jt j| |}	ttj|	d}
|
t|	< t| ||||||||	}|rhd|j	vrht
|	d|j|j	dd |t|	< d S )N)r   r   Zignoredz->T)flush)rR   rS   rV   r   r   r   r   r   r7   r   printr   )r   r   r   r   r   r   r   r   r   fin_pathhipify_resultresultr   r   r   r&      s    

r&   c                 C   sP   dd | d D }t dt|d t d| t dt| d d d S )	Nc                 S   s   h | ]\}}|qS r   r   )ru   Z	cuda_callZ	_filepathr   r   r   	<setcomp>   ry   z compute_stats.<locals>.<setcomp>unsupported_callsz1Total number of unsupported CUDA function calls: rj   , z+
Total number of replaced kernel launches: kernel_launches)r   lenr   )r   r   r   r   r   r'      s    r'   c                 C   s  d}d}|  dd dd} dd tdD }d|| d< t| D ]\}}|d	krV q|d
krh|d	7 }n|dkrx|d	8 }|dks|t| d	 krB|dkrB||dk || d< |d	7 }|dk rB|d	 || d< qB| |d d |d d d	  }| |d	 d |d	 d  }| |d d |d d   ddd}	| |d	 d |d	 d   ddd}
d|	 d}d|
 d}| |	|}| |
|}| || || }|S )zBadds dim3() to the second and third arguments in the kernel launchr   <<<r   >>>c                 S   s   g | ]}i qS r   r   )ru   _r   r   r   
<listcomp>   ry   zadd_dim3.<locals>.<listcomp>r   startr   (),end
 zdim3()ro   range	enumerater   strip)kernel_stringcuda_kernelcountclosureZarg_locsindcZfirst_arg_rawZsecond_arg_rawZfirst_arg_cleanZsecond_arg_cleanZfirst_arg_dim3Zsecond_arg_dim3Zfirst_arg_raw_dim3Zsecond_arg_raw_dim3r   r   r   r(      s6    
  **r(   z([ ]+)(detail?)::[ ]+\\\n[ ]+c                    sV  t dd    fdd}dd }dd }t|| } }|D ]
}||} d	|d
 }	 |d d |	d  }
 |d |d
  }|d d
 dkrdnd} |d d || d
 d  }t||
}ttd|d dd	dd}d|dd ddd|  d dddd|d	| d  }||
|}|d | qD|S )zK Replace the CUDA style Kernel launches with the HIP style kernel launches.c                 S   s   |  d |  d dS )Nr   r   z::groupinpr   r   r   <lambda>  ry   z'processKernelLaunches.<locals>.<lambda>c           
         s  | d | d dddddddd}ddi}d}d}d	}d
}|}t |d d d ddD ]"} | }	|||fv r|	dkr||kr|}||d d< |d  d7  < |	dkr|d  d8  < |d dkr||kr||d d< |}||krZ |  s | dv rP||kr|}||d d< |dkr~d|d d< |d |d |d g  S qZ||krZ||d d< |d |d |d g  S qZd S )Nr   r   r   r   rc   )kernel_launchkernel_nametemplatez<>r   r   r      r   >r   <>   r   r   #:r   r   )r   isalnum)
Z	in_kernelposr   ZSTARTZAT_TEMPLATEZAFTER_TEMPLATEZAT_KERNEL_NAMEr   icharstringr   r   grab_method_and_template  sD    

z7processKernelLaunches.<locals>.grab_method_and_templatec                 S   sd   d}g }|  d|dkr`|  d|}|  d|d }|dkrDtd|||| || d q|S )zKFinds the starting and ending points for all kernel launches in the string.r   r   rc   r   r   zno kernel end found)r   r   r   )findr    r_   )r   Z
kernel_endZkernel_positionsZkernel_startr   r   r   find_kernel_boundsS  s    

z1processKernelLaunches.<locals>.find_kernel_boundsc                 S   s   d}d}d}| D ]}|dkrf|dkr2|dkr2d}q|dkrH|dkrHd}q|dkr|dkr|dkrd}nX|dkr|d	ks~|d
krd}n:|dkr|dkr|dkrd}n|dkr|dkr|dkrd}|}|dkr||7 }q|d7 }q|S )Nr   rn   z//*z/*"\'r   xr   )r   Z
in_commentZprev_cZ
new_stringr   r   r   r   mask_commentsk  s2    

z,processKernelLaunches.<locals>.mask_commentsr   r   r   r   r   rc   r   r   r   r   zhipLaunchKernelGGL(z, 0   r   r   )	RE_KERNEL_LAUNCHsublistr   r(   r   r;   ro   r_   )r   r   r   r   r   Zget_kernel_positionsoutput_stringZkernelparamsZparenthesisr   r   Zend_param_indexZkernel_name_with_templateZcuda_kernel_dim3Znum_klpZ
hip_kernelr   r   r   r)     s6    ;!
 
"r)   c                 C   s   d}d}|}d\}}|t | k r| | |d krP|du rFd}d}|}q|d7 }n0| | |d kr|r|d8 }|dkr|}||fS |d7 }qdS )a  Generalization for finding a balancing closure group

         if group = ["(", ")"], then finds the first balanced parentheses.
         if group = ["{", "}"], then finds the first balanced bracket.

    Given an input string, a starting position in the input string, and the group type,
    find_closure_group returns the positions of group[0] and group[1] as a tuple.

    Example:
        >>> find_closure_group("(hi)", 0, ["(", ")"])
        (0, 3)
    Fr   )rc   rc   Tr   )NN)r   )input_stringr   r   Zinside_parenthesisZparensr   Zp_startZp_endr   r   r   r*     s$    

r*   c                 C   s   t | |ddgdS )z%Finds the first balanced parantheses.{}r   r*   r   r   r   r   r   r+     s    r+   c                 C   s   t | |ddgdS )z!Finds the first balanced bracket.r   r   r   r   r   r   r   r   r,     s    r,   z\bassert[ ]*\(c                 C   s.   | }t D ] }|| dt |  d}q|S )a  FIXME: Temporarily replace std:: invocations of math functions
        with non-std:: versions to prevent linker errors NOTE: This
        can lead to correctness issues when running tests, since the
        correct version of the math function (exp/expf) might not get
        called.  Plan is to remove this function once HIP supports
        std:: math function calls inside device code

    r   )r   ro   )r   r   funcr   r   r   r-     s    	r-   z:?:?\b(__syncthreads)\b(\w*\()c                    sh   |  ddg}t  fdd|D r& S d v }|d v 7 }|d v 7 }|t du7 }|rdd	|    S )
a  If the file makes kernel builtin calls and does not include the cuda_runtime.h header,
    then automatically add an #include to match the "magic" includes provided by NVCC.
    TODO:
        Update logic to ignore cases where the cuda_runtime.h is included by another file.
    zhip/hip_runtime.hzhip/hip_runtime_api.hc                 3   s(   | ] }t d | d| d V  qdS )z#include ("z"|<z>)N)research)ru   extr   r   r   rx     ry   z#hip_header_magic.<locals>.<genexpr>ZhipLaunchKernelGGL
__global__Z
__shared__Nz#include "hip/hip_runtime.h"
)r{   RE_SYNCTHREADSr   )r   headersZhasDeviceLogicr   r   r   r.     s    r.   zGextern\s+([\w\(\)]+)?\s*__shared__\s+([\w:<>\s]+)\s+(\w+)\s*\[\s*\]\s*;c                 C   s   | }t dd |}|S )a  Match extern __shared__ type foo[]; syntax and use HIP_DYNAMIC_SHARED() MACRO instead.
       https://github.com/ROCm/hip/blob/master/docs/markdown/hip_kernel_language.md#__shared__
    Example:
        "extern __shared__ char smemChar[];" => "HIP_DYNAMIC_SHARED( char, smemChar)"
        "extern __shared__ unsigned char smem[];" => "HIP_DYNAMIC_SHARED( unsigned char, my_smem)"
    c                 S   s.   d|  dpd d|  d d|  d dS )	NzHIP_DYNAMIC_SHARED(r   r   r   r   r   r   r   r   r   r   r   r   r     ry   z'replace_extern_shared.<locals>.<lambda>)RE_EXTERN_SHAREDr   )r   r   r   r   r   r/     s
    r/   c                 C   s   t j| rJ |s t| s | S t j| \}}t j|\}}|dkrLd}|}|}|dd}|dd}|dd}|dd}|dd}|d	kr|dd}|s||krt j|d}|r||kr|| |kr|d
 }t j||| S )z3
    Returns the new name of the hipified file
    .cu.hipcudaZhipCUDAHIPTHCTHHzcaffe2/coreZ_hip)rR   rS   isabsr1   r[   splitextro   r   )r   r   dirpathrG   rootr   orig_filenameZorig_dirpathr   r   r   r0   !  s*    $r0   c                 C   s>   t j| rJ | drdS | dr,dS | dr:dS dS )Ntorch/Fthird_party/nvfuser/tools/autograd/templates/TrR   rS   r   
startswithr   r   r   r   r1   i  s    


r1   c                 C   sZ   t j| rJ | dr,| dr(dS dS | dr:dS | drHdS | drVdS dS )Nzaten/zaten/src/ATen/core/FTr   r   r   r   r   r   r   r   r2   u  s    




r2   c                 C   s   t | rd|  v S dS )NsparseFr2   lowerr   r   r   r   r3     s    r3   c                 C   s<   t | r8d|  v rdS d|  v r8d|  v r4dS dS dS )Nr   TZlinalgZbatchlinearalgebralibblasFr   r   r   r   r   r4     s    r4   c                 C   sR   t j| rJ | drdS t j| }t j|\}}d|v sJ|dv oPd|vS )Nzc10/cudaTZgpur   .cuhZcudnn)rR   rS   r   r   basenamer   )r   rG   r   r   r   r   r   r5     s    
r5   c                   @   s   e Zd ZdZdd ZdS )TrieNodezA Trie node whose children are represented as a directory of char: TrieNode.
       A special char '' represents end of word
    c                 C   s
   i | _ d S r>   )childrenr   r   r   r   r     s    zTrieNode.__init__N)r   r   r   rl   r   r   r   r   r   r    s   r  c                   @   sV   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Ze	j
dd Zdd Zdd ZdS )r6   zCreates a Trie out of a list of words. The trie can be exported to a Regex pattern.
    The corresponding Regex should match much faster than a simple Regex union.c                 C   s&   t  | _tjdd| _| j | _dS )z,Initialize the trie with an empty root node.F)usedforsecurityN)r  r   hashlibmd5_hashdigest_digestr   r   r   r   r     s    zTrie.__init__c                 C   sT   | j |  | j  | _| j}|D ]}|j|t  |j| }q&d|jd< dS )zAdd a word to the Trie. Tr   N)	r  updateencoder  r  r   r  
setdefaultr  r   wordnoder   r   r   r   rU     s    zTrie.addc                 C   s   | j S )zReturn the root node of Trie. )r   r   r   r   r   dump  s    z	Trie.dumpc                 C   s
   t |S )z Escape a char for regex. )r   escape)r   r   r   r   r   quote  s    z
Trie.quotec                 C   s6   | j }|D ] }||jv r$|j| }q
 dS q
d|jv S )zZSearch whether word is present in the Trie.
        Returns True if yes, else return FalseFr   )r   r  r  r   r   r   r     s    
zTrie.searchc              	   C   sH  |}d|j v r$t|j  dkr$dS g }g }d}t|j  D ]j}t|j | trz,| |j | | j}|| 	||  W q t
y   || 	| Y q0 q>d}q>t|dk }	t|dkrt|dkr||d  n|dd| d  t|dkr|d }
ndd| d	 }
|rD|	r8|
d
7 }
nd|
 d}
|
S )zConvert a Trie into a regular expression pattern

        Memoized on the hash digest of the trie, which is built incrementally
        during add().
        r   r   Nr   []z(?:|r   ?z)?)r  r   keyssorted
isinstancer  _patternr  r_   r  	Exceptionr   )r   r   r  r  Zaltccqr   ZrecurseZcconlyr   r   r   r   r    s6    

zTrie._patternc                 C   s   |  | j| jS z#Export the Trie to a regex pattern.r  r   r  r   r   r   r   r}     s    zTrie.patternc                 C   s   |  | j| jS r  r  r   r   r   r   export_to_regex  s    zTrie.export_to_regexN)r   r   r   rl   r   rU   r  r  r   	functools	lru_cacher  r}   r  r   r   r   r   r6     s   
+r6   PYTORCH_MAPr   z(?<=\W)(z)(?=\W)z#include "([^"]+)"z#include <([^>]+)>z"#define THC_GENERIC_FILE "([^"]+)"z\.cu\bc	                    s  t jt j|t|}t }	| vrFd|	_d|	_tj	|	_
|	S tt j|}
tddT}| tkrd|	_d|	_tj	|	_
|	W  d   S |d | }W d   n1 s0    Y  |}t jt jt|
}t jt j|st j| dd fd	d
}r8t|}nDt|
rPt||}n,t|
rht|}ndd }t||}d' 	f	dd	}t|dd|}t|dd|}t|d|}|dr|dd}|dd}td|}st |	}|dr,d|vr,t!|}t"|}rv||krvt jt j|krv|	_d|	_tj	|	_
|	S |krt#drt| }d}t j|rt|dd}| |k}W d   n1 s0    Y  |rzVj|ddd}|$| W d   n1 s0    Y  ||	_d|	_tj	|	_
|	W S  t%y } zTt&t'j( d | d!|j) d" d#t'j* 	t+j,d$ |	_d%|	_tj	|	_
|	W  Y d}~S d}~0 0 n||	_d&|	_tj	|	_
|	S dS )(z< Executes the CUDA -> HIP conversion on the specified file. Nz[ignored, not to be hipified]zutf-8)encodingz#[ignored, input is hipified output]r   c                 S   s   t | d S Nr   )r"  r   mr   r   r   pt_repl[  s    zpreprocessor.<locals>.pt_replc                    s   t | d | S r$  )PYTORCH_SPECIAL_MAPgetr   r%  )r'  r   r   pt_special_repl^  s    z%preprocessor.<locals>.pt_special_replc                 S   s   t | d S r$  )
CAFFE2_MAPr   r%  r   r   r   c2_replk  s    zpreprocessor.<locals>.c2_replTc                    s$    	
fdd}|S )Nc              
      s  |  d}tj| |ds4|drJ|dsJt|  dS rt fddD rd }d }rtj}tj	tj
||}tj|r|}|}|d u rD ]<}tj
|}tj	tj
||}tj|r|}|}q|d u r|  dS |tvr,t|
		 nz|tv rt| }|jtjkrtj|}tj	tj
t|}	|	|_|t|< tj|	d ur|	n||S t| j}
ttj|
d ur|
n||S |  dS )Nr   )z	ATen/cudazATen/native/cudazATen/native/nested/cudazATen/native/quantized/cudazATen/native/sparse/cudazATen/native/transformers/cudazTHC/r   ZTHCPc                 3   s   | ]}|  V  qd S r>   rs   )ru   srw   r   r   rx     ry   z>preprocessor.<locals>.mk_repl.<locals>.repl.<locals>.<genexpr>r   )r   rR   rS   r   r   formatr0   r{   dirnamerV   r   rT   r   r&   r   r   r   r   r   rq   )r&  ri   Z
header_dirZheader_filepathZheader_dir_to_checkZheader_path_to_checkheader_include_dirZheader_resultZheader_rel_pathZheader_fout_pathZhipified_header_filepath)r   r   r   r   r   include_current_dirr   r   r   r   templrw   r   replq  sd    






z+preprocessor.<locals>.mk_repl.<locals>.replr   )r2  r1  r3  )	r   r   r   r   r   r   r   r   r   )r1  r2  r   mk_replp  s     :zpreprocessor.<locals>.mk_replz#include "{0}"z#include <{0}>Fz#define THC_GENERIC_FILE "{0}"zCMakeLists.txtr   r   r   r   r   r   Z	PowKernelz[skipped, no changes])r   r   .c.cc.cpp.h.hppwz[ok]zFailed to save z with "z", leaving z unchanged.filez[skipped, no permissions]z[skipped, already hipified])T)-rR   rS   rV   r   rq   r   r   r   r   r   r   r   rF   readlineHIPIFY_C_BREADCRUMBseekreadr0   rT   r/  r\   RE_PYTORCH_PREPROCESSORr   r4   r2   RE_CAFFE2_PREPROCESSORRE_QUOTE_HEADERRE_ANGLE_HEADERRE_THC_GENERIC_FILErt   ro   RE_CU_SUFFIXr)   r-   r.   r$   writeOSErrorr   r"   rK   strerrorrL   sysstderr)r   r   r   r   r   r   r   r   r   r   r   ZfinZoutput_sourceZorig_output_sourceZ	fout_pathr*  r,  r4  Zdo_writeZfout_oldZfoutrv   r   )
r   r   r   r   r   r   r   r'  r   r   r   r7   4  s    
&

<
,*&r7   c                    s   t | dj}| }|r>tdt| d fdd|}n|| }|d || |  W d    n1 sz0    Y  d S )Nr+z\b(z)\bc                    s    S r>   r   )r   replace_stringr   r   r     ry   z+file_specific_replacement.<locals>.<lambda>r   )	r!   r@  r   r   r  ro   r?  rG  truncate)r   Zsearch_stringrN  strictri   contentsr   rM  r   r8     s    &

r8   c                 C   s   t | dh}| }|d dkr8|d dkr8d| d}d| d| }|d || |  W d    n1 sx0    Y  d S )	NrL  r   r   rc   r   r   z	#include z 
)r!   r@  r?  rG  rO  )r   headerri   rQ  r   r   r   r9     s    

r9   c                 C   s   |  dd} | S )z<Static global kernels in HIP results in a compilation error.z __global__ staticr   ro   )Zin_txtr   r   r   r:     s    r:   z#include .*\nc                 C   s6  g }ddd}| }|d }|t |k r2|| dkrF|d  d7  < nt|| dkrd|d  d8  < nV|| dkr|d  d7  < n8|| dkr||d  dkr|d dkr|d  d8  < |d dkr|d dkr|||d	 q2|d dkr(|d dkr(|| d
kr(|||d	 |d }|d7 }q|S )ad   Return the list of arguments in the upcoming function parameter closure.
        Example:
        string (input): '(blocks, threads, 0, THCState_getCurrentStream(state))'
        arguments (output):
            '[{'start': 1, 'end': 7},
            {'start': 8, 'end': 16},
            {'start': 17, 'end': 19},
            {'start': 20, 'end': 53}]'
    r   )r   r   r   r   r   r   r   -r   r   )r   r_   )r   r   	argumentsZclosurescurrent_positionZargument_start_posr   r   r   r;     s.    (*
r;   c                 C   s.   |   dv rdS |   dv r dS tddS )zArgumentParser doesn't support type=bool. Thus, this helper method will convert
    from possible string types to True / False.)yestruety1T)nofalseri   rb   0FzBoolean value expected.N)r   argparseArgumentTypeError)vr   r   r   r<   ;  s
    r<   r   r   r5  r6  r7  r8  z.inr9  r   r8  r9  r   T)project_directoryshow_detailedrr   header_extensionsr   r   r   extra_filesr   r   r   r   r   hipify_extra_files_onlyr   rm   c                    s  dkrt  t js.td td sDd d krtfddD fddD t jst	 t
ttt
ttt
t|||d	}t|}|D ]0}t j|st j|}||vr|| qd
dlm} |D ]R}t j|r*||}n|t j|}| fdd|dD  q|d u rvtdd}g g d}|s|n|D ]}t||||||||
	 qttjd tj tjd |rt| tS )Nr   z,The project folder specified does not exist.r   rn   Z_amdc                    s   g | ]}|  qS r   rS  )ru   includer   re  r   r   r   e  ry   zhipify.<locals>.<listcomp>c                    s   g | ]}|  qS r   rS  )ru   rD   rk  r   r   r   f  ry   )r   r   rr   r   r   r   )Pathc                 3   sF   | ]>}|  rtt|rtt|st|j rt|V  qd S r>   )is_filer   strr$   name)ru   rS   )rg  r   r   r   r   rx     s
   
zhipify.<locals>.<genexpr>r   T)rM   )r   r   z-Successfully preprocessed all matching files.r;  )rR   getcwdrS   rT   r   rJ  exitrstripshutilcopytreer   maprq   r%   rN   r   r   r_   pathlibrl  extendrglobr#   r&   r"   rJ   rL   rK  r'   r   )re  rf  rr   rg  r   r   r   rh  r   r   r   r   r   ri  r   r   Zall_files_setri   rl  r0  Zheader_include_dir_pathr   r   r   )rg  r   r   r   re  r   r=   F  sZ    







r=   )r   r   r   FF)F)F)Frb  rc  r   r   rd  r   Fr   TFFFN)crl   r_  r|   r   rs  rJ  rR   r   r   Zcuda_to_hip_mappingsr   r   typingr   collections.abcr   r   r	   enumr
   r   r  r   r   dictrn  ZHipifyFinalResultr>  r   __annotations__ZPYTORCH_TEMPLATE_MAP__all__r  r    r!   r"   r#   rq   boolr$   r   r%   r   r&   r'   r(   compiler   r)   r*   r+   r,   Z	RE_ASSERTr-   r   r.   r   r/   r0   r1   r2   r3   r4   r5   r  r6   ZCAFFE2_TRIEr+  ZPYTORCH_TRIEr"  objectr(  mappingr  itemssrcrg   dstZ	meta_dataZ
API_CAFFE2rU   ZAPI_SPECIALr)  ZAPI_PYTORCHr  rB  rA  rC  rD  rE  rF  r7   r8   r9   r:   Z
RE_INCLUDEr;   r<   r=   r   r   r   r   <module>   s&  	
!     -
#
 &



H
^








 :

.              