
    Og                    R   d dl m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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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' d dl(m)Z)m*Z*m+Z+ d dl,m-Z-m.Z.m/Z/ d dl0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6 d dl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA d dlBmCZCmDZDmEZEmFZFmGZG erd dlHmIZI d dlJmKZK d*dZL	 	 	 	 	 	 	 	 d+dZM ed       G d d             ZN ed       G d d             ZO	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZPe	 	 	 	 	 	 d-d       ZQdd 	 	 	 	 	 	 	 	 	 	 	 d.d!ZR	 	 	 	 	 	 	 	 d/d"ZS	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d0d#ZT	 	 	 	 	 	 	 	 	 	 	 	 d1d$ZU	 	 	 	 	 	 	 	 	 	 	 	 d2d%ZV	 d3	 	 	 	 	 	 	 	 	 d4d&ZW	 	 	 	 	 	 	 	 	 	 	 	 	 	 d5d'ZXd6d(ZYeZd)k(  r eY        yy)7    )annotationsN)defaultdict)	dataclass)Path)AnyCallableTextIOTYPE_CHECKING)dest)cpp)CppSignatureCppSignatureGroupCType
NamedCType)method_with_native_function"method_with_nested_native_functionwith_native_function_and_index)et_cpp)ComputeNativeFunctionStubgen_custom_ops_registration)
contextArgExecutorchCppSignature)Unboxing)ETKernelIndexETKernelKeyETParsedYaml)	ET_FIELDSparse_et_yamlparse_et_yaml_struct)get_custom_build_selector get_native_function_declarations8get_native_function_declarations_from_ns_grouped_kernels(get_native_function_schema_registrations
LineLoaderparse_native_yaml)
BackendIndexBackendMetadataDEFAULT_KERNEL_NAMESPACEDispatchKeyFunctionSchemaLocationNativeFunctionNativeFunctionsGroupOperatorNameVariant)contextFileManagermake_file_managermapMaybeNamespaceHelper)Sequence)SelectiveBuilderc                   t        | t              r| j                         S t        j                  | j
                  j                        j                         }| j                         D cg c]  }|j                          }}dj                  t        j                         g|z         }| d| j                          d| d}|S c c}w )z
    A wrapper function to basically get `sig.decl(include_context=True)`.
    For ATen kernel, the codegen has no idea about ET contextArg, so we
    use this wrapper to add it.
    ,  ())
isinstancer   declaten_cppreturns_typefuncreturnscpp_type	argumentsjoinr   name)sigr?   acpp_argscpp_args_strsig_decls         ^/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torchgen/gen_executorch.py_sig_decl_wrapperrL   A   s     #-.xxz(()9)9:CCEL"%--/2Q2H299joo/08;<LqAl^1=HO 3s   *Cc           	        t        |      dk(  s|j                  ry|D cg c]  }|j                  |      s| }}d}t        |      dk(  r]|d   j                  |      }|rmdj	                  d | j                         D              }d|j                   d|j                   d	| d
}n&d|j                  j                   dt        |       d}d|j                   d|j                   dt        |        d| d	S c c}w )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    N   r8   c              3  4   K   | ]  }|j                     y wNrE   ).0rG   s     rK   	<genexpr>z"static_dispatch.<locals>.<genexpr>h   s     =QVV=   z	return ::::r:   z);zH
ET_ASSERT_UNREACHABLE_MSG("The number of native function(s) binding to z is z	.");
    
// 
TORCH_API inline z {
    z
}
)lenmanual_kernel_registration
has_kernel
get_kernelrD   rC   cpp_namespacekernelr@   rE   	namespacerL   )rF   fbackend_indicesbbackendsstatic_blockbackend_metadataargss           rK   static_dispatchrg   Q   s    ?q A$@$@*>aall1o>H>L
8}#A;11!499=S]]_==D&'7'E'E&FbIYI`I`HaabcgbhhjkLHHI}TXY\]eYfXg hKK=166( #C() *N   ?s
   C<C<T)frozenc                  H    e Zd ZU ded<   ded<   ded<   ded<   edd	       Zy
)ComputeFunctionlist[BackendIndex]static_dispatch_backend_indicesr6   selectorbooluse_aten_lib Callable[[NativeFunction], bool]is_custom_opc                   d}| j                   j                  |j                   d|j                  j                         sy t
        j                  |j                  vrt
        j                  |j                  v rd}n^t
        j                  |j                  v rt
        j                  |j                  vs&t        d|j                   d|j                   d      | j                  r0t        j                  |d|j                        j                         nt        j                  |      }| j                  r| j!                  |      sd}|rd	|j                   d|j                   d
