o
    ki                    @  sN  U d dl mZ d dlZd dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZ d dlmZmZ e
rAd dlmZmZmZ ed	d
G dd dZG dd deZdZg dZg dZdgdd eD  ZddhZG dd deZG dd deZd{ddZeD ]!ZeD ]Ze eee se Z!e"e! e#de e d e! qqej$ej%ej&ej'ej(hZ)ej%ej&hZ*ej&ej+ej,ej-ej%ej$ej'ej.ej/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ej<ej=ej>ej?ej@ejAejBejCej(gZDd|d#d$ZEd|d%d&ZFd|d'd(ZGd|d)d*ZHd|d+d,ZIeFd-eGd.iZJG d/d0 d0eZKi ZLd1eMd2< eeKjNeKjOeKjPeKjQeKjRgeLd3< eeKjSeKjTgeLd4< eeKjUeKjVgeLd5< eLd3 eLd4 B eLd6< eLd6 eLd5 B eLd7< eLd4 eLd5 B eLd8< G d9d: d:eZWG d;d< d<eZXG d=d> d>eZYed	d
G d?d@ d@ZZG dAdB dBeZ[ed	d
G dCdD dDZ\ed	d
G dEdF dFZ]ed	d
G dGdH dHZ^ed	d
G dIdJ dJZ_ed	d
G dKdL dLZ`ed	d
G dMdN dNZaed	d
G dOdP dPZbG dQdR dReZced	d
G dSdT dTebZded	d
G dUdV dVebZeed	d
G dWdX dXebZfed	d
G dYdZ dZebZged	d
G d[d\ d\Zhed	d
G d]d^ d^Zied	d
G d_d` d`Zjed	d
G dadb dbZked	d
G dcdd ddZlg deZmed	d
G dfdg dgZned	d
G dhdi diZod}dmdnZped	d
G dodp dpZqd~dqdrZrddsdtZsddwdxZted	d
G dydz dzZudS )    )annotationsN)	dataclass)autoEnum)TYPE_CHECKING)assert_never)NamespaceHelper
OrderedSet)CallableIteratorSequenceT)frozenc                   @  s(   e Zd ZU ded< ded< d	ddZdS )
Locationstrfileintlinereturnc                 C  s   | j  d| j S )N:)r   r   self r   X/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torchgen/model.py__str__1   s   zLocation.__str__Nr   r   )__name__
__module____qualname____annotations__r   r   r   r   r   r   ,   s   
 r   c                   @  s   e Zd Ze Ze ZdS )VariantN)r   r   r   r   functionmethodr   r   r   r   r   6   s    
r   z
at::native)CPUCUDAHIPXLAMTIAMPSIPUXPUHPUVELazyMetaPrivateUse1PrivateUse2PrivateUse3) 	QuantizedSparse	SparseCsrNestedTensorAutogradAutogradNestedTensorc                 C  s   g | ]}d | qS )r6   r   ).0	componentr   r   r   
<listcomp>[   s    r:   	quantizedquantized_decomposedc                   @  sr  e Zd ZdZeZe Ze Ze Ze Z	e Z
e Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Z e Z!e Z"e Z#e Z$e Z%e Z&e Z'e Z(e Z)e Z*e Z+e Z,e Z-e Z.e Z/e Z0e Z1e Z2e Z3e Z4e Z5e Z6e Z7e Z8e Z9e Z:e Z;e Z<e Z=e Z>e Z?e Z@e ZAe ZBe ZCe ZDe ZEe ZFe ZGe ZHe ZIe ZJe ZKe ZLe ZMe ZNe ZOe ZPe ZQe ZRe ZSe ZTe ZUe ZVe ZWe ZXe ZYe ZZe Z[e Z\e Z]e Z^e Z_e Z`e Zae Zbe Zce Zde Zee Zfe Zge Zhe Zie Zje Zke Zle Zme Zne Zoe Zpe Zqe Zre Zse Zte Zue Zve Zwe Zxe Zye Zze Z{e Z|e Z}e Z~e Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze ZdddZdddZedd	d
ZdS )DispatchKeyr   r   r   c                 C     | j S Nnamer   r   r   r   r         zDispatchKey.__str__c                 C  s   t |  S r?   )r   lowerr   r   r   r   rC         zDispatchKey.lowervaluec                 C  2   t j D ]\}}|| kr|  S qtd|  )Nzunknown dispatch key )r=   __members__itemsAssertionErrorrE   kvr   r   r   parse   
   zDispatchKey.parseNr   )rE   r   r   r=   )r   r   r   	UndefinedCatchAllr   FPGAMAIAVulkanMetalMKLDNNOpenGLOpenCLIDEEPCustomRNGKeyId	MkldnnCPUr3   r4   r5   DensePythonTLSSnapshotPreDispatchPythonDispatcherPythonFuncTorchDynamicLayerBackMode
ZeroTensor	ConjugateNegativeBackendSelectNamedAutogradOtherAutogradFunctionalityr7   TracerAutocastAutocastCPUAutocastCUDABatchedVmapModeFuncTorchGradWrapperFuncTorchBatchedBatchedNestedTensorFuncTorchVmapModeFuncTorchDynamicLayerFrontModeFunctionalizeTESTING_ONLY_GenericWrapperTESTING_ONLY_GenericModeADInplaceOrViewr6   CompositeImplicitAutograd%CompositeImplicitAutogradNestedTensorCompositeExplicitAutograd&CompositeExplicitAutogradNonFunctionalFuncTorchBatchedDecompositionr"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   QuantizedCPUQuantizedCUDAQuantizedHIPQuantizedXLAQuantizedMTIAQuantizedMPSQuantizedIPUQuantizedXPUQuantizedHPUQuantizedVEQuantizedLazyQuantizedMetaQuantizedPrivateUse1QuantizedPrivateUse2QuantizedPrivateUse3	SparseCPU
SparseCUDA	SparseHIP	SparseXLA
SparseMTIA	SparseMPS	SparseIPU	SparseXPU	SparseHPUSparseVE
SparseLazy
SparseMetaSparsePrivateUse1SparsePrivateUse2SparsePrivateUse3SparseCsrCPUSparseCsrCUDASparseCsrHIPSparseCsrXLASparseCsrMTIASparseCsrMPSSparseCsrIPUSparseCsrXPUSparseCsrHPUSparseCsrVESparseCsrLazySparseCsrMetaSparseCsrPrivateUse1SparseCsrPrivateUse2SparseCsrPrivateUse3NestedTensorCPUNestedTensorCUDANestedTensorHIPNestedTensorXLANestedTensorMTIANestedTensorMPSNestedTensorIPUNestedTensorXPUNestedTensorHPUNestedTensorVENestedTensorLazyNestedTensorMetaNestedTensorPrivateUse1NestedTensorPrivateUse2NestedTensorPrivateUse3AutogradCPUAutogradCUDAAutogradHIPAutogradXLAAutogradMTIAAutogradMPSAutogradIPUAutogradXPUAutogradHPU
AutogradVEAutogradLazyAutogradMetaAutogradPrivateUse1AutogradPrivateUse2AutogradPrivateUse3r   rC   staticmethodrM   r   r   r   r   r=   d   s"   

r=   c                   @     e Zd Ze Ze Ze ZdS )_TorchDispatchModeKeyN)r   r   r   r   FAKEPROXY
FUNCTIONALr   r   r   r   r         
r   r   r   c                    s0   g } t D ] |  fddtD  qd| S )Nc                 3  s     | ]}d   | dV  qdS )z    z	 = auto()Nr   )r8   bcfkr   r   	<genexpr>      z.codegen_per_backend_entries.<locals>.<genexpr>
)FUNCTIONALITY_KEYSextendBACKEND_COMPONENTSjoinrr   r   r   codegen_per_backend_entries  s   
r   zMissing zL from DispatchKey enum.  Here is the autogenerated list we expect to have:

dkboolc                 C  s   | t jt jt jt jhv S r?   r=   ry   rz   rw   rx   r   r   r   r   is_generic_dispatch_keyM  s   r   c                 C      | t jt jt jt jt jt jhv S r?   )r=   r#   r}   r   r   r   r   r   r   r   r   is_cuda_dispatch_keyW     r   c                 C  r   r?   )r=   r)   r   r   r   r   r   r   r   r   r   is_xpu_dispatch_keyc  r   r   c                 C     | t v S r?   )STRUCTURED_DISPATCH_KEYSr   r   r   r   is_structured_dispatch_keyp  s   r   c                 C  r   r?   )UFUNC_DISPATCH_KEYSr   r   r   r   is_ufunc_dispatch_keyt     r   cudaxpuc                   @  s   e Zd Ze Ze Ze Ze Ze Ze Z	e Z
e Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze ZdddZedddZedd	d
ZedddZdS )
ScalarTyper   r   c                 C  r>   r?   r@   r   r   r   r   r     rB   zScalarType.__str__rE   ScalarType | Nonec                 C  s(   t j D ]\}}|| kr|  S qd S r?   )r   rG   rH   rJ   r   r   r   maybe_parse  s
   zScalarType.maybe_parsec                 C  s$   t | }|d u rtd|  |S )Nzunknown dtype )r   r   rI   )rE   mb_rr   r   r   rM     s   
