a
    dk                     @   s,  d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZmZmZmZ d dlZd dlmZ d dlmZ d dlmZmZmZmZ d dlmZmZ d d	lmZ d d
l m!Z!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- d dl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z;m<Z<m=Z=m>Z>m?Z? eee$f e4e
e/ e@dddZAeddG dd dZBeddG dd dZCee4 e<e9eDddddZEeee5e4f e/e
e@ dddZFdd ee4 e
e/ e9eDeee4  e@d!d"d#ZGee4 ee4 e
e/ e9e	e1e/f e<eDdd$d%d&ZHee4 e9e	e1e/f e<eDdd'd(d)ZIe@e@ee@ eDedd*d+d,ZJe	e1e	e6e0f f e	e1e/f d-d.d/ZKd;ee@ e@ee4geDf eDee
e4 e	e1e	e6e0f f f d1d2d3ZLe@e@ee@ ee@ e9eDee-ee- f d4d5d6ZMdd7d8d9ZNeOd:kr(eN  dS )<    N)defaultdict)	dataclass)CallableDictListOptionalSequenceTextIOTupleUnion)dest)cpp)CppSignatureCppSignatureGroupCType
NamedCType)method_with_native_functionwith_native_function_and_index)et_cpp)ComputeNativeFunctionStubgen_custom_ops_registration)ExecutorchCppSignature)Unboxing)get_custom_build_selector get_native_function_declarations(get_native_function_schema_registrations
LineLoaderparse_native_yaml
ParsedYaml)	BackendIndexBackendMetadataDispatchKeyis_cuda_dispatch_keyLocationNativeFunctionNativeFunctionsGroupOperatorNameVariant)SelectiveBuilder)contextFileManagermake_file_managermapMaybeNamespaceHelper)sigfbackend_indicesreturnc              	      s   t |dks jrdS  fdd|D }d}t |dkr|d  }|rddd	 |  D }d
|j d|j d| d}nd jj dt | d}d j	 d j d| 
  d| d	S )a  
    For a given `NativeFunction`, find out the corresponding native function and dispatch to it. If zero or more than one
    native function exists, error out. A simplified version of register_dispatch_key.py
    Arguments:
        sig: A CppSignature for this native function we want to use.
        f: NativeFunction to generate static dispatch.
        backend_indices: All available backends.
    Return:
        C++ code to call backend-specific functions, e.g., "return at::native::add(self, other, scale);"
    r    c                    s   g | ]}|  r|qS  )Z