t#        |       d|j%                         d   j                   d|j	                          d|j'                  d |j%                         dd  D               dS d	|j                   d|j                   d
t#        |       d|j	                          d|j'                  d |j%                         D               dS t)        ||| j*                        S )NFrV   TCan't handle native function z* with the following variant specification .methodfallback_bindingr8   rW   rX   z {
    return r   r:   c              3  4   K   | ]  }|j                     y wrQ   rR   rS   es     rK   rT   z+ComputeFunction.__call__.<locals>.<genexpr>   s     =baff=brU   rO   z);
}
z {
    return at::c              3  4   K   | ]  }|j                     y wrQ   rR   ry   s     rK   rT   z+ComputeFunction.__call__.<locals>.<genexpr>   s     'H1'HrU   )ra   )rm   is_root_operatorr_   r@   rE   r/   functionvariantsrv   	Exceptionro   r   from_native_functionmanual_cpp_bindingmost_faithful_signaturer   rq   rL   rC   rD   rg   rl   )selfr`   is_method_variantrF   commas        rK   __call__zComputeFunction.__call__   s   !}}--R}.MN1::-'..AJJ2N $ ""ajj0W^^1::5U/x7abcblblammno     22%!2F2F%%''<<Q? 	 T%6%6q%9E KK=166( #C() *MMOA##$Achhj\5::=bcmmo^_^`Na=b3b2c d KK=166( #C() *
|1UZZ'H'HHI J  # $ D D     N)r`   r,   return
str | None)__name__
__module____qualname____annotations__r   r    r   rK   rj   rj   y   s,    %7722 , !,r   rj   c                  <    e Zd ZU ded<   ded<   e	 	 	 	 dd       Zy)ComputeCodegenUnboxedKernelsr6   rm   rn   ro   c                f   |d   }|d   d   }|d   d   }|j                    d|j                  j                   }| j                  j	                  |      syt        |t              s|g}| j                  j                  ||D cg c]  }|j                          c}      }|sy| j                  rt        j                  |d|j                        j                         }t        j                  }	t        j                   }
|j#                         }d|j                    d|j                          }nbt%        j                  |      }t&        j                  }	t&        j                   }
|j#                  d      }|j(                   d|j*                   }t-        |		      j/                  |      \  }}d
}d}|j1                  d |D               }d}g }t3        |j                  j4                        dk(  rt3        |j                  j"                  j6                        dk(  rt9        d|j                   d      |j                  j"                  j6                  d   }dt3        |       d|j                   d}d}t3        |      g}nt3        |j                  j"                  j6                        dk(  rIdt3        |       d} |
|j                  j4                        j;                         dz   }t3        |      g}n[d}d}t=        t?        t3        |j                  j"                  j6                                    D cg c]  }t3        |      |dz   z
   }}|D ]  }|d| dz  } d}dj1                  |D cg c]  }d|j                    d|j                  j                   d|dk7  r|dz   |dz   z   nd dtA        jB                          d|j1                  |       d|j                  j                   d |j                  j                   d!| | d"| d#| d$| d% c}      S c c}w c c}w c c}w )&Nr   rO   rV   rN   Fru   ztorch::executor::)include_context)argument_type_genz
	r8   c              3  4   K   | ]  }|j                     y wrQ   rR   ry   s     rK   rT   z8ComputeCodegenUnboxedKernels.__call__.<locals>.<genexpr>   s     (FA(FrU   rs   z  with no returns and no out yet.zstack[z] = &;z*stack[z] = EValue(result_);z result_ = zJinternal::event_tracer_log_evalue(context.internal_event_tracer(), *stack[z]);
z
    
z
Kernel(
    "z",default"z
    [](z, EValue** stack) {
        zr

        internal::EventTracerProfileOpScope event_tracer_op_scope(context.internal_event_tracer(), "native_call_z/");
        EXECUTORCH_SCOPE_PROF("native_call_z");
        z
(context, z);
        	
        z

    }
),
)"r_   r@   rE   rm   r|   r<   listet_get_selected_kernelsto_native_stringro   r   r   r   r   r>   argumenttype_typer?   rC   r   r   r]   r^   r   convert_argumentsrD   rY   rA   outr   rB   reversedranger   defn)r   unbox_kernel_entryr`   
kernel_keykernel_metaop_namekused_kernel_keysrF   r   return_type_genrC   kernel_callbinding_list	code_listcode_connectorarg_connectorargs_strevent_tracer_output_logging
output_idsr   return_assignment
ret_prefixi	output_idnewlines                             rK   r   z%ComputeCodegenUnboxedKernels.__call__   sA   
 /q16H6KA6N
'9!'<Q'?[[MAFFKK=1}}--g6*d+$J==@@J?qa((*?
   #88%!2F2F%%'  !) : :&33OI-akk]"SXXZLIK(==a@C & 8 8$11Oe<I(667r+:L:L9MNK"*/#


I
& 	 i
  #(((F(FFG&(#
qvv~~!#166##''(A-3AFF8;[\  &&""&&q)C$*3|+<*=U388*A PJl+,J166##''(A-L 122FI " -QVV^^<EEG-W
!,/0
$&!
 &eC0@0@0D0D,E&FG %Q/
 
 $ 	I'#E+'	 yy  * kk]"QVV[[M!y.GcMQX$>VX#Y Z 				Y	'( )qqrqwqwq|q|p} ~,,-FFKK= 9		[MH: 6		$% &		 
 	