zScalarType.parsevaluesOrderedSet[ScalarType]c                 C  sB   t  }| dD ]}|tv r|t|  q|t| q|S )N, )r	   splitDTYPE_CLASSESupdateaddr   rM   )r   dtypesrE   r   r   r   	parse_set  s   zScalarType.parse_setNr   )rE   r   r   r   )rE   r   r   r   )r   r   r   r   )r   r   r   r   ByteCharShortIntLongHalfFloatDoubleComplexHalfComplexFloatComplexDoubleBoolBFloat16Float8_e5m2Float8_e5m2fnuzFloat8_e4m3fnFloat8_e4m3fnuzFloat8_e8m0fnur   r   r   rM   r   r   r   r   r   r   }  s4    
r   z!dict[str, OrderedSet[ScalarType]]r   IntegralFloatingComplexAllAllAndComplexFloatingAndComplexc                   @  sN   e Zd Ze Ze Ze Ze Ze Ze Z	e Z
d	ddZed
ddZdS )UfuncKeyr   r   c                 C  r>   r?   r@   r   r   r   r   r     rB   zUfuncKey.__str__rE   c                 C  rF   )Nzunknown ufunc key )r  rG   rH   rI   rJ   r   r   r   rM     rN   zUfuncKey.parseNr   )rE   r   r   r  )r   r   r   r   CUDAFunctorCUDAFunctorOnOtherCUDAFunctorOnSelf	CPUScalar	CPUVector
ScalarOnlyGenericr   r   rM   r   r   r   r   r    s    
r  c                   @  s   e Zd ZdZdZdS )DeviceCheckTyper      N)r   r   r   NoCheck	ExactSamer   r   r   r   r    s    r  c                   @  r   )ViewSchemaKindN)r   r   r   r   aliasingaliasing_inplacenon_aliasingr   r   r   r   r    r   r  c                   @  s:  e Zd ZU ded< ded< ded< ded< ded	< d
ed< d
ed< ded< ded< ded< ded< ded< ded< ded< ded< d
ed< ded< ded< ded< ded < ded!< ded"< ded#< ded$< e	%d?d@d-d.ZdAd0d1ZdAd2d3ZedBd4d5Z	edBd6d7Z
edCd9d:ZedDd;d<ZedBd=d>Zd%S )ENativeFunctionr   	namespaceFunctionSchemafuncr   !use_const_ref_for_mutable_tensorsdevice_guardr  device_check
str | Nonepython_modulecategory_overridezset[Variant]variantsmanual_kernel_registrationmanual_cpp_bindingr   loczlist[OperatorName]autogenzdict[UfuncKey, UfuncInnerLoop]ufunc_inner_loop
structuredzOperatorName | Nonestructured_delegatestructured_inheritszPrecompute | Noneprecomputedset[str]cpp_no_default_argsis_abstract&has_composite_implicit_autograd_kernel4has_composite_implicit_autograd_nested_tensor_kernel&has_composite_explicit_autograd_kernel5has_composite_explicit_autograd_non_functional_kerneltagsNeidict[str, object]
valid_tagsignore_keysset[DispatchKey] | Noner   Mtuple[NativeFunction, dict[DispatchKey, dict[OperatorName, BackendMetadata]]]c           7        s	  |   }|d}t|tstd| tj|dd}|jdd}t	|j
 |dg }t|ts:td| t|}	|d	d
}
t|
tsPtd|
 |
rZ jjrZtd|dd}t|tsltd| t }|dD ]}|dkr|tj qt|dkr|tj qttd| |dd
}t|tstd| |dd
}t|tstd| |dd}t|tstd| |dd}|du st|tstd| |du s|tjv std| |du rtj}nt| }|dd
}t|tstd| |dd}|du s&t|ts&td| |dur4d|v r4tdd}|dur@t	|}|dd}|du sXt|tsXtd| |durfd|v rftd |d!d}|du s~t|ts~td| |durtj|v rtd"|d#d}|du st|tstd| |d$d}|dur|durtd%| |rt	|nd}|d&g }t|tr|g}t|tstd'| |dkrd(|v r|d( t }|D ]}t|d)krtd*||v r|| qtd+| d)d,lm} |d-d}|du s4t|ts4td.| i } d)}!|dur
|rDtd/d
}"| D ]\}#}|#d0krUqJt|#tsetd1|# d2| t|tsutd3| d2| |#d4D ]V}$t 	|$! }%|!d7 }!|r|%|v rqz|%t"vrtd5|% d6| d7tj|d8d9}|jd:d}&t#|j
|ot$|%|&d; d<| |%< |%t j%u r||& krd}"qzqJ|!dkr|"rtd=|s	| ' t j%hks	| t j% ( s	|!dks	td>|&  d?| t j%  d@n:|sD|du rDt j&j&}'|')dAs/|'*dBs/ jj+r7 j, s7tdC|' dDt#|& d
t-dE| t j%< dFdG | D }(t|(dksit|(dHkret j.|(vret j/|(v sitdI|dJdK})t|)ts|tdL|) |)dKkrg n	dMdG |)dD }*|dNi }+i },t|+trt0	|+t1j2|,t1j2< nFt|+tr|+ D ]3\}$}-|$d0krqt|$tstdO|$ t|-tstdP|- t1	|$}.t0	|-|.|,|.< qntdQ|+ |,r|stdRd)dl3m4  m5}/ t6D ]}%|%| v rtdS|% t#|/7 |%dt-d<| |%< q|r$d}0n| ' t j%hko?| ' t j/hko?| ' t j%t j/hk}0t j%| v }1t j/| v }2t j8| v }3t j.| v }4 fdTdU|  D }5|d0d |rotdV| |durt9D ]}6|6| v rtdW|6 dXqvt:d`i d d	|
d|d|d|d|d$|dJ|*dN|,d|d|d!|d#|d|d|dY|d|	dZ|0d[|1d\|2d]|3d^|4d&|d_||5fS )azp
        Parse a NativeFunction from a dictionary as directly parsed
        from native_functions.yaml
        r$  znot a str: r  )namespaced_entity	max_levelaten)defaultr6  z#cpp_no_default_args is not a list: r%  Fz1use_const_ref_for_mutable_tensors is not a bool: z4see https://github.com/pytorch/pytorch/issues/145522r+  r    zvariants is not a str: r   r!   zillegal variant r,  znot a bool: r-  r&  Tr'  Nzillegal device_check: r1  r2  ::zbnamespace is not supported in structured delegate, using the same namespace as the native functionr3  zbnamespace is not supported in structured inherits, using the same namespace as the native functionr)  z&functions in modules cannot be methodsr*  r4  z5precomputed requires structured=True, got structured=r<  ztags is not a list: pt2_compliant_tagr   zvalid_tags is emptyzillegal tag )cppdispatchzdispatch is not a dict: zncannot specify both manual_kernel_registration and dispatch; with manual registration, dispatch has no effect!__line__zillegal dispatch key 'z' in zillegal dispatch value ',zDispatch key z of kernel z! is not a supported dispatch key.   )rD  atz::native)kernelr1  cpp_namespacezSunnecessary dispatch table for this function; just delete the dispatch key entirelyzQunexpected name for singleton CompositeImplicitAutograd dispatch entry: expected z	 but got zR.  Rename your implementation to the expected name, then delete the dispatch tablenew__likez	expected z to have a CompositeExplicitAutograd dispatch entry, but there was no dispatch table.  Factory functions should not have implicit dispatch as they should not be decomposed for __torch_dispatch__)r1  rP  c                 S  s8   g | ]}|t jks|t jks|t jks|t jkr|qS r   r   )r8   dr   r   r   r:   c  s    