has_kernel).0br/   r3   `/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchgen/gen_executorch.py
<listcomp>E       z#static_dispatch.<locals>.<listcomp>N   , c                 s   s   | ]}|j V  qd S Nname)r4   ar3   r3   r7   	<genexpr>J   r9   z"static_dispatch.<locals>.<genexpr>z	return ::::(z);zH
ET_ASSERT_UNREACHABLE_MSG("The number of native function(s) binding to z is z	.");
    
// 
TORCH_API inline z {
    z
}
)lenZmanual_kernel_registration
get_kerneljoin	argumentsZcpp_namespacekernelfuncr>   	namespacedecl)r.   r/   r0   backendsZstatic_blockZbackend_metadataargsr3   r6   r7   static_dispatch3   s.    rO   T)frozenc                   @   sT   e Zd ZU ee ed< eed< eed< ee	gef ed< e
e	ee dddZdS )	ComputeFunctionstatic_dispatch_backend_indicesselectoruse_aten_libis_custom_opr/   r1   c                 C   s   | j |j d|jj s d S tj|jvr0d S | jrLt	j
|d|jd nt
|}| jr| |sd}d|j d|j d|  d|  d|d	d
 | D  dS t||| jdS d S )NrA   FmethodZfallback_bindingr;   rC   rD   z {
    return at::rB   c                 s   s   | ]}|j V  qd S r<   r=   r4   er3   r3   r7   r@   x   r9   z+ComputeFunction.__call__.<locals>.<genexpr>z);
}
            )r0   )rS   is_root_operatorrK   rJ   r>   r'   functionvariantsrT   r   from_native_functionmanual_cpp_bindingmost_faithful_signaturer   rU   rL   rG   rH   rO   rR   )selfr/   r.   commar3   r3   r7   __call__e   s8    
zComputeFunction.__call__N)__name__
__module____qualname__r   r   __annotations__r(   boolr   r$   r   r   strrc   r3   r3   r3   r7   rQ   [   s   
rQ   c                   @   s2   e Zd ZU eed< eed< eeedddZ	dS )ComputeCodegenUnboxedKernelsrS   rT   rV   c                 C   s  | j |j d|jj s dS | jrJtj|d|jd	 }t
j}t
j}nt|}tj}tj}t|d| \}}d}d}|dd	 |D  }	t|jjd
krt|jjjd
krtd|j d|jjjd
 }
dt| d|
j d}d}nBt|jjjd
kr0dt| d}||jj d }nd}d}d|j d|jj d|| d|jj d| d|j d|  d|	 d| dS )NrA   r2   FrW   )argument_type_genz
	r;   c                 s   s   | ]}|j V  qd S r<   r=   rY   r3   r3   r7   r@      r9   z8ComputeCodegenUnboxedKernels.__call__.<locals>.<genexpr>r   zCan't handle native function z  with no returns and no out yet.zstack[z] = &;z*stack[z] = EValue(result_);z result_ = z
Operator(
    "z$",
    [](EValue** stack) {
        z-

        EXECUTORCH_SCOPE_PROF("native_call_z");
        ztorch::executor::rB   z);

        z

    }
),
)rS   r[   rK   rJ   r>   rT   r   r^   r_   r`   aten_cppZargumenttype_typeZreturns_typer   r   r   Zconvert_argumentsrH   rG   rE   returnsout	ExceptionZcpp_type)ra   r/   r.   rk   Zreturn_type_genZbinding_listZ	code_listZcode_connectorZarg_connectorargs_strro   Zreturn_assignmentZ
ret_prefixr3   r3   r7   rc      sh    

	z%ComputeCodegenUnboxedKernels.__call__N)
rd   re   rf   r(   rg   rh   r   r$   ri   rc   r3   r3   r3   r7   rj      s   
rj   )native_functionscpu_fmrS   rT   r1   c                    s>   t ttf tddd}|jd| | fddddhd	 d S )
N)fnr1   c                 S   s   | j S r<   )	root_namert   r3   r3   r7   key_func   s    zgen_unboxing.<locals>.key_funcz!RegisterCodegenUnboxedKernels.cppc                    s   dt  | giS )Nunboxed_ops)rj   rv   rS   rT   r3   r7   <lambda>   s    zgen_unboxing.<locals>.<lambda>r:   rx   )Zkey_fnZenv_callableZ
num_shardsZsharded_keys)r   r$   r%   ri   Zwrite_sharded)rr   rs   rS   rT   rw   r3   ry   r7   gen_unboxing   s    r{   )gbackend_indexr1   c                 C   sZ   t | tsJ tj| d}|| }|d u r0g S |jr:dnd}| d|j|jd dgS )Nr6   ZstaticZ	TORCH_API r=   rl   )
isinstancer$   r   r^   rF   externalrL   rI   )r|   r}   r.   metadataprefixr3   r3   r7   #compute_native_function_declaration   s    
r   custom_ops_native_functions)rr   static_dispatch_idxrS   rT   r   r1   c              
      s   t t}| D ]}||j | qd}d}|D ]^}	t|	ddd}
ttt||| fddd||	 }|d|
j d|| d|
j	 d7 }q.|S )	a  
    Generates namespace separated C++ function API inline declaration/definitions.
    Native functions are grouped by namespaces and the generated code is wrapped inside
    namespace blocks.

    E.g., for `custom_1::foo.out` in yaml file we will generate a C++ API as a symbol
    in `torch::executor::custom_1::foo_out`. This way we avoid symbol conflict when
    the other `custom_2::foo.out` is available.
    r2   
   )Znamespace_strentity_nameZ	max_levelc                    s    d uo|  v S r<   r3   r6   r   r3   r7   rz     s   z,gen_functions_declarations.<locals>.<lambda>)rR   rS   rT   rU   z	
        )