E @js   P$
>P)9B$P.N)r   :tuple[NativeFunction, tuple[ETKernelKey, BackendMetadata]]r   str)r   r   r   r   r   r   r   r   rK   r   r      s6    'c
Vc
 
c
 (c
r   r   c           	         	 	 	 	 dd}| D 	cg c]/  }|j                  |      j                         D ]  \  }}	|||	ff 1 c}	}}rdndg|rdnd}
|j                  |
|fdddd	h
       y c c}	}}w )Nc                T    | d   j                   dz   | d   d   j                         z   S )Nr   :rO   )	root_namer   )items    rK   key_funczgen_unboxing.<locals>.key_func+  s/     Aw  3&a)D)D)FFFr   Functions.hNativeFunctions.hzRegisterKernels.cppz!RegisterCodegenUnboxedKernels.cppc                H     t              |       g| d   k(  rdS g dS )Nr   )unboxed_kernels	fn_header)r   )r   headeritemsrm   ro   s    rK   <lambda>zgen_unboxing.<locals>.<lambda>@  sA    D,X|DEWX  "U1X-  	1
  1
 r   rO   r   r   )key_fnenv_callable
num_shardssharded_keys)r   r   r   r   )get_kernelsr   write_sharded)native_functionscpu_fmrm   ro   kernel_indexmanual_registrationr   native_functionr   metadatafilenamer   r   s     ``       @@rK   gen_unboxingr   !  s    GHG	G  0O O$0$<$<_$M$S$S$UO !J 
:x01O1OE  ,m1DEF  	0 
 
 '5  Os   4A9c           	         t        | t              sJ t        j                  |       |j	                  |       j                         }|g S dfd}dD cg c]  }|D ]  } |||        c}}S c c}}w )N)r`   c                D    j                  | j                  |       dS )N)rE   r   r   )r=   r^   )r   r   rF   s     rK   gen_declz5compute_native_function_declaration.<locals>.gen_declY  s#    (((QRRSTTr   )FT)r   r'   r   rn   r   r   )r<   r,   r   r   r   values)gr   metadata_listr   r   r   rF   s         @rK   #compute_native_function_declarationr   M  s     a(((
 
5
5
:C ,,Q/668M	U
  -%  	?++  s   A3)custom_ops_native_functionsc                x   |j                         }t        t              }| D ]   }||j                     j	                  |       " d}d}	|D ]k  }