z,NativeFunction.from_yaml.<locals>.<listcomp>   aH  cannot specify more than one of CompositeExplicitAutograd, CompositeExplicitAutogradNonFunctional, or CompositeImplicitAutograd on a single kernel; each strictly subsumes the other.  If you wanted to provide an explicit autograd implementation, specify CompositeExplicitAutograd; otherwise specify CompositeImplicitAutograd onlyr/  r1   zautogen is not a str: c                 S  s   g | ]}t |qS r   )OperatorNamerM   r8   xr   r   r   r:         r0  z#ufunc_inner_loop key is not a str: z%ufunc_inner_loop value is not a str: z"ufunc_inner_loop not str or dict: zufunc must be structuredz2ufunc should not have explicit dispatch entry for c                   s   i | ]
\}}| j |iqS r   r@   )r8   rK   rL   r$  r   r   
<dictcomp>      z,NativeFunction.from_yaml.<locals>.<dictcomp>zleftover entries: z+if structured_delegate, then must not have z* in dispatch dictionary (it is delegated!)r.  r7  r8  r9  r:  r;  r"  r   );copypop
isinstancer   rI   r   from_namespaced_entityget_cpp_namespacer#  rM   entity_namelistsetr   	argumentsoutr   r   r   r    r!   r  rG   r  rU  
Precomputeappendlentorchgen.apirI  dictrH   r=   stripdispatch_keysBackendMetadatar   rw   rA   keyssupports_symint
startswithendswithtensor_optionshas_tensor_argDEFAULT_KERNEL_NAMESPACErz   rx   UfuncInnerLoopr  r  torchgen.api.ufuncapiufuncr   schema_kernel_namery   r   r!  )7r=  r.  r?  r@  efuncsnamespace_helperr"  cpp_no_default_args_listr6  r%  
variants_sr+  rL   r,  r-  r&  device_check_sr'  r1  structured_delegate_sr2  r3  r)  r*  precomputed_dictr4  tags_inpr<  trI  raw_dispatchrJ  num_dispatch_keys%redundant_composite_implicit_autogradksrK   dispatch_keykernel_namespacerA   composites_in_dispatchautogen_strr/  raw_ufunc_inner_loopr0  vo	ufunc_keyrx  r7  r8  r9  r:  r;  backend_metadatakeyr   rY  r   	from_yamlo  s~  















#
	










	
zNativeFunction.from_yamlNonec                 C  s    | j rtd| jstdd S )NzMThis function is structured, but there was no valid functional variant of it.zThis function delegates to another structured out function, but no valid function was found (the delegate may not exist, or it has the wrong type))r1  rI   r2  r   r   r   r   validate_unstructured  s   z$NativeFunction.validate_unstructuredc                 C  s  | j jjr| jtjhkrtd| jr&| j  t	jkrtd| j
s&td| jr<| j  t	jkr5td| j
s<td| jrF| jrFtddd | j  D }t| j|}t|dkrdtd	| | jd urp| jsptd
t| j jdr| jtjkrtddt| j jv sdt| j jv stdd | j jjD rdt| j jvrt| j jjdks| j j rd| jvrtd| j j d S d S )NzNative functions with out arguments MUST be declared with only function variant; e.g., variants: function; otherwise you will tickle a Python argument binding bug (which usually manifests itself as the result variable being undefined.)zYPut structured field on the out= variant of a function; did you mean structured_delegate?z:device_guard: False is not respected by structured kernelszQstructured_delegate field not allowed on out= functions; did you mean structured?z?Cannot have both structured and structured_delegate on functionc                 S  s   h | ]
}|j d ur|jqS r?   )rF  rA   r8   ar   r   r   	<setcomp>9  s    z/NativeFunction.__post_init__.<locals>.<setcomp>r   zInvalid cpp_no_default_args: z4structured_inherits must also imply structured: True_foreachzsforeach kernels fall back to slow path when tensor are on different devices, device_check not allowed to be enabledranddropoutc                 s  s    | ]}d |j v V  qdS )r  Nr@   r8   argr   r   r   r   R  s    

z/NativeFunction.__post_init__.<locals>.<genexpr>backward_cudnn_init_dropout_statenondeterministic_seededz(nondeterministic_seeded tag missing for )r$  rd  re  r+  r   r    rI   r1  kind
SchemaKindr&  r2  schema_order_argumentsrc  
differencer6  rh  r3  r   rA   rp  r'  r  r  anyflat_allhas_generator_argr<  )r   defaulted_argumentsinvalid_argsr   r   r   __post_init__  sv   



zNativeFunction.__post_init__c                 C  s   | j p| jp| jp| j o| jS r?   )r8  r:  r;  r9  r   r   r   r   has_composite_kernela  s   z#NativeFunction.has_composite_kernelc                 C  st   | j j}t|dkotdd |D }d| jv o't| j jdko't| j jdk}tdd | j  D }|p9|p9|S )Nr   c                 s  s$    | ]}|j d uo|j j V  qd S r?   
annotationis_writer8   r   r   r   r   r   o  s    
z,NativeFunction.is_view_op.<locals>.<genexpr>inplace_viewresize_
resize_as_c                 s  s&    | ]}|j d uod|j jv V  qd S )N*)r  alias_set_after)r8   inpr   r   r   r   x  s
    
)r$  returnsrh  r  r<  r   rA   r  )r   retsis_non_mutating_viewis_inplace_viewis_wildcard_viewr   r   r   
is_view_opl  s   
zNativeFunction.is_view_opr  c                 C  sF   | j r| jjjjrd| jvrtd| jj tjS | j r tjS tj	S )Nr  zinplace_view tag missing for )
r  r$  rA   inplacer<  rI   r  r  r  r   r   r   r   r   view_schema_kind~  s   
zNativeFunction.view_schema_kindc                 C  s   | j jjjS r?   )r$  rA   baser   r   r   r   	root_name  s   zNativeFunction.root_namec                 C  s   | j p| jd uS r?   )r1  r2  r   r   r   r   part_of_structured_group     z'NativeFunction.part_of_structured_groupr?   )
r=  r>  r.  r   r?  r5  r@  rA  r   rB  r   r  r   r   )r   r  r   )r   r   r   r   r   r  r  r  propertyr  r  r  r  r  r   r   r   r   r!    sV   
 	
   

K