r   listrK   appendr-   r,   rQ   ZprologuerG   epilogue)rr   r   rS   rT   r   Zns_grouped_functionsZnative_functionZfunctions_declarationsnewlinerK   Z	ns_helperZdeclarationsr3   r   r7   gen_functions_declarations   s<    
r   )rr   r   r   rS   r0   rs   rT   r1   c              	      sf   dg r,| ddfdd  d |d fdd |dfd	d d S )
Nz#include <ATen/Functions.h>zCustomOpsNativeFunctions.hzNativeFunctions.hc                      s   dt  tjdiS NZnativeFunctions_declarations)Zgrouped_native_functionsr0   Znative_function_decl_genr   r   r   r3   )r0   r   r3   r7   rz   *  s    zgen_headers.<locals>.<lambda>%#include "CustomOpsNativeFunctions.h"zFunctions.hc                      s"   r ndgt ddS )Nz#include "NativeFunctions.h")rr   r   rS   rT   r   )Zstatic_dispatch_extra_headersZFunctions_declarations)r   r3   )aten_headersr   rr   rS   r   rT   r3   r7   rz   5  s    c                      s   dt  rtjntdiS r   r   r3   )r0   rr   rT   r3   r7   rz   E  s    )write_with_templater   writerr   r   r   rS   r0   rs   rT   r3   )r   r0   r   rr   rS   r   rT   r7   gen_headers  s     

r   )rr   rS   r0   rs   rocmr1   c                    s   t j| }t|||d\ |d dd fdd |d ddfdd t|d	\|d
fdd d S )N)rr   rS   r}   r   ZRegisterzCustomOps.cppz RegisterDispatchKeyCustomOps.cppc                      s   d  d dS )Nr   r2   Zops_headersr!   Zdispatch_namespaceZdispatch_namespaced_definitionsZdispatch_anonymous_definitions"static_init_dispatch_registrations)lowerr3   )anonymous_definitiondispatch_keyr   r3   r7   rz   g  s    z gen_custom_ops.<locals>.<lambda>zStub.cppc                      s"   d    dttt dS )Nr2   r   )r   r   r,   r   r3   )r   rr   r   r3   r7   rz   s  s    
)rr   Zschema_selectorzRegisterSchema.cppc                      s
    dS )N)schema_registrationsaten_schema_registrationsr3   r3   )r   r   r3   r7   rz     s    )r!   CPUr   r   r   r   )rr   rS   r0   rs   r   r}   r3   )r   r   r   rr   r   r   r7   gen_custom_opsQ  s@    

r   )tags_yaml_pathaten_yaml_pathnative_yaml_pathrT   out_filer1   c              
      s  |r@t |d}||  W d   n1 s20    Y  dS t|| ddd}|j}dd |D }|rtj|rt|j	dkrdS t |d"}	t
j|	td}
|
sW d   dS |
D ]}t|d	tsJ |t||d	 t fd
d d|vrd|d< d|v r$W d   qt|dts>J ||d}d|vrZd| }||v shJ |||d< W d   q1 s0    Y  qt
j|
|dd W d   n1 s0    Y  dS )a  Translates Executorch DSL dialect to use the same syntax as
    native_functions.yaml. The major difference is that Executorch DSL dialect
    supports "op" key, where it refers to the operator name in native_functions.yaml.

    For example, a functions.yaml may have the following entry:

    - op: add.out
      ...

    It needs to be translated to the following:

    - func: add.out(Tensor self, Tensor other, *, Scalar alpha=1, Tensor(a!) out) -> Tensor(a!)
      ...

    We go in aten_yaml_path and find the operator schema for "add.out" and add it
    to the original functions.yaml. We also add required field "variants", where for
    Executorch it will always be "function".

    For ATen mode we don't have to do the translation because native_yaml_path is
    the same as native_functions.yaml.

    Args:
        tags_yaml_path: Path to a tags.yaml file to satisfy codegen parsing.
            It is not optional.
        aten_yaml_path: Path to ATen operator yaml file native_functions.yaml.
        native_yaml_path: Path to a functions.yaml file to parse.
            If the path does not exist in the filesystem, it is treated as an
            empty file. If `custom_ops_yaml_path` exists, the contents of that
            file are appended to the yaml input to be parsed.
        use_aten_lib: We use this flag to determine if we want to generate native
            functions. In ATen mode we should generate out= variants.
        out_file: The IO object that we are writing into.
    Returns:
        None
    rNFskip_native_fns_genc                 S   s(   i | ] }|j  d |jj t|jqS )rA   )rK   rJ   r>   ri   r4   r/   r3   r3   r7   