t        |
dd      }t        t        t        |g||fd      ||
               }|d|j                   d|	j                  |       d|j                   dz  }m |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.
    rN   r      )namespace_strentity_name	max_levelc                    d uxr | v S rQ   r   )r`   r   s    rK   r   z,gen_functions_declarations.<locals>.<lambda>  s    +Fd+R ,988 r   )rl   rm   ro   rq   r   )_to_backend_indexr   r   r_   appendr4   r3   rj   prologuerD   epilogue)r   r   rm   ro   r   backend_indexns_grouped_functionsr   functions_declarationsr   r_   	ns_helperdeclarationss       `        rK   gen_functions_declarationsr   c  s    * !224M&t,+ P_667>>OPG) 	##
	
 5BO%!-"9	 %Y/	
 	 '
  l  
  	# 	%. "!r   c                D   t        t              }| D ]  }t               }|j                  |      }|j	                         D ][  }|r|j
                  }|j                  |       nt        }t        |      dk  s
J d|        ||   j                   |||             ]  |S )NrO   z6Codegen only supports one namespace per operator, got )
r   r   setr   r   r]   addr(   rY   extend)	r   r   native_function_decl_genns_grouped_kernelsr`   native_function_namespaces
op_kernelsre   r_   s	            rK   get_ns_grouped_kernelsr     s     0;4/@ %(U"!--a0
 * 1 1 3 	,::	*..y94	./14eGHbGcde4y)00(L9	 r   c           	        	
 dgt         j                  j                         i|r(|j                  ddfd       j	                  d       |j                  d fd       |j                  dd	        d
ddgi	r,	d
   j	                  d       |j                  d	 fd       yt         t              
|j                  d	
fd       y)a%  Generate headers.

    Args:
        native_functions (Sequence[NativeFunction]): a collection of NativeFunction for ATen ops.
        gen_custom_ops_header (bool): whether we should generate CustomOpsNativeFunctions.h
        custom_ops_native_functions (Sequence[NativeFunction]): a collection of NativeFunction for custom ops.
        kernel_index (ETKernelIndex): kernel collection
        cpu_fm (FileManager): file manager manages output stream
        use_aten_lib (bool): whether we are generating for PyTorch types or Executorch types.
    z#include <ATen/Functions.h>zCustomOpsNativeFunctions.hr   c                 F    t         t        j                        ddgdS )Ngrouped_native_functionsra   r   z#include <ATen/ATen.h>z#include <torch/torch.h>)nativeFunctions_declarationsheaders)r!   r   r   )ra   r   s   rK   r   zgen_headers.<locals>.<lambda>  s.    0P-H$3-1-U-U1 -.
 r   %#include "CustomOpsNativeFunctions.h"r   c                 4    r ndgt              dS )Nz#include "NativeFunctions.h")r   r   rm   ro   r   )static_dispatch_extra_headersFunctions_declarations)r   )aten_headersr   r   r   rm   ro   s   rK   r   zgen_headers.<locals>.<lambda>  s/     .:01&@!1)!),G'	
 r   zRegisterKernels.hc                 
    ddiS )Ngenerated_commentz(@generated by torchgen/gen_executorch.pyr   r   r   rK   r   zgen_headers.<locals>.<lambda>  s    !P
 r   r   zK#include <executorch/runtime/core/exec_aten/exec_aten.h> // at::Tensor etc.z=#include <executorch/runtime/kernel/kernel_runtime_context.h>z3#include <executorch/codegen/macros.h> // TORCH_APIc                 T    t        dt         t        j                        ifi S )Nr   r   )dictr!   r   r   )ra   r   r   s   rK   r   zgen_headers.<locals>.<lambda>  s5    D24T1A(7151Y1Y5	 	 r   )r   r   r   c                 4    t        dt              ifi  S )Nr   )r   )r  r"   )r   r   s   rK   r   zgen_headers.<locals>.<lambda>  s)    D24l+=5  r   N)r)   CPUr   write_with_templater   writer   r   )r   gen_custom_ops_headerr   rm   r   r   ro   r   ra   r   r   s   ` ``` `@@@@rK   gen_headersr
    s    ( 22L"(F(F(HIO""(
	
 	CD
LL	
 	
 LL	
 	YK
G 	!!"WX		
 4-%%H

 	
	
r   c                   	 t         j                  t         |||      \  	|j                  d dd	fd       |j                  d dd 	fd       t	         |      \  |j                  d	fd
       y )N)r   rm   r   rocmRegisterzCustomOps.cppz RegisterDispatchKeyCustomOps.cppc                 2    dj                         d dS )Nr   rN   ops_headersr)   dispatch_namespacedispatch_namespaced_definitionsdispatch_anonymous_definitions"static_init_dispatch_registrations)lower)anonymous_definitiondispatch_keyr  s   rK   r   z gen_custom_ops.<locals>.<lambda>1  s%    B'"."4"4"6/1.B2T
 r   zStub.cppc            
     h    d  j                         dt        t        t                           dS )NrN   r  )r  r   r3   r   )r  r   r  s   rK   r   z gen_custom_ops.<locals>.<lambda>=  s<    '"."4"4"6/1.2246FG/ 3U	
 r   )r   schema_selectorzRegisterSchema.cppc                      dS )N)schema_registrationsaten_schema_registrationsr   )r  r  s   rK   r   z gen_custom_ops.<locals>.<lambda>R  s    $8)B
 r   )r)   r  r   r  r#   r  )