r!  c                   @  s*   e Zd Ze Ze Ze Ze Ze ZdS )r  N)	r   r   r   r   
functionalr  re  mutablescratchr   r   r   r   r    s    
r  c                   @  sv   e Zd ZU ded< ded< ded< ded< edd	d
ZdddZdddZd ddZed!ddZ	e
d"ddZdS )#NativeFunctionsGroupr!  r  NativeFunction | Noner  r  re  r   r   c                 C     | j jS r?   )re  r1  r   r   r   r   r1    s   zNativeFunctionsGroup.structuredr  c                 C  sB  | j j }|  D ]+}||j kr td| d|j  | j|jkr5td| jjj d|jj q
| j j	 t
j krKtd| j j	  d| jj	 t
jkr`td| jj	  d| j j| jjkrwtd	| j j d
| jj d| jd ur| jj	 t
jkrtd| jj	  d| jj| j jkrtd| jj d| j j d| jd ur| jj	 t
jkrtd| jj	  d| jj| j jkrtd| jj d| j j d| j jjjjstd| jr6| jjs| jjrtd| j j| jjjkrt| j jj d| j j d| jjj | jd ur6| jj| jjjkr6t| jjj d| jj d| jjj tdd |  D }ddd |D }t }|  D ]}|dd |jD  qRddd t|D }t|dkrt|dkrtd| d | d!t|jj ||krtd| d"| d#| d$d S )%Nz_NativeFunctionsGroup constructed from two NativeFunctions that don't have matching signatures:  != zMNativeFunctionsGroup constructed from structured and unstructured functions:  and zfunctional.func.kind() is z , expected SchemaKind.functionalzout.func.kind() is z, expected SchemaKind.outzfunctional.namespace (z) != out.namespace ()zinplace.func.kind() is z, expected SchemaKind.inplacezinplace.namespace (z) != functional.namespace (zmutable.func.kind() is z, expected SchemaKind.mutablezmutable.namespace (zSfunctional.func.name.name.functional_overload must be True when mutable is not Nonez.structured composite kernels are not supportedz delegates to z but its actual delegate is c                 S  s"   g | ]}d |j v rt|jjqS )	generated)r<  r   r$  rA   )r8   fr   r   r   r:     s   " z6NativeFunctionsGroup.__post_init__.<locals>.<listcomp>r   c                 s      | ]}t |V  qd S r?   r   rV  r   r   r   r         z5NativeFunctionsGroup.__post_init__.<locals>.<genexpr>c                 s  r  r?   r  )r8   opr   r   r   r     r  c                 s  r  r?   r  rV  r   r   r   r     s    
r   z,The codegen expects to be able to generate 'zv'. In order to generate them however, we expect them to be called out explicitly in the yaml. Please add an 'autogen: z' line to the entry for z*'. To do so, it expects a line: 'autogen: z'. Instead, it found 'autogen: ')r  r$  	signature	functionsrI   r1  r  re  rA   r  r  r"  r  r  functional_overloadr8  r9  r2  sortedr   rc  r   r/  rh  RuntimeErrorr   )r   test_sigr  generated_fnsgenerated_fns_strexpected_generated_fnsexpected_generated_fns_strr   r   r   r    s   




z"NativeFunctionsGroup.__post_init__r#  c                 C  s   | j j S r?   )re  r$  r  r   r   r   r   r    rD   zNativeFunctionsGroup.signatureIterator[NativeFunction]c                 c  s>    | j V  | jV  | jd ur| jV  | jd ur| jV  d S d S r?   )r  re  r  r  r   r   r   r   r    s   

zNativeFunctionsGroup.functionsr   c                 C  r  r?   )r  r  r   r   r   r   r    r   zNativeFunctionsGroup.root_namerS   dict[SchemaKind, NativeFunction]NativeFunctionsGroup | Nonec                 C  s   | st dt| dkrd S t| } | tjd }| tjd }| tjd }| tjd }| r7t d|  |d u r?t d|d u rEd S t	||||dS )Nz from_dict called with empty dictr  zunexpected keys in dict: zfunctional variant is required)r  r  r  re  )
rI   rh  rj  r]  r  r  r  r  re  r  )rS  r  r  r  re  r   r   r   	from_dict  s*   zNativeFunctionsGroup.from_dictNr  r  r   r#  )r   r  r   )rS  r  r   r  )r   r   r   r   r  r1  r  r  r  r  r   r  r   r   r   r   r    s   
 

_
r  c                   @  s0   e Zd ZU ded< ded< ded< d
ddZd	S )rm  r   rO  r   r1  rP  r   c                 C  s
   d| j v S )N_symint)rO  r   r   r   r   ro  I     
zBackendMetadata.supports_symintNr  )r   r   r   r   ro  r   r   r   r   rm  6  s
   
 	rm  c                   @  s4   e Zd ZU ded< ded< ded< edd	d
ZdS )ru  r   rA   r   supported_dtypesr  r  rE   r   c                 C  s~   |  dd\}}|d dkrtd| |d dkr"td| t }|dd  d	D ]	}|t|O }q.t|||d
S )N r  r   (z0expected '(' at start of supported_dtypes, got: r  z.expected ')' at end of supported_dtypes, got: r   )rA   r  r  )r   rI   r	   r   r   ru  )rE   r  rA   supported_dtypes_strr  rK   r   r   r   rM   U  s   zUfuncInnerLoop.parseN)rE   r   r  r  r   ru  )r   r   r   r   r   rM   r   r   r   r   ru  M  s   
 ru  c                   @  sl   e Zd ZU ded< ded< ded< ded< ded< edddZd ddZd!ddZd"ddZd#ddZ	dS )$BackendIndexr=   r  r   use_out_as_primaryr&  externalz#dict[OperatorName, BackendMetadata]indexparent_index6dict[DispatchKey, dict[OperatorName, BackendMetadata]]child_indexr   r  c                 C  sT   |  D ]#\}}|  D ]\}}|| | v r td| d| || | |< qqd S )Nzduplicate operator z for dispatch key )rH   rI   )r  r  rK   rL   op_namemetadatar   r   r   
grow_index~  s   zBackendIndex.grow_indexgr  r!  c                 C  s   | j r|jS |jS r?   )r  re  r  )r   r  r   r   r   primary  s   zBackendIndex.primary%NativeFunction | NativeFunctionsGroupc                 C  s   |  |}|d uS r?   )
get_kernel)r   r  mr   r   r   
has_kernel  s   
zBackendIndex.has_kernelBackendMetadata | Nonec                 C  sN   t |tr|}nt |tr| |}nt| |jj| jvr d S | j|jj S r?   )r^  r!  r  r  r   r$  rA   r  )r   r  r  r   r   r   r    s   

zBackendIndex.get_kernelr(  c                 C  s   | j rt| j dS d S )NNativeFunctions)r  r   r  r   r   r   r   native_function_class_name  s   z'BackendIndex.native_function_class_nameN)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   r  r  r  r  r  r   r   r   r   r  o  s   
 


r  c                   @  s   e Zd ZU ded< ded< ded< ed4d	d
Zd5ddZedZ	e
d6ddZd4ddZd7ddZd4ddZd4ddZd8ddZd9d d!Zd"d"d"d#d:d'd(Zd;d)d*Zd<d+d,Zed4d-d.Zd4d/d0Zd=d1d2Zd3S )>r#  rU  rA   	Argumentsrd  tuple[Return, ...]r  r   r   c                   s$   d	dd t  fdd| jjD S )
Nr  Argumentr   r   c                 S  s   | j d u rdS | j jS NFr  )r  r   r   r   r    s   
z+FunctionSchema.is_mutable.<locals>.is_writec                 3  s    | ]} |V  qd S r?   r   r  r  r   r   r     r  z,FunctionSchema.is_mutable.<locals>.<genexpr>)r  r  r   r   )r  rd  r  r   r   r   r   
is_mutable  s   
zFunctionSchema.is_mutableIterator[Argument]c                 C  s   t | jj| jj| jjS r?   )	itertoolschainrd  flat_positionalflat_kwarg_onlyre  r   r   r   r   r    s
   z%FunctionSchema.schema_order_argumentsz3(?P<name>[^\(]+)\((?P<args>.*)\) -> (?P<returns>.*)r$  r   c           	      C  s   t j| }t|dkrtd|  |d \}}}t|}t|}t|}t |||d}t	|| kr@tt	| d|  |S )Nr  zInvalid function schema: r   rA   rd  r  r  )
r#  decl_refindallrh  rI   rU  rM   r  parse_returnsr   )	r$  declsopsargsreturn_declrA   rd  r  r   r   r   r   rM     s   

zFunctionSchema.parsec                 C     t dd | jD S )Nc                 s  s&    | ]}|j d ur|j jr|V  qd S r?   r  r  r   r   r   r     s    z5FunctionSchema.returns_are_aliased.<locals>.<genexpr>)r  r  r   r   r   r   returns_are_aliased  s   z"FunctionSchema.returns_are_aliasedr  c                   s  t | jj| jD ]\}|jjkrtd|j dj q| jjD ] t fdd| jD r:tdt|  q#t	| jjdd | jj
D  }dd | jD }d	d | jD }t|d
ksot|d
ksotdt|  |D ]tfdd|D stdqq| jjrtdd | jjD rt| jd
krtdn tdd | jjD }|t| jkrtd| dt| j d| jjjr| jj}|r|jjr|jjjstd| j d|jjttjkrt| jdkr| jd
 j|jjkstd| j dnt| jd
krtd| j d| jjd ur+|  tjkr+tdt|  |  rA|  tjkrCtdt|  d S d S )NzOut arguments must have matching return Tensor; furthermore, the ith-argument needs to correspond to the ith return. arg.annotation=z, ret.annotation=c                 3      | ]	} j |j kV  qd S r?   r  r  r  r   r   r   !      z/FunctionSchema.__post_init__.<locals>.<genexpr>z^If you have a schema with mutable positional args, we expect them to not be returned. schema: c                 S  s   g | ]	}|j d kr|qS r   r@   r  r   r   r   r:   )  s    z0FunctionSchema.__post_init__.<locals>.<listcomp>c                 S  "   g | ]}|j d ur|j jr|qS r?   r  r8   retr   r   r   r:   ,  
    c                 S  s"   g | ]}|j d u s|j js|qS r?   r  r  r   r   r   r:   1  r  r   zYNativeFunctions must have either only mutable returns, or only immutable returns. Found: c                 3  r  r?   r  r  )r  r   r   r   @  r  zAll mutable returns must be aliased either to a keyword argument, or to "self". Did you forget to mark an out argument as keyword-only?c                 s  s     | ]}|j ttjkV  qd S r?   )typeBaseTypeBaseTyTensorr  r   r   r   r   K  r   zout= ops that accept tensor lists as out arguments are expected to have no return type (since you can't do method chaining on them)c                 S  s   g | ]
}|j d s|qS 	_scratch_rA   rp  r  r   r   r   r:   U  s    
zSMust return as many arguments as there are out arguments, or no return at all. Got z non-scratch out args and z returnszInplace op z4 must have a self argument with a mutable annotationr  z" with Tensor self must return selfz* with non-Tensor self must have no returnszFound an operator that is not functional or out variant, but has tensor options arguments.This is not allowed- tensor options arguments are only allowed for factory functions.schema: zFound an operator that is not functional, but its overload contains the string 'functional'.This is a special keyword in the codegen, please use a different overload name.schema: )ziprd  re  r  r  rI   post_self_positional_mutabler  r   rb  r  rh  rA   r  self_argargumentr  r  r  r  r  rr  r  r  r  is_functional_fn)r   r  out_and_selfmutable_returnsimmutable_returnsnon_scratch_out_argsself_ar   )r  r  r   r    s   

zFunctionSchema.__post_init__c                 C  s   d| j jv S )Nr  rA   overload_namer   r   r   r   r$    rD   zFunctionSchema.is_functional_fnc                 C  s   t | jjS r?   )r   rd  re  r   r   r   r   	is_out_fn  s   zFunctionSchema.is_out_fnr  c                 C  s   t | jj}t dd | jjD }| jjj}tdd | jjD }|r)|r)td|r.tjS |r9|s6tdtj	S |rD|rAtdtjS |rItj
S tjS )a	  
        What kind of schema is this?  A functional schema is one
        that returns a newly allocated output; an inplace schema
        modifies the self argument inplace; an out schema writes
        the result into an explicitly provided out argument.
        c                 S  s   g | ]
}|j d r|qS r  r  r  r   r   r   r:     r[  z'FunctionSchema.kind.<locals>.<listcomp>c                 s  s"    | ]}|j d uo|j jV  qd S r?   r  r  r   r   r   r     s
    
z&FunctionSchema.kind.<locals>.<genexpr>z(A schema cannot be both out= and inplacezFinvariant: all scratch operators are expected to be out= operators toozjWe should not categorize a scratch op as an out variant. Check if the order of if statements are expected!)r   rd  re  rA   r  r  post_self_positionalrI   r  r  r  r  )r   is_out
is_scratch
is_inplacer  r   r   r   r    s6   
zFunctionSchema.kindlist[str | None]c                   s   g }| j D ]=  fdd| jjD }t|dkr|d  qt|dkr-||d j qddd |D }td j d	| d
|S )Nc                   s&   g | ]}|j d ur|j  j kr|qS r?   r  r  r   r   r   r:     s
    z7FunctionSchema.aliased_return_names.<locals>.<listcomp>r   r  r   c                 s  s    | ]}|j V  qd S r?   r@   r  r   r   r   r     s    z6FunctionSchema.aliased_return_names.<locals>.<genexpr>zFound a return (z)that aliases multiple inputs (r  )r  rd  r  rh  rg  rA   r   rI   )r   outsaliased_argsaliased_namesr   r   r   aliased_return_names  s   

z#FunctionSchema.aliased_return_namesF)strip_defaultstrip_view_copy_namekeep_return_namesr6  r7  r8  c          
        s   d fdd}j j j}|r%|dr|dd}n|dr%|d	d
}t fddtjjdur:jjj	gng jj
jjD }tt|j}|| }jj|d}	tj dkrktt|	dd}	ttt|dj j jddd|	|dS )a
  
                Certain schemas are 'related', in that they are simply
                inplace/out/functional versions of the same function.  This method
                factors these schemas into the "core" functional signature which
                is equal across all versions.

                Here is what normalization happens to the schema to convert
                it to a signature:
                - The overload name is stripped (name is retained, since
                  it expresses semantic content about what the function does)
                - Inplace is set False
                - Out arguments are stripped
                - Mutable post_self_positional args are converted to returns
                - Mutability annotations are stripped  (this is sound
                  because you cannot overload on mutability annotation)
                - Return names are stripped since they are not overloadable and
                  some variants have return names but some not
                - TensorOptions are dropped
                  because out= variants of factory functions don't include them
                  (and we want to be able to pair up factory functions with their out variants)

                Finally, we want to be able to pair up related "view" and their
                corresponding "view_copy" operators. We do this by optionally
                stripping the trailing "_copy" from the base name.

                Example of a mutable op before and after:

                f.func (Mutable operator):
        _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor(a!) running_min, Tensor(b!) running_max, Tensor(c!) scale, Tensor(d!) zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask)  # noqa: B950

                f.func (Corresponding functional operator):
        _fused_moving_avg_obs_fq_helper.functional(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor output, Tensor mask, Tensor running_min_out, Tensor running_max_out, Tensor scale_out, Tensor zero_point_out)  # noqa: B950

                f.func.signature() output:
        _fused_moving_avg_obs_fq_helper(Tensor self, Tensor observer_on, Tensor fake_quant_on, Tensor running_min, Tensor running_max, Tensor scale, Tensor zero_point, float averaging_const, int quant_min, int quant_max, int ch_axis, bool per_row_fake_quant=False, bool symmetric_quant=False) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)  # noqa: B950
        r   Returnr   c                   s   t  r| jnd | jd dS )NrA   r  r  )r9  rA   r  r   )r8  r   r   strip_ret_annotation  s
   z6FunctionSchema.signature.<locals>.strip_ret_annotation_copyr1   _scatterscatterinversec                 3  sZ    | ](  j d ur j jrt fddjD str" j dnd  jd dV  qd S )Nc                 3  r  r?   r  r  r  r   r   r   @  r  z5FunctionSchema.signature.<locals>.<genexpr>.<genexpr>_outr:  )r  r  r  r  r9  rA   r  )r8   r8  r   r  r   r   *  s    	
z+FunctionSchema.signature.<locals>.<genexpr>Nr6  zbernoulli.pzfloat pzfloat p=0.5Fr  r  dunder_methodr*  r  )r   r9  r   r9  )rA   r  rq  replacetupler  r  rd  r"  r#  re  r-  mapr  r  r   r  rM   r#  rU  BaseOperatorNamerD  )
r   r6  r7  r8  r;  	base_namereturns_from_mutable_inputsoriginal_returnsr  args_sigr   rA  r   r    sB   ,


	zFunctionSchema.signaturec                 C  s   | j ddS )NTr7  )r  r   r   r   r   view_signatureX  rD   zFunctionSchema.view_signaturec                 C  s   t || j| jdS )Nr  )r#  rd  r  )r   rA   r   r   r   	with_name[  s
   zFunctionSchema.with_namec                 C  s   |   tjtjtjfv S r?   )r  r  r  re  r  r   r   r   r   modifies_argumentsb  s   z!FunctionSchema.modifies_argumentsc                 C  
   | j  S r?   )rd  has_symint_argr   r   r   r   
has_symintf  r  zFunctionSchema.has_symintc                 C  sX   t | j}t| jdkrt | jd }nddtt | j d }| j d| d| S )Nr  r   r  r   r  z) -> )r   rd  rh  r  r   rG  rA   )r   all_arguments_strr  r   r   r   r   i  s
   
zFunctionSchema.__str__Nr  )r   r  )r$  r   r   r#  r  )r   r  )r   r1  )r6  r   r7  r   r8  r   r   r#  r  )rA   rU  r   r#  r   )r   r   r   r   r  r  r  recompiler  r   rM   r  r  r$  r,  r  r5  r  rN  rO  rP  rS  r   r   r   r   r   r#    s4   
 





v


0
i

r#  c                   @  s>   e Zd ZU ded< ded< ded< edd	d
ZdddZdS )
Annotationztuple[str, ...]	alias_setr   r  r  annr   r   c                 C  s   t d| }|d u rtd|  |d|dr|dnd }t|d}|ddk}|r@t|dkr@td	|  d
|drOt|ddnd}t|dkret|dkretd|  d
t|||d}t|| kr{t| d|  |S )Nz2^([a-z])(\|[a-z])*(!?)( -> (\*|[a-z](\|[a-z])*))?$zunrecognized alias annotation r  rT  r1   |rM  !z,alias set larger than 1 is not mutable, got z	 instead.   r   zSbefore alias set and after alias set cannot be larger than 1 at the same time, got )rX  r  r  r  )	rU  matchrI   grouprF  r   rh  rW  r   )rY  r  before_aliasrX  r  	after_setr   r   r   r   rM     s*   "
"
zAnnotation.parsec                 C  s>   d | j}| jr| d}d | j}|r| d| }|S )NrZ  r[   -> )r   rX  r  r  )r   rX  r  r   r   r   r     s   
zAnnotation.__str__N)rY  r   r   rW  r   )r   r   r   r   r   rM   r   r   r   r   r   rW  z  s   
 &rW  c                   @  sn   e Zd ZedddZedddZddd	ZdddZdddZdddZ	dddZ
dddZdddZdS ) Typer  r   r   c                 C  s,   t | }t|| krt| d|  |S )Nr  )rb  _parser   rI   )r  r   r   r   r   rM     s   
z
Type.parsec              
   C  s   t d| }|d urtt|dS t d| }|d ur:|dd ur,t|dnd }tt|d|dS t d| }|d urKt|dS zt	t
|  W S  tyf } ztd|  |d }~ww )Nz^(.+)\?$r  z^(.+)\[([0-9]+)?\]$rT  )elemsizez-^__torch__\.torch\.classes\.([a-zA-Z0-9_.]+)$zunrecognized type )rU  r]  OptionalTyperb  rM   r^  r   ListTypeCustomClassTyper  r  KeyErrorr  )r  r  re  rz  r   r   r   rc    s     zType._parsec                 C     t r?   NotImplementedErrorr   r   r   r   r        zType.__str__base_tyr  r   c                 C  rj  r?   rk  r   rn  r   r   r   is_base_ty_like  rm  zType.is_base_ty_likec                 C     |  tjS r?   )rp  r  r  r   r   r   r   is_tensor_like  rD   zType.is_tensor_likec                 C  rq  r?   )rp  r  	Generatorr   r   r   r   is_generator_like  rD   zType.is_generator_likec                 C  rq  r?   )rp  r  SymIntr   r   r   r   is_symint_like  rD   zType.is_symint_likec                 C  rj  r?   rk  r   r   r   r   is_nullable  rm  zType.is_nullableListType | Nonec                 C  rj  r?   rk  r   r   r   r   is_list_like  rm  zType.is_list_likeN)r  r   r   rb  r   rn  r  r   r   r  r   rx  )r   r   r   r   rM   rc  r   rp  rr  rt  rv  rw  ry  r   r   r   r   rb    s    





rb  c                   @  s   e Zd Ze Ze Ze Ze Ze Ze Z	e Z
e Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze Ze ZdS )r  N)r   r   r   r   rs  r   r  r   Dimname	DimVectorfloatr   r   LayoutDeviceDeviceIndexScalarMemoryFormatQSchemeStorageStreamru  SymBoolGraphModuler   r   r   r   r    s*    
r  c                   @  sH   e Zd ZU ded< dddZdd	d
ZdddZdddZdddZdS )r  r  rA   r   r   c                 C  s
   | j j  S r?   r@   r   r   r   r   r     r  zBaseType.__str__rn  r   c                 C  s
   | j |kS r?   r@   ro  r   r   r   rp    r  zBaseType.is_base_ty_likec                 C     dS r  r   r   r   r   r   rw    rm  zBaseType.is_nullablerx  c                 C     d S r?   r   r   r   r   r   ry    rm  zBaseType.is_list_likec                 C  s   | j tjkS r?   )rA   r  ru  r   r   r   r   rv    rD   zBaseType.is_symint_likeNr   rz  r  r{  )	r   r   r   r   r   rp  rw  ry  rv  r   r   r   r   r       
 



r  c                   @  sH   e Zd ZU ded< dddZdd
dZdddZdddZdddZdS )rf  rb  rd  r   r   c                 C  s   | j  dS )N?)rd  r   r   r   r   r   !  rD   zOptionalType.__str__rn  r  r   c                 C     | j |S r?   rd  rp  ro  r   r   r   rp  $  rD   zOptionalType.is_base_ty_likec                 C  rQ  r?   rd  rv  r   r   r   r   rv  '  r  zOptionalType.is_symint_likec                 C  r  )NTr   r   r   r   r   rw  *  rm  zOptionalType.is_nullablerx  c                 C  rQ  r?   )rd  ry  r   r   r   r   ry  -  r  zOptionalType.is_list_likeNr   rz  r  r{  	r   r   r   r   r   rp  rv  rw  ry  r   r   r   r   rf    r  rf  c                   @  sH   e Zd ZU ded< dddZdd	d
ZdddZdddZdddZdS )rh  r   
class_namer   c                 C  s   d| j  S )zK
        Return the class name will prefix __torch__.torch.classes
        z__torch__.torch.classes.)r  r   r   r   r   r   6  s   zCustomClassType.__str__rn  r  r   c                 C  r  r  r   ro  r   r   r   rp  <  rm  zCustomClassType.is_base_ty_likec                 C  r  r  r   r   r   r   r   rv  ?  rm  zCustomClassType.is_symint_likec                 C  r  )z8
        Assume a custom class is not nullable.
        Fr   r   r   r   r   rw  B  s   zCustomClassType.is_nullablerx  c                 C  r  r?   r   r   r   r   r   ry  H  rm  zCustomClassType.is_list_likeNr   rz  r  r{  r  r   r   r   r   rh  2  s   
 



rh  c                   @  sP   e Zd ZU ded< ded< dddZdddZdddZdddZdddZdS )rg  rb  rd  z
int | Nonere  r   r   c                 C  s$   | j r| j  nd}| j d| dS )Nr1   [])re  rd  )r   re  r   r   r   r   X  s   zListType.__str__rn  r  r   c                 C  r  r?   r  ro  r   r   r   rp  \  rD   zListType.is_base_ty_likec                 C  rQ  r?   r  r   r   r   r   rv  _  r  zListType.is_symint_likec                 C  rQ  r?   )rd  rw  r   r   r   r   rw  b  r  zListType.is_nullablerx  c                 C  s   | S r?   r   r   r   r   r   ry  e  rm  zListType.is_list_likeNr   rz  r  r{  r  r   r   r   r   rg  S  s   
 



rg  c                   @  sb   e Zd ZU ded< ded< ded< ded< edd
dZedddZedddZdddZ	dS )r  r   rA   rb  r  r(  rF  Annotation | Noner  r   c                 C  r>   r?   r  r   r   r   r   
alias_info     zArgument.alias_infor  c                 C  s  d| vrt d|  dd| v r6| ddkrt d|  d| d\}}|dd\}}| d| }n| dd\}}|}d }td|}|rk|dd	vr[t d
|d d|d }t|d}n|}d }t	|}	t
||	||d}
t|
| krt t|
 d|  |
S )Nr  zillegal argument 'r  =r  z&illegal argument with default value: 'Tensor\((.+)\)(.*)rT  r1   r  z[].unrecognized alias analysis form with Tensor: r  rA   r  rF  r  r  )rI   countr   rsplitrU  r]  r^  rW  rM   rb  r  r   )r  type_and_annot_and_namerF  type_and_annotrA   name_and_defaultr]  type_sr  r  r   r   r   r   rM     s>   
zArgument.parser   c                 C     | j d uo| j jS r?   r  r   r   r   r   r       zArgument.is_writec                 C  sr   | j  }| jr|dvrtd| |dd| j d}| jd u r$|S d}| jr/d| j }| d| j | S )	Nr  zTensor?zTensor[]annotation on non-Tensor type: r  Tensor(r  r1   r  r  )r  r  rI   rE  rA   rF  )r   r  
mb_defaultr   r   r   r     s   
zArgument.__str__Nr   r  )r  r   r   r  r  r   
r   r   r   r   r  r  r   rM   r  r   r   r   r   r   r  i  s   
 (r  c                   @  sZ   e Zd ZU ded< ded< ded< eddd	ZedddZedddZdddZ	dS )r9  r(  rA   rb  r  r  r  r   c                 C  r>   r?   r  r   r   r   r   r    r  zReturn.alias_infor  r   c                 C  s   d| v r|  dd\}}n| }d }td|}|r:|ddvr*td|d d|d }t|d}n|}d }t|}t|||d}t	|| kr[tt	| d	|  |S )
Nr  r  r  rT  r  r  r  r:  r  )
r  rU  r]  r^  rI   rW  rM   rb  r9  r   )r  r  rA   r]  r  r  r  r   r   r   r   rM     s.   
zReturn.parser   c                 C  r  r?   r  r   r   r   r   r    r  zReturn.is_writec                 C  sX   | j  }| jr|dvrtd| |dd| j d}| jd u r$|S | d| j S )Nr  r  r  r  r  r  )r  r  rI   rE  rA   )r   r  r   r   r   r     s   
zReturn.__str__Nr  )r  r   r   r9  r  r   r  r   r   r   r   r9    s   
 r9  c                   @  s   e Zd ZU ded< dS )SelfArgumentr  r#  N)r   r   r   r   r   r   r   r   r  	  s   
 r  c                   @  s8   e Zd ZU ded< ded< ded< ded< ddd	Zd
S )TensorOptionsArgumentsr  dtypelayoutdevice
pin_memoryr   Sequence[Argument]c                 C  s   | j | j| j| jgS r?   r  r  r  r  r   r   r   r   all	     zTensorOptionsArguments.allNr   r  )r   r   r   r   r  r   r   r   r   r  		  s   
 r  c                   @  s@  e Zd ZU ded< ded< ded< ded< ded< ded	< ded
< edDddZedDddZedDddZedDddZedDddZ	edEddZ
edFddZedGddZedEd d!ZdHd#d$ZdId&d'ZdId(d)ZdId*d+Zd,d-dJd/d0ZdKd1d2ZdLd5d6ZedMd:d;ZedNd<d=ZdOd>d?ZdPdAdBZdCS )Qr  ztuple[Argument, ...]pre_self_positionalzSelfArgument | Noner"  r-  pre_tensor_options_kwarg_onlyzTensorOptionsArguments | Nonerr  post_tensor_options_kwarg_onlyre  r   r  c                 C      g }| | j | | j |S r?   )r   r  r  r   r  r   r   r   flat_non_out+	  s   zArguments.flat_non_outc                 C  s8   g }| | j | jd ur|| jj | | j |S r?   )r   r  r"  rg  r#  r-  r  r   r   r   r  2	  s   
zArguments.flat_positionalc                 C     dd | j D S )Nc                 S  s   g | ]}|j r|qS r   r   r  r   r   r   r:   =	  rX  z:Arguments.post_self_positional_mutable.<locals>.<listcomp>)r-  r   r   r   r   r!  ;	  r  z&Arguments.post_self_positional_mutablec                 C  s:   g }| | j | jd ur| | j  | | j |S r?   )r   r  rr  r  r  r  r   r   r   r  @	  s   
zArguments.flat_kwarg_onlyc                 C  ,   g }| | j | | j | | j |S r?   )r   r  r  re  r  r   r   r   r  I	  
   zArguments.flat_all:Sequence[Argument | SelfArgument | TensorOptionsArguments]c                 C  r  r?   )r   
positional
kwarg_onlyr  r   r   r   non_outQ	  s   zArguments.non_out!Sequence[Argument | SelfArgument]c                 C  6   g }| | j | jd ur|| j | | j |S r?   )r   r  r"  rg  r-  r  r   r   r   r  Z	     
zArguments.positional+Sequence[Argument | TensorOptionsArguments]c                 C  r  r?   )r   r  rr  rg  r  r  r   r   r   r  c	  r  zArguments.kwarg_onlyc                 C  r  r?   )r   r  r  re  r  r   r   r   r  l	  r  zArguments.all	list[str]c                 C  r  )Nc                 S  s$   g | ]}|j d ur|j jr|jqS r?   )r  r  rA   r  r   r   r   r:   u	  s
    z/Arguments.mutable_arg_names.<locals>.<listcomp>)r  r   r   r   r   mutable_arg_namest	  s   zArguments.mutable_arg_namesr   c                 C  r  )Nc                 s      | ]}|j  V  qd S r?   )r  rr  r  r   r   r   r   |	      z+Arguments.has_tensor_arg.<locals>.<genexpr>r  r  r   r   r   r   rs  {	  r  zArguments.has_tensor_argc                 C  r  )Nc                 s  r  r?   )r  rv  r  r   r   r   r   	  r  z+Arguments.has_symint_arg.<locals>.<genexpr>r  r   r   r   r   rR  ~	  r  zArguments.has_symint_argc                 C  r  )Nc                 s  r  r?   )r  rt  r  r   r   r   r   	  r  z.Arguments.has_generator_arg.<locals>.<genexpr>r  r   r   r   r   r  	  r  zArguments.has_generator_argFrB  r6  c             	     sr   d fdd}t tt|| j| jd urt|| jjnd tt|| jtt|| jtt|| j	 d dddS )	Nr  r  r   c                   s$   t | j| j s| jd dS d d dS )Nr  )r  rA   r  rF  r  rB  r   r   strip_arg_annotation	  s   z1Arguments.signature.<locals>.strip_arg_annotationr   r  r"  r-  r  rr  r  re  )r  r  r   r  )
r  rF  rG  r  r"  r  r#  r-  r  r  )r   r6  r  r   rB  r   r  	  s(   



zArguments.signaturec                 C  s2   | j d u r	tdtj| ttj| j jd ddS )Nz2remove_self_annotation called but self_arg is Noner  )r"  )r"  rI   dataclassesrE  r  r#  r   r   r   r   remove_self_annotation	  s   
z Arguments.remove_self_annotationr2  list[Argument]c                 C  s0   t | jdkrtd| j tj| t|dS )Nr   z0with_out_args called but self.out is not empty: )re  )rh  re  rI   r  rE  rF  )r   r2  r   r   r   with_out_args	  s   
zArguments.with_out_argsr  r   5tuple[list[Argument], list[Argument], list[Argument]]c                 C  s   g }g }g }|}|  dD ]@}|sq|dkr!||urtd|}qt|}|jd ur;|jjr;||u r4n||u r:|}n||u rHtd|j d|| q|||fS )Nr   r  z:invalid syntax: kwarg-only specifier * can only occur onceznon-mutable argument 'z%' cannot follow mutable out arguments)r   rI   r  rM   r  r  rA   rg  )r  r  r  re  arguments_accr  pargr   r   r   	_preparse	  s6   

zArguments._preparsec              	   C  s  t | \}}}d}t|D ]\}}|jdkr|} nq|dur5|d| }t|| }||d d }	ng }d}|}	g }
d}g }|
}dd
d}|dtd|dtd|dtd|dtdg}d}|t|k r|t|t| krtdd t	||||t|  D r||
urt
dt|| ||d  ||d  ||d  d}|t|7 }|}qh|||  |d7 }|t|k snt t||t|	t|
|t|t|dS )z.
        Input: 'int x, int y, int z'
        Nr   r  rA   r   tyrb  r   Callable[[Argument], bool]c                   s    fddS )Nc                   s   | j  ko| jtfv S r?   )rA   r  rf  r  rA   r  r   r   <lambda>
  r[  z/Arguments.parse.<locals>.pred.<locals>.<lambda>r   r  r   r  r   pred

  s   zArguments.parse.<locals>.predr  r   r  r  r  r  r  r   r   c                 s  s    | ]	\}}||V  qd S r?   r   )r8   pr  r   r   r   r   
  s
    
z"Arguments.parse.<locals>.<genexpr>z-tensor options arguments can only appear oncerT  rM  r  r  )rA   r   r  rb  r   r  )r  r  	enumeraterA   r  rb  rM   rh  r  r   rI   r  rg  rF  )r  r  r  re  self_ixir  r  r"  r-  r  rr  r  kwarg_only_accr  
predicatesr   r   r   rM   	  sn   




zArguments.parsec                 C  sZ   g }| tt| j | js| jr|d | tt| j | tt| j d|S )Nr  r   )r   rG  r   r  r  re  rg  r   )r   all_argumentsr   r   r   r   8
  s   

zArguments.__str__r  c                 C  s^   | j d u r| jrtd| jd u r| jrtddd | jD }t|dkr-td| d S )Nz5pre_self_positional is non-empty but self_arg is NonezFpost_tensor_options_kwarg_only is non-empty but tensor_options is Nonec                 S  r  r?   r  r  r   r   r   r:   Q
  r  z+Arguments.__post_init__.<locals>.<listcomp>r   zQmutable pre_self_positional arguments are not currently supported in the schema: )r"  r  rI   rr  r  rh  )r   mutable_pre_self_positionalsr   r   r   r  A
  s$   

zArguments.__post_init__Nr  )r   r  )r   r  )r   r  r   r  r  )r6  r   r   r  )r   r  )r2  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  r  r  r  rs  rR  r  r  r  r  r   r  rM   r   r  r   r   r   r   r  	  sN   
 




%


'
R	r  )r   submuldivmodpowlshiftrshiftandxororc                   @  sV   e Zd ZU ded< ded< ded< dZded< dZd	ed
< edddZdddZdS )rH  r   r  r   r  rD  Fr  Nr(  r"  r  r   c           
        s^  | dkrt d| drt dtd| }|r|dnd}|r'|dn| }td|}|d ur^d	}|d t fd
dtD rNd	} dd   n%d} d dkr]t d|  nd}|  d dkrqd	} d d  nd}d} |rd	} d t|   |s|rt d|  nd}t ||||d}	t	|	| krt t	|	 d|  |	S )Nr1   zoperator name cannot be emptyr@  zs_out suffix is reserved and not permitted for operator names; did you mean to specify an out overload name instead?z^(?:(.*)::)?(.*)$r  rT  z^__([^_]+)__$Tc                 3  s    | ]
} d | kV  qdS )r  Nr   )r8   nr  r   r   r   
  s    z)BaseOperatorName.parse.<locals>.<genexpr>Fr   r  z,unexpected dunder method starting with 'i': r  __functionalz:functional overload cannot be a dunder method or inplace: )r  r  rD  r  r"  r  )
rI   rq  rU  r]  r^  r  AUGMENTED_ASSIGNMENT_NAMESrh  rH  r   )
r  r]  r"  op_without_nsr  rD  r  functional_suffixr  r   r   r  r   rM   
  s`   