<dictcomp>  s   z)translate_native_yaml.<locals>.<dictcomp>r   )LoaderZ__line__c                      s   d  dS )Nzin z:
  r3   r3   locr3   r7   rz     r9   z'translate_native_yaml.<locals>.<lambda>r]   r\   rJ   oprA   zaten::i  )width)open
writelines	readlinesr   rr   ospathexistsstatst_sizeyamlloadr   r   getintr#   popr)   ri   dump)r   r   r   rT   r   Z	aten_yamlZaten_parsed_yamlZaten_native_functionsZschema_dictZnative_yamlZ	native_esrZ   opnamer3   r   r7   translate_native_yaml  sP    *,




0r   )bsr1   c                 C   s<   t dd }|  D ]"\}}t|ddt||d||< q|S )Nc                   S   s   t tjdddi dS )NTFr   Zuse_out_as_primaryr   Zdevice_guardindex)r   r!   	Undefinedr3   r3   r3   r7   rz     s   z)convert_backend_indices.<locals>.<lambda>TFr   )r   itemsr   r"   )r   indiceskvr3   r3   r7   convert_backend_indices  s    	r   F)r   r   function_filterr   r1   c                    s   | rt j| rt | jdkrt| |d |d}tt||j}dd |D t	t
tf t	t
tf dfdd  fdd	|j D }||fS g i fS d S )
Nr   r   c                 S   s   g | ]}|j jqS r3   )rJ   r>   r   r3   r3   r7   r8   
  r9   zparse_yaml.<locals>.<listcomp>)mr1   c                    s    fdd D S )Nc                    s   i | ]}|v r| | qS r3   r3   )r4   r   )r   op_namesr3   r7   r     r9   z1parse_yaml.<locals>.map_index.<locals>.<dictcomp>r3   r   )r   r   r7   	map_index  s    zparse_yaml.<locals>.map_indexc                    s   i | ]\}}| |j qS r3   )r   )r4   r   r5   )r   r3   r7   r     s   zparse_yaml.<locals>.<dictcomp>)r   r   r   r   r   r   r   filterrr   r   r&   r    r0   r   )r   r   r   r   parsed_yamlrr   r0   r3   )r   r   r7   
parse_yaml  s"     


r   )r   r   r   custom_ops_yaml_pathrS   rT   r1   c              	      s0  ddl }ttd fdd}| }tj|d}	t|	d }
t| ||||
 W d   n1 sd0    Y  t	|	| || \}}t	|| |d\}}|| }t
t}|| |D ]8}||vr|||| i qi || || ||< qt|t|}t|t|}W d   n1 s0    Y  ||fS )	a  Parses functions.yaml and custom_ops.yaml files.

    Args:
        tags_yaml_path: Path to a tags.yaml file to satisfy codegen parsing.
            It is not optional.
        aten_yaml_path: Path to ATen operator yaml file native_functions.yaml.
        native_yaml_path: Path to a functions.yaml file to parse.
            If the path does not exist in the filesystem, it is treated as an
            empty file. If `custom_ops_yaml_path` exists, the contents of that
            file are appended to the yaml input to be parsed.
        custom_ops_yaml_path: Path to a custom_ops.yaml file to parse. If
            the path does not exist in the filesystem, it is ignored.
        selector: For selective build.
        use_aten_lib: We use this flag to determine if we want to generate native
            functions. In ATen mode we should generate out= variants.
    Returns:
        A tuple with two elements:
        [0]: The parsed results of concatenating the contents of
             `native_yaml_path` and `custom_ops_yaml_path`.
        [1]: The parsed results of the contents of `custom_ops_yaml_path`, if
             present. If not present, None.
    r   NrV   c                    s
     | S r<   )Zis_native_function_selectedr6   rS   r3   r7   r   :  s    z)parse_yaml_files.<locals>.function_filterztranslated.yamlwT)tempfiler$   rh   TemporaryDirectoryr   r   rG   r   r   r   r   dictupdater   r   )r   r   r   r   rS   rT   r   r   Z
tmpdirnameZtranslated_yaml_pathZ
translatedZtranslated_functionsZtranslated_backend_indicesZcustom_ops_functionsZcustom_ops_backend_indicesZcombined_functionsZcombined_backend_indicesZdkZcombined_yamlcustom_ops_parsed_yamlr3   r   r7   parse_yaml_files  sJ    
"