r   rm   r   r   r  r  r  r  r  r  s
   `    @@@@@rK   gen_custom_opsr    s     ??L 	$)!		* 
<..*	
 
<.)*		
$ 	1) 	!
 LL	
r   c                   |r4t        |      5 }|j                  |j                                ddd       yt        || dd      \  }}|D ci c]2  }|j                  |j
                   d|j                  j                   4 }	}|	j                         D 
ci c]  \  }
}|
j                  | }}
}|	j                         D 
ci c]  \  }
}|t        |
       }}
}|j                         D ci c]  \  }}||   | }}}|rAt        j                  j                  |      r"t        j                  |      j                  dk(  ryt        |      5 }t        j                  |t               }|s
	 ddd       y|D ]  }t#        |j%                  d      t&              sJ |       t)        ||j+                  d            t-        fd      5  d	|vrd
|d	<   d|v r
	 ddd       jt#        |j%                  d      t              sJ |       |j+                  d      }d|vrd|z   }||v sJ |j%                  |      |d<   ||v r ||   j                         D ]
  \  }}|||<    ddd        t        j.                  ||d       ddd       y# 1 sw Y   yxY wc c}w c c}}
w c c}}
w c c}}w # 1 sw Y   @xY w# 1 sw Y   yxY w)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
    NF)skip_native_fns_genrV   r   Loader__line__c                     d  dS )Nzin z:
  r   )locs   rK   r   z'translate_native_yaml.<locals>.<lambda>  s    3se5!1 r   r~   r}   r@   opzaten::i  )width)open
writelines	readlinesr   r@   r_   rE   r   r   ospathexistsstatst_sizeyamlloadr$   r<   getintr+   popr0   dump)tags_yaml_pathaten_yaml_pathnative_yaml_pathro   out_file	aten_yamlr   persisted_fieldsr`   func_to_scoped_namer@   rE   op_to_scoped_nameschema_dictr%  vkernel_persist_dictnative_yaml	native_esrz   opnamer   r$  s                         @rK   translate_native_yamlrC  Y  s   T .! 	7Y	 3 3 56	7)6!	*&& :J6451;;-r!&&++//6 6 +>*C*C*E2&D$		42 2 6I5N5N5PQztT4T?QKQ.>.D.D.F6%*R"q 6 6
 ww~~./77#$,,1		 3;IIk*=	3 3  	!AaeeJ/58q85+QUU:->?C12 !Q&$.AjMQ;	! !
 "!%%+s36Q63tv%%.F,,,'OOF3&	 00 3F ; A A C !1 !!! !	!( 			)XT213 3;	762 R6"! !3 3s[    J7JJ#J)3J/K=AKJ5 	K)A>J5'"KJ5J?:KKc                v   | rt         j                  j                  |       rtt        j                  |       j                  dkD  rQt        |       5 }t        j                  |t              }d d d        t        d D              rt        |      nd }|D ]  }t        D ]  }|j                  |d         ! t        | |d ||      }	t        t        ||	j                               }
|
D cg c]  }|j"                  j$                   c}|?|j&                  j)                         D ci c]  \  }}|v r|| }}}|
t+        |      fS 	 	 	 	 dfd}|	j,                  j)                         D ci c]  \  }}| ||j&                         }}}|
|fS g i fS # 1 sw Y   0xY wc c}w c c}}w c c}}w )Nr   r   c              3  $   K   | ]  }d |v  
 yw)kernelsNr   ry   s     rK   rT   zparse_yaml.<locals>.<genexpr>  s     +GqIN+Gs   )r  loaded_yaml)indexc                @    | D ci c]  }|v s|| |    c}S c c}w rQ   r   )mr%  op_namess     rK   	map_indexzparse_yaml.<locals>.map_index  s'     )*<"R8^B"I<<<s   	)rJ  #dict[OperatorName, BackendMetadata]r   rM  )r*  r+  r,  r-  r.  r'  r/  r0  r$   anyr   r   r3  r%   r   filterr   r@   rE   rH  r   r   ra   )r+  r5  function_filterr  r`   esr   entryfieldparsed_yamlr   r   kernel_mappingfiltered_indexrL  r   rb   ra   rK  s                     @rK   
parse_yamlrW    s    t$)>)>)B$Z 	111Z0B	1
 ),+GB+G(G $T 	
  	'E" '		%&'	' ( 3
  8T8T UV)9:AAFFKK: # 0</A/A/G/G/I+G^h& 'N 
 $]%HHH	=2	=0	= 1<0K0K0Q0Q0S
&,q!Ay!!
 
  002vY	1 	1* ;
s   F-F*,F/5F5F'c           	     P   ddl }dfd}|j                         5 }t        j                  j	                  |d      }	t        |	d      5 }
t        | ||||
       ddd       t        |	| ||       \  }}t        || |d      \  }}t        |t              st        j                  |      }t        |t              st        j                  |      }||z   }t        j                  ||      }t        ||      }t        ||      }ddd       ||fS # 1 sw Y   xY w# 1 sw Y   fS xY w)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   Nc                &    j                  |       S rQ   )is_native_function_selected)r`   rm   s    rK   rP  z)parse_yaml_files.<locals>.function_filter  s    33A66r   ztranslated.yamlwT)r`   r,   r   rn   )tempfileTemporaryDirectoryr*  r+  rD   r'  rC  rW  r<   r   from_backend_indicesmerge_indicesr   )r5  r6  r7  custom_ops_yaml_pathrm   ro   r\  rP  
tmpdirnametranslated_yaml_path
translatedtranslated_functionstranslated_indicescustom_ops_functionscustom_ops_indicescombined_functionscombined_kernel_indexcombined_yamlcustom_ops_parsed_yamls       `              rK   parse_yaml_filesrl    sT   < 7 
	$	$	& X*!ww||J8IJ&, 	