zBaseOperatorName.parsec                 C  sj   | j r	| j  dnd}| jr | jrdnd}| d| | j dS | jr%dn| jr*dnd}| | j | S )NrG  r1   r  __r  r  )r"  rD  r  r  r  )r   namespace_prefixr  r   r   r   r   
  s   zBaseOperatorName.__str__)r  r   r   rH  r   )	r   r   r   r   r  r"  r   rM   r   r   r   r   r   rH  t
  s   
 ArH  c                   @  sT   e Zd ZU ded< ded< edddZdd	d
ZdddZdddZdddZ	dS )rU  rH  rA   r   r+  r  r   c                 C  sZ   d| v r|  dd\}}n| }d}tt||d}t|| kr+tt| d|  |S )N.r  r1   r*  r  )r   rU  rH  rM   r   rI   )r  rA   r+  r   r   r   r   rM   
  s   zOperatorName.parsec                 C      | j r| j d| j  S | j S )Nr  r+  rA   r   r   r   r   r   
     zOperatorName.__str__c                 C  r  )Nr  r  r   r   r   r   unambiguous_name  r  zOperatorName.unambiguous_namec                 C  s    t t| jjd| jjd| jdS NFrC  r*  )rU  rH  rA   r  rD  r+  r   r   r   r   remove_inplace
  s   zOperatorName.remove_inplaceoverloadc                 C  s   t t| jjd| jjd|dS r  )rU  rH  rA   r  rD  )r   r  r   r   r   with_overload  s   zOperatorName.with_overloadN)r  r   r   rU  r   )r   rU  )r  r   r   rU  )