$r   )r1   c               	   C   s>  t jdd} | jdddd | jddd	d | jd
ddd | jdddd | jdddddd | jdddd | jdddd | jdddd d! | jd"d#dd$d! | jd%d&d'd | jd(d)d | jd*dd+d | jd,d-dd.d | jd/tdd0d1gd0d1gd2d3 |  }|jsJ d4t|j|j}t	|j
|j|j|j||jd5\}}|j|j }}|rd|jng }t|d6}|tj g}	d0|jv rt|||	||||jd7 d1|jv rt||||jd8 |rt|||||jd9 |jr:t|j }
|
j}|
j}|d:ffD ]0\}}|| }|
j||  }||t| qd S );NzGenerate operator source files)descriptionz-sz--source-pathz-path to source directory for kernel templates)helpz--functions-yaml-pathz--functions_yaml_pathzpath to the functions.yaml file to use. Optional, but at least one of --functions-yaml-path and --custom-ops-yaml-path must be specified.z--custom-ops-yaml-pathz--custom_ops_yaml_pathzpath to the custom_ops.yaml file to use. Optional, but at least one of --functions-yaml-path and --custom-ops-yaml-path must be specified.z--aten-yaml-pathz--aten_yaml_pathz#path to native_functions.yaml file.z-dz--install-dirz--install_dirzoutput directoryzbuild/generated)r   defaultz-oz--output-dependenciesz:output a list of dependencies into the given file and exitz	--dry-run
store_truez5run without writing any files (still updates outputs))actionr   z--static-dispatch-backendz--static_dispatch_backend*z?generate static dispatch code for the specific backend (if set))nargsr   z--op-registration-whitelistz--op_registration_whitelistzfilter op registrations by the whitelist (if set); each item is `namespace`::`operator name` without overload name; e.g.: aten::empty aten::conv2d ...z--op-selection-yaml-pathz--op_selection_yaml_pathaD  Provide a path to the operator selection (for custom build) YAML that contains the information about the set of selected operators and their categories (training, ...). Each operator is either a full operator name with overload or just a bare operator name. The operator names also contain the namespace prefix (e.g. aten::)z--tags-pathz>Path to tags.yaml. Required by yaml parsing in codegen system.z--rocmz=reinterpret CUDA as ROCm/HIP and adjust filepaths accordinglyz--use-aten-libz--use_aten_libzka boolean flag to indicate whether we use ATen kernels or not, in the future this flag will be per operatorz
--generateheaderssourceszGenerate only a subset of files)typer   choicesr   r   z.tags.yaml is required by codegen yaml parsing.)r   r   r   r   rS   rT   )optionsr   )rr   rs   rS   rT   )rr   rS   r0   rs   r   r2   ) argparseArgumentParseradd_argumentri   
parse_argsZ	tags_pathr   Zop_registration_whitelistZop_selection_yaml_pathr   r   Zfunctions_yaml_pathr   rT   rr   r0   r+   r!   r   generater   r{   r   r   Zoutput_dependenciespathlibPathresolver>   stemparentZwrite_outputs)parserr   rS   r   r   rr   r0   r   rs   r   Zdepfile_pathZdepfile_nameZdepfile_stemZfmr   varnamer   r3   r3   r7   mainf  s
   	
	

r   __main__)F)Pr   r   r   collectionsr   Zdataclassesr   typingr   r   r   r   r   r	   r
   r   r   Ztorchgenr   Ztorchgen.apir   rm   Ztorchgen.api.typesr   r   r   r   Ztorchgen.contextr   r   Ztorchgen.executorch.apir   Z"torchgen.executorch.api.custom_opsr   r   Ztorchgen.executorch.api.typesr   Z torchgen.executorch.api.unboxingr   Ztorchgen.genr   r   r   r   r   r   Ztorchgen.modelr   r    r!   r"   r#   r$   r%   r&   r'   Z!torchgen.selective_build.selectorr(   Ztorchgen.utilsr)   r*   r+   r,   r-   ri   rO   rQ   rj   rh   r{   r   r   r   r   r   r   r   r   r   rd   r3   r3   r3   r7   <module>   s   ( ,

()D
2
8
?T
  M %