! 	 4> ./|CS4
00 4> ./44
00
 ,m<!.!C!CDV!W,m<!.!C!CDV!W14HH - ; ; 2!
 %%79NO!-.BDV!W;X> 000;	 	X> 000s$   -D	DB(DD	DD%c            	     6   t        j                  d      } | j                  ddd       | j                  ddd	       | j                  d
dd       | j                  ddd       | j                  ddddd       | j                  ddd       | j                  ddd       | j                  dddd !       | j                  d"d#dd$!       | j                  d%d&d'       | j                  d(d)       | j                  d*dd+       | j                  d,d-dd.       | j                  d/d0dd1       | j                  d2t        dd3d4gd3d4gd56       | j	                         }|j
                  sJ d7       t        |j                  |j                        }t        |j                  |j
                  |j                  |j                  ||j                  8      \  }}|j                  |j                  }}|r|j                  ng }t!        |9      }d3|j"                  v r&t%        ||j                  |||||j                  :       d4|j"                  v rAt'        ||||j                  ||j(                  ;       |rt+        |||||j,                  <       |j.                  r{t1        |j.                        j3                         }	|	j4                  }
|	j6                  }|d=ffD ]7  \  }}||z   }|	j8                  ||
z   z  }|j;                  |t        |             9 y y )>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)ro  r   z-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))actionro  z--static-dispatch-backendz--static_dispatch_backend*z?generate static dispatch code for the specific backend (if set))nargsro  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--manual_registrationz--manual-registrationzfa boolean flag to indicate whether we want to manually callregister_kernels() or rely on static init. z
--generater   sourceszGenerate only a subset of files)typers  choicesr   ro  z.tags.yaml is required by codegen yaml parsing.)r6  r5  r7  r`  rm   ro   )options)r   r	  r   rm   r   r   ro   )r   r   rm   ro   r   r   )r   rm   r   r   r  rN   )argparseArgumentParseradd_argumentr   
parse_args	tags_pathr    op_registration_whitelistop_selection_yaml_pathrl  r6  functions_yaml_pathr`  ro   r   r   r2   generater
  r   r   r  r  output_dependenciesr   resolverE   stemparentwrite_outputs)parserrw  rm   rT  rk  r   r   r   r   depfile_pathdepfile_namedepfile_stemfmprefixvarnamer+  s                   rK   mainr  ;  s   $$1QRF <  
         2   !   I   D  
 ##N	   %%-	   ""M   M   L  
 	   6	   I&I&.   !GNNN())&&H
 +;--(( 44$99))+'K' 	$$   #
 4J//r   w/FG$$$-")">">(C% --	
 G$$$- --% ' ; ;	
 '!<!)\\ ""G778@@B#((#(( RL
 	1JB |+G&&&<*?@DWc$i0	1 #r   __main__)rF   %CppSignature | ExecutorchCppSignaturer   r   )rF   r  r`   r,   ra   rk   r   r   )r   Sequence[NativeFunction]r   r1   rm   r6   ro   rn   r   r   r   rn   r   None)r   z%NativeFunctionsGroup | NativeFunctionr   r   r   z	list[str])r   r  r   r   rm   r6   ro   rn   r   zSequence[NativeFunction] | Noner   r   )r   r  r   r   r   zKCallable[[NativeFunctionsGroup | NativeFunction, ETKernelIndex], list[str]]r   zdict[str, list[str]])r   r  r	  rn   r   r  rm   r6   r   r   r   r1   ro   rn   r   r  )r   r  rm   r6   r   r   r   r1   r  rn   r   r  )r5  r   r6  r   r7  r   ro   rn   r8  r	   r   r  )F)