r   r   r   r   r   rM   r   r  r  r  r   r   r   r   rU  
  s   
 



rU  r  r  bc                 C  s(   | j  tjuo||  o||jS r?   )r$  r  r  r  r  )r  r  r  r   r   r   "gets_generated_out_inplace_wrapper  s
   

r   c                   @  s\   e Zd ZU ded< ded< ded< ddd	Zd
ddddZedddZedddZdS )NativeFunctionsViewGroupr!  viewr  	view_copyview_inplacer   r  c                 C  s  | j jstd| j jj | jd u r+t| j r*tt| j jj dt| j dnR| jjjjj	
ds?td| jjj | j j | jjjddkre| j j }| jjjdd}td| d	| d
| jjvr}tt| jjjt| j jf d| jd ur| j j | jj kr| j j }| jj }td| d	| | j jr| jd ur| jjstt| j jj dt| jjj d| j jr| jd ur| jjstt| j jj dt| jjj dd S d S d S )Nzview is not a view op: z appears to be a new operator that aliases its inputs. The codegen expects you to add a corresponding operator to native_functions.yaml: z3. See Note [view_copy NativeFunctions] for details.)r<  r=  z4view_copy name must end with '_copy' or '_scatter': TrM  z+view and view_copy signatures don't match: r  r  z appears to be a view_copy operator. The codegen expects view_copy operators to be annotated with the 'view_copy' tag in native_functions.yaml. See Note [view_copy NativeFunction] for details.z.view and view_inplace signatures don't match: r  z] must either both have CompositeImplicitAutograd kernels, or both not have composite kernels.zi must either both have CompositeImplicitAutogradNestedTensor kernels, or both not have composite kernels.)r  r  rI   r$  rA   r  gets_generated_view_copyr   get_view_copy_namer  rq  r  r<  r  r8  r9  )r   view_sigview_copy_sigview_inplace_sigr   r   r   r  >  s`   



"
"z&NativeFunctionsViewGroup.__post_init__T)include_copyr
  r   r  c                c  s>    | j V  | jd ur| jV  | jd ur|r| jV  d S d S d S r?   )r  r  r  )r   r
  r   r   r   r  s  s   
z"NativeFunctionsViewGroup.functionsr   c                 C  r  r?   )r  r  r   r   r   r   r  z  r   z"NativeFunctionsViewGroup.root_namec                 C  r  r?   )r  r8  r   r   r   r   	composite~  s   z"NativeFunctionsViewGroup.compositeNr  )r
  r   r   r  r   r  )	r   r   r   r   r  r  r  r  r  r   r   r   r   r  4  s   
 
5r  c                 C  s<   | j sdS | jr
dS d| jv rdS | jjjjdrdS dS )NFr  _inverseT)r  r8  r<  r$  rA   r  rq  )r  r   r   r   r    s   
r  c                 C  sj   dg}t | jj|vrt| st| jj d| jjjj d}tt|d| jjjjd| jjj	d}|S )Nnarrowz, does not have a generated view_copy variantr<  FrC  r*  )
r   r$  rA   r  rI   r  rU  rH  rD  r+  )r  -list_of_ops_with_explicit_view_copy_operatorsrI  view_copy_namer   r   r   r    s   r  r  r  c                 C  sH   | dkrdS | d dkr| d dkr| dd } t dd	 | d
D S )z$
    Input: '()'
    Output: []
    z()r   r   r  r  r  r  c                 s  s    | ]}t |V  qd S r?   )r9  rM   r  r   r   r   r     r  z parse_returns.<locals>.<genexpr>r   )rF  r   )r  r   r   r   r
    s
   r
  c                   @  s@   e Zd ZU ded< ded< eddd	ZdddZdddZdS )rf  zdict[str, list[Argument]]rE  r  r   srcobjectr   c           
      C  s  t | tstdt|  g }d| d vr*| d d}dd |D }| d d } i }| D ]>}t |ts>tdt| d|vrItd| |d\}}d	|v r\td
| d|d}dd |D }|||< q.t||d}	|	 | krtd|	  d|  |	S )Nz precomputed must be a list, got ra  r  rL  c                 S     g | ]	}t | qS r   r  rM   rk  r8   rA   r   r   r   r:         z$Precompute.parse.<locals>.<listcomp>z$precomputed item must be a str, got zSprecomputed parameters without replacement are allowed only in the last line, got: r  zillegal kernel param name 'z' in precomputed parametersc                 S  r  r   r  r  r   r   r   r:     r  )rE  r   zr.to_list() != src: r  )r^  rb  rI   r  r   r   rf  to_list)
r  add_argsadd_listrE  raw_replace_itemr  with_list_raw	with_listwith_list_argsr   r   r   r   rM     s:   
	



zPrecompute.parser  c                 C  sj   | j D ]}|j |jkrtd|j q| j D ]}|D ]}|j |jkr1td|j qqd S )Nz5precomputed argument name must not be all uppercase: )r   rA   upperrI   rE  r   )r   r  r  r   r   r   r    s   


zPrecompute.__post_init__r  c                 C  sD   g }| j  D ]\}}ddd |D }|| d|  q|S )Nr   c                 s  r  r?   r  )r8   paramr   r   r   r     r  z%Precompute.to_list.<locals>.<genexpr>ra  )rE  rH   r   rg  )r   replace_listkernel_paramreplacement_paramsreplacementsr   r   r   r    s
   zPrecompute.to_listN)r  r  r   rf  r  r  )r   r   r   r   r   rM   r  r  r   r   r   r   rf    s   
 
*rf  r   )r   r=   r   r   )r  r!  r  r  r  r  r   r   )r  r!  r   r   )r  r!  r   rU  )r  r   r   r  )v
__future__r   r  r  rU  r   enumr   r   typingr   typing_extensionsr   torchgen.utilsr   r	   collections.abcr
   r   r   r   r   rt  r   r   AUTOGRAD_KEYSFRAGMENT_NAMESPACESr=   r   r   r   r   hasattrr   printr  r'   r#   r"   r)   r&   r   r   r   r   rZ   r   r   r   r   r   r   r|   r}   rw   rx   ry   rz   r   r   r   r   r-   r   r   r   r   ra   rl  r   r   r   r   r   dispatch_device_mapr   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r!  r  r  rm  ru  r  r#  rW  rb  r  r  rf  rh  rg  r  r9  r  r  r  r  rH  rU  r   r  r  r  r
  rf  r   r   r   r   <module>   s@   	
 #


&




0

	      !q   >7 ]9
  Ls
6
P