r+  r   r5  r   rP  rp   r  rn   r   zctuple[list[NativeFunction], dict[DispatchKey, dict[OperatorName, BackendMetadata]] | ETKernelIndex])r5  r   r6  r   r7  r   r`  r   rm   r6   ro   rn   r   z(tuple[ETParsedYaml, ETParsedYaml | None])r   r  )[
__future__r   rx  r*  collectionsr   dataclassesr   pathlibr   typingr   r   r	   r
   r/  torchgenr   torchgen.apir   r>   torchgen.api.typesr   r   r   r   torchgen.contextr   r   r   torchgen.executorch.apir   "torchgen.executorch.api.custom_opsr   r   torchgen.executorch.api.typesr   r    torchgen.executorch.api.unboxingr   torchgen.executorch.modelr   r   r   torchgen.executorch.parser   r   r   torchgen.genr    r!   r"   r#   r$   r%   torchgen.modelr&   r'   r(   r)   r*   r+   r,   r-   r.   r/   torchgen.utilsr0   r1   r2   r3   r4   collections.abcr5   !torchgen.selective_build.selectorr6   rL   rg   rj   r   r   r   r   r   r
  r  rC  rW  rl  r  r   r   r   rK   <module>r     sd   "  	 # !  7 7   ( Q Q 
 + M 5 N N T T     (B #	.## (# 		#P $6 6 6t $i
 i
 i
X).) ) 	)
 )  ) ) 
)X  ,<I  6 DH3".3"  3" 	3"
 3" "A3" 	3"l.  	 >a
.a
  a
 ":	a

 a
  a
 a
 a
 
a
H:.: :  	:
 : : 
:z`3`3`3 !`3 	`3
 `3 
`3N !&	6
66 66 	6
6rC1C1C1 !C1 %	C1
 C1 C1 .C1Li1X zF r   