U
    zhG                     @   sh  U d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZm	Z	m
Z
mZmZmZ d dlZd dlm  mZ d dlmZ d dlmZ d dlmZ eedoeedZe jdd	 ZG d
d dZejjZ ejj!Z!ee!dddZ"i Z#e	e$df e%d< e!j&e!j'e!j(e!j)e!j*e!j+gZ,G dd deZ-dd Z.dd Z/dd Z0dd Z1G dd dZ2e2 a3dKddZ4dd  Z5d!d" Z6d#d$ Z7d%d& Z8d'd( Z9d)d* Z:e; a<ed+ e%d,< d-d. Z=d/d0 Z>d1d2 Z?G d3d+ d+eZ@G d4d5 d5e@ZAd6d7 ZBejCeDd8d9d:ZEG d;d< d<ZFeFd=d>d?ZGG d@dA dAejHZIdBdC ZJdDdE ZKG dFdG dGeIZLG dHdI dIejHZMeM ZNeMe%dJ< dS )L    N)AnyCallableDictListSetTypeUnion)_utils_internal)dispatch_functorch)TorchDispatchModegetdlopenflagssetdlopenflagsc               	   c   sB   t sdV  dS t } t| tjB  z
dV  W 5 t|  X dS )z
    Context manager to set the RTLD_GLOBAL dynamic linker flag while we open a
    shared library to load custom operators.
    N)_SET_GLOBAL_FLAGSsysr   r   ctypesRTLD_GLOBAL)Z	old_flags r   </var/www/html/venv/lib/python3.8/site-packages/torch/_ops.pydl_open_guard   s    
r   c                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )OperatorBasez
    Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator
    (which represents Python-only operators that are unrepresentable in TorchScript).
    c                 C   s   i | _ i | _i | _i | _d S N)_dispatch_cache
py_kernelspython_key_mode_tablefunctorch_tableselfr   r   r   __init__,   s    
zOperatorBase.__init__c                 O   s   t d S r   NotImplementedError)r   argskwargsr   r   r   __call__X   s    zOperatorBase.__call__c                 C   s
   || j kS r   )r   r   kr   r   r   has_kernel_for_dispatch_key[   s    z(OperatorBase.has_kernel_for_dispatch_keyc                 C   s,   | j D ] }tj|s||r dS qdS )NTF)r   torch_CZ_dispatch_is_alias_keyhas)r   ksr$   r   r   r   has_kernel_for_any_dispatch_key^   s    
z,OperatorBase.has_kernel_for_any_dispatch_keyc                    s    fdd}|S )Nc                    s   t  r:t tr: jks"t| j < j  | S t t	j
jjrf jksXt| j < | S t t	j
jsxt t	j
jjkstd jkrtd  d  | j < j  | S )NzGPlease register a mode for the torch._C.DispatchKey.Python key instead.z%Trying to override a python impl for z on operator )inspectisclass
issubclassr   r   AssertionErrorr   clear
isinstancer&   r'   
_functorchTransformTyper   DispatchKeyPythonr   RuntimeErrorname)fnr$   r   r   r   innere   s*    





z#OperatorBase.py_impl.<locals>.innerr   )r   r$   r9   r   r8   r   py_impld   s    zOperatorBase.py_implc                    s   ddl m mm  fdd}fdd}fdd}| tjjj| | tj	j
j| | tjjjj| S )	Nr   )CppFunctionalizeAPIFunctorchFunctionalizeAPIPythonFunctionalizeAPIc                     s     f| |S r   r   r    r!   )_CppFunctionalizeAPIr7   r   r   functionalize_dk_fn   s    z?OperatorBase.py_functionalize_impl.<locals>.functionalize_dk_fnc                    s    | f||S r   r   )moder    r!   )_PythonFunctionalizeAPIr7   r   r   functionalize_dispatch_mode_fn   s    zJOperatorBase.py_functionalize_impl.<locals>.functionalize_dispatch_mode_fnc                    s    | f||S r   r   )interpreterr    r!   )_FunctorchFunctionalizeAPIr7   r   r   functionalize_functorch_fn   s    zFOperatorBase.py_functionalize_impl.<locals>.functionalize_functorch_fn)#torch._subclasses.functional_tensorr;   r<   r=   r:   r&   r'   r3   FunctionalizeZ_subclassesZfunctional_tensorFunctionalTensorModer1   r2   )r   r7   r@   rC   rF   r   )r?   rE   rB   r7   r   py_functionalize_impl   s    z"OperatorBase.py_functionalize_implc                 C   s   t d S r   r   r   r   r   r   r6      s    zOperatorBase.nameN)__name__
__module____qualname____doc__r   r"   r%   r*   r:   rJ   r6   r   r   r   r   r   &   s   ,(r   )opr$   c                 C   sd  |  |r|S tj}|tjks(t||r6|  |r6|S tj}|tjksPt||r^|  |r^|S | tj	|pz|  tj}tj
}|tjkrt||r|  |r|s|S tj}|tjkst||r|  |r|tjkr| tjjrtdn|s|S tj}t||r|  |r|S tj}t||r:|  |r:|S tj|rL|S td|  d| d S )Nzambiguous autogradother kernelzcould not find kernel for  at dispatch key )r%   r3   Z&CompositeExplicitAutogradNonFunctionalZ	Undefinedis_included_in_aliasZCompositeExplicitAutogradr*   r&   r'   Z*_dispatch_get_backend_keyset_from_autogradZ%CompositeImplicitAutogradNestedTensorCompositeImplicitAutogradZAutogradOtherZ _dispatch_autogradother_backendsr5   AutogradZFuncTorchBatchedDecompositionZ_dispatch_has_backend_fallbackr   )rO   r$   candZhas_backend_kernelr   r   r   resolve_key   sn    



rU   HigherOrderOperator_higher_order_opsc                       s\   e Zd Z fddZ fddZedd Zdd Zd	d
 Zdd Z	dd Z
dd Z  ZS )rV   c                    sr   t    || _|| _| t|< d| _| jtkrN| jr>d| j nd}| j	| | _	t
j | _tD ]}| | q^d S )Nhigher_order. )superr   _namerK   rW   _ns	__class__rV   	namespacerL   r&   r'   _dispatch_keyset_fullnon_fallthrough_keys2_HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYSfallthrough)r   r6   Zself_name_spacedispatch_keyr^   r   r   r      s    

zHigherOrderOperator.__init__c                    s4   t |tjjr(| j|s(| j|| _t |S r   )	r0   r&   r'   r3   ra   r(   addr[   r:   r#   re   r   r   r:     s    zHigherOrderOperator.py_implc                 C   s   | j S r   )r]   r   r   r   r   r_     s    zHigherOrderOperator.namespacec                 C   s   | j || _ d S r   )ra   remove)r   rd   r   r   r   rc      s    zHigherOrderOperator.fallthroughc              
   O   s  ddl m} || jkr<| j| }t|tjjr2t|||S |tjjjkrVt	| ||S |tjjj
krddl m} | }|d k	stdt|| jkstd| d| jt| }| }	||	f||W  5 Q R  S Q R X tj|}
|
tjjjkrddl m} t dkrtjtj
st }|d k	s8tdt|| jksXtd| d| jt| }||
}	||	f||W  5 Q R  S Q R X t| |}|| jkrtd| j d	| d
| d|tjjjkr| j| | j|< | j| }t|tjjrt|||S )Nr   _get_current_dispatch_mode)_pop_mode_temporarilyMIllegal invocation of dispatch on torch._C.DispatchKey.Python without a mode.zCurrent active mode z not registeredzRIllegal invocation of dispatch on torch._C.DispatchKey.PreDispatch without a mode.z.could not find kernel for HigherOrderOperator rP   z (resolved from ))torch.utils._python_dispatchri   r   r0   r&   r'   r3   r.   ZFuncTorchDynamicLayerFrontModer
   r4   rj   typer   _to_functionality_keyPreDispatch&_len_torch_dispatch_stack_pre_dispatch&_dispatch_tls_is_dispatch_key_excluded'_get_current_dispatch_mode_pre_dispatchrU   r   r   r\   )r   rd   r    r!   ri   Zkernelrj   	curr_modehandlerrA   functionality_key	final_keyr   r   r   dispatch#  sh    



"

"
	
zHigherOrderOperator.dispatchc                    s0   dd l ddl m} | fdd}| S )Nr   )disablec                     sP   t  } j| r,jj| f S t j}j| f S r   )_to_flat_tupleZ	overridesZhas_torch_functionZhandle_torch_function_compute_keysetra   rx   highestPriorityTypeId)Z	flat_argsdispatch_key_setr    r!   r   r&   r   r   wrappero  s$    
 z-HigherOrderOperator.__call__.<locals>.wrapper)Ztorch._dynamory   )r   r    r!   ry   r   r   r~   r   r"   i  s
    zHigherOrderOperator.__call__c                 C   s
   |    S r   )r6   r   r   r   r   __str__~  s    zHigherOrderOperator.__str__c                 C   s   | j S r   r\   r   r   r   r   r6     s    zHigherOrderOperator.name)rK   rL   rM   r   r:   propertyr_   rc   rx   r"   r   r6   __classcell__r   r   re   r   rV      s   
Fc                 C   s   t j| |S r   )pytreeZarg_tree_leavesr>   r   r   r   rz     s    rz   c                 C   s   t | |}t||S r   )_get_tensorskey_extractor)r    r!   ra   tensorsr   r   r   r{     s    
r{   c                 C   s    t | |}dd |D }t|S )Nc                 S   s   g | ]}t |tjr|qS r   )r0   r&   ZTensor).0tr   r   r   
<listcomp>  s      z _get_tensors.<locals>.<listcomp>)rz   tuple)r    r!   Zflat_allZtensor_argsr   r   r   r     s    
r   c                 C   s>   t j }| D ]}|t j|B }q|t j  }||@ }|S r   )r&   r'   Z_dispatch_tls_local_include_setZ_dispatch_keysZ_dispatch_tls_local_exclude_set)r   Zkey_maskZkey_setZtensorr   r   r   r     s    
r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
_ModeStackStateForPreDispatchc                 C   s   d d g| _ d | _d S r   )*_ModeStackStateForPreDispatch__infra_modes_schema_check_moder   r   r   r   r     s    
z&_ModeStackStateForPreDispatch.__init__c                 C   s    |t | jk st|| j|< d S r   lenr   r.   )r   indexrA   r   r   r   set  s    z!_ModeStackStateForPreDispatch.setc                 C   s   |t | jk st| j| S r   r   )r   r   r   r   r   get  s    z!_ModeStackStateForPreDispatch.getc                 C   s"   t dd | jD t| jd k	 S )Nc                 S   s   g | ]}|d k	r|qS r   r   )r   ir   r   r   r     s      z7_ModeStackStateForPreDispatch.count.<locals>.<listcomp>)r   r   intr   r   r   r   r   count  s    z#_ModeStackStateForPreDispatch.countN)rK   rL   rM   r   r   r   r   r   r   r   r   r     s   r   Fc                    st   t   d ks*tjjjtjjjfks*t|r:d ks:t fdd}| }t }|dkrptjtjj	j
d |S )Nc                     sl   t jjjkr* d} t dd  | S t jjjkrT d} t dd  | S t j} d t _| S d S Nr      )	r&   r'   _TorchDispatchModeKeyPROXYr   !mode_stack_state_for_pre_dispatchr   
FUNCTIONALr   )current_modeZcurrent_mode_stack_pre_dispatchmode_keyr   r   _unset_mode  s    

z,unset_mode_pre_dispatch.<locals>._unset_moder   F)r   r&   r'   r   r   r   r.   rq   '_dispatch_tls_set_dispatch_key_includedr3   rp   )r   schema_checkr   r   Znew_pre_dispatch_lenr   r   r   unset_mode_pre_dispatch  s     

 r   c                 C   s   ddl m} ddlm} ddlm} t| |||fs8tt }t| |rjt	 j
}|dkr`td| t	 _
nXt| |rt	 d}|d kstt	 d|  n&t	 d}|d kstt	 d|  |dkrtjtjjjd d S )Nr   )rI   )SchemaCheckMode)ProxyTorchDispatchModezYSchemaCheckMode for pre-dispatch must be used exclusively, found other modes on the stackr   T)rG   rI   Z#torch._subclasses.schema_check_moder   Z"torch.fx.experimental.proxy_tensorr   r0   r.   rq   r   r   r   r   r&   r'   r   r3   rp   )rA   rI   r   r   Zprevious_mode_stack_lenr   r   r   r   _set_mode_pre_dispatch  s<    	


 r   c                  C   sn   t  } t }|dkrtd| jd k	r2td ddS | dd k	rNttjjj	S | dd k	rjttjjj
S d S )Nr   zTrying to pop empty mode stackT)r   r   )r   rq   r.   r   r   r   r&   r'   r   r   r   )Z
mode_stackZpre_dispatch_lenr   r   r   _pop_mode_from_pre_dispatch  s    
r   c                   C   s
   t   S r   )r   r   r   r   r   r   rq      s    rq   c                 C   sF   | t jjjt jjjfkst| t jjjkr6t dS t dS d S r   )r&   r'   r   r   r   r.   r   r   )r   r   r   r   _get_dispatch_mode_pre_dispatch$  s    
r   c                  C   sf   t  jd k	rt  jS t   } | dkr2t  dS | dkrbt  dd k	rVt  dS t  dS d S )N   r   r   )r   r   r   r   )Z	stack_lenr   r   r   rs   /  s    

rs   c                   C   s   t S r   )"_mode_stack_state_for_pre_dispatchr   r   r   r   r   ?  s    r   
OpOverload
cached_opsc                 C   s   t |  d S r   )r   rf   )op_overloadr   r   r   add_cached_opG  s    r   c                   C   s   t   d S r   )r   r/   r   r   r   r   reset_cached_opsL  s    r   c                   C   s   t S r   )r   r   r   r   r   get_cached_opsQ  s    r   c                       s   e Zd Z fddZedd Zedd Zedd Zd*d
dZdd Z	dd Z
dd Zdd Zdd Z fddZ fddZedd Zdd Zdd Zd d! Zd"d# Zed$d% Zed&d' Zed(d) Z  ZS )+r   c                    s  t    || _|| _|| _|| _|| _|jdkr6dn|j| _| jj	| _
|jrb|  j
d|j 7  _
| jj	dd  d| j | _|j| _|j|_| j
| _i | _d | _| jtjjk| _d }| jjD ].}|jd krq|d kr|jj}q|jjp|}q|d k	o| | _d S )NrZ   defaultrY   ::r   )r[   r   _op_op_dk_schema_overloadpacket_tagsoverload_name_overloadnamer6   r\   splitrK   rL   rM   __annotations___lazy_handler&   libraryZ_defsZ_defined_in_python	argumentsZ
alias_infois_writeZis_view)r   overloadpacketrO   Zop_dkschematagsr   are   r   r   r   Y  s4    

 

zOpOverload.__init__c                 C   s   | j jdd S Nr   r   r   r6   r   r   r   r   r   
_namespace  s    zOpOverload._namespacec                 C   s   | j jdd S )Nr   r   r   r   r   r   r   _opname  s    zOpOverload._opnamec                 C   s(   | j d kr"tj| jj| jj| _ | j S r   )r   r&   r'   Z_dispatch_find_schema_or_throwr   r6   r   r   r   r   r   _handle  s    
 zOpOverload._handleNc                 C   s   | S r   r   r   memor   r   r   __deepcopy__  s    zOpOverload.__deepcopy__c                 C   s   dj | jjd| jf S )Nz'<OpOverload(op='{}.{}', overload='{}')>r   formatr   r6   r   r   r   r   r   r   __repr__  s     zOpOverload.__repr__c                 O   s   | j ||S r   r   self_r    r!   r   r   r   r"     s    zOpOverload.__call__c                 O   s   | j j|f||S r   )r   Zredispatch_boxed)r   Zkeysetr    r!   r   r   r   
redispatch  s    zOpOverload.redispatchc                 C   s
   t | jS r   hashr   r   r   r   r   __hash__  s    zOpOverload.__hash__c                 C   s   dj | jjd| jf S )Nz{}.{}.{}r   r   r   r   r   r   r     s    zOpOverload.__str__c                    s   t  |ptj|  |S r   )r[   r%   r&   r'   %_dispatch_has_kernel_for_dispatch_keyr6   r#   re   r   r   r%     s
    z&OpOverload.has_kernel_for_dispatch_keyc                    s   t j|  |pt |S r   )r&   r'   Z)_dispatch_has_kernel_for_any_dispatch_keyr6   r[   r*   )r   r)   re   r   r   r*     s     
z*OpOverload.has_kernel_for_any_dispatch_keyc                 C   s   | j jdd S r   r   r   r   r   r   r_     s    zOpOverload.namespacec                 O   sP   t jjj}|| jkr$| j| ||S t j|  |rH| j|f||S tS d S r   )	r&   r'   r3   rR   r   r   r6   r   NotImplemented)r   r    r!   Zdkr   r   r   	decompose  s    

zOpOverload.decomposec                 C   s   | j |d  d S r   )r   pop)r   keyr   r   r   _uncache_dispatch  s    zOpOverload._uncache_dispatchc           	         sN   j kst d   tjjjkrtttsPjsP j  < t	  S  fdd}|j  < t	 |S tj
 }|tjjjkrt }|dkrtjtjsfdd}|S t } tjjjk} tjjjkr$dd lm  m} |jr$||}|r |j  < t	 |S j||}|rJ|j  < t	 |S )N c               
      s   ddl m} t| }|d k	s&td|jkrttrttjj	
 &}tjjj|f| |W  5 Q R  S Q R X nj f| |S tjj	
 $}j| |f| |W  5 Q R  S Q R X d S )Nr   rh   rk   )rm   ri   rn   r.   r   r0   TorchBindOpOverloadr&   utilsZ_python_dispatchrj   _libraryhandle_dispatch_moder   )r    r!   ri   rt   rA   r   r   r   r   ru     s(    


 z)OpOverload._get_dispatch.<locals>.handlerr   c               
      sD   t jdd }| &}tjjj| f| |W  5 Q R  S Q R X d S )Nc                  s   s    t  } z
| V  W 5 t|  X d S r   )r   r   )Ztop_moder   r   r   (_temporarily_pop_modes_from_pre_dispatch  s    
z[OpOverload._get_dispatch.<locals>.handler.<locals>._temporarily_pop_modes_from_pre_dispatch)
contextlibcontextmanagerr&   r   r   r   )r    r!   r   rt   r   r   r   ru     s    
 )r   r.   r&   r'   r3   r4   r0   r   r   r   ro   rp   rq   rr   rU   rH   Ztorch._dispatch.pythonZ	_dispatchpythonZCROSSREF_FUNCTIONALIZEZmake_crossref_functionalizer   r   )	r   r   ru   rv   Zcurr_stack_lenrw   Zcache_resultZ
pydispatchrr   r   r   _get_dispatch  sN    




zOpOverload._get_dispatchc                 C   s   | j S r   r   r   r   r   r   r6   0  s    zOpOverload.namec                 C   s   | j S r   )r   r   r   r   r   r   3  s    zOpOverload.overloadpacketc                 C   s   | j S r   r   r   r   r   r   rO   7  s    zOpOverload.opc                 C   s   | j S r   )r   r   r   r   r   r   ;  s    zOpOverload.tags)N)rK   rL   rM   r   r   r   r   r   r   r   r"   r   r   r   r%   r*   r_   r   r   r   r6   r   rO   r   r   r   r   re   r   r   X  s6   &




`

c                   @   s<   e Zd Zee dddZejdd Zdd Z	dd	 Z
d
S )r   )returnc                    sD   t jt jt jt jt jt jt jg}t dfdd  fdd|D S )Nr   c                    s@   t j  | r$t j  | S |  jkp> j|  t jjkS r   )r&   r'   r   r6   0_dispatch_kernel_for_dispatch_key_is_fallthroughr   r   Zfallthrough_kernelr   r   r   r   (_may_use_fallthrough_instead_of_fallbackT  s     
zWTorchBindOpOverload._fallthrough_keys.<locals>._may_use_fallthrough_instead_of_fallbackc                    s   g | ]} |r|qS r   r   )r   r   )r   r   r   r   _  s   z9TorchBindOpOverload._fallthrough_keys.<locals>.<listcomp>)r3   rS   ZAutogradCPUZAutogradCUDAADInplaceOrViewBackendSelectPythonTLSSnapshotPythonDispatcher)r   Z_DEFAULT_FALLTHROUGH_KEYSr   )r   r   r   _fallthrough_keysG  s    

z%TorchBindOpOverload._fallthrough_keysc                 c   sH   ddl m}m}m} z| |kr*|| |j d V  W 5 | |krB|| = X d S )Nr   )_EffectType_register_effectful_opSIDE_EFFECTS)Ztorch._higher_order_ops.effectsr   r   r   ZORDERED)r   r   r   r   r   r   r   %_register_as_effectful_op_temporarilye  s    
z9TorchBindOpOverload._register_as_effectful_op_temporarilyc              
   O   sD   t ||r8|    | |||  W  5 Q R  S Q R X | j||S r   )_must_dispatch_in_pythonr   _dispatch_in_pythonr   r   r   r   r   r   r"   w  s    

  zTorchBindOpOverload.__call__c           	      C   s   t j }|D ]}||}qt|||}| }|| jkrF| |n| j| }t|t	rt j
|  |r| ||||g S td|  d| d| dt|tst|||S )NzTorchbind op z4 received a FakeScriptObject input when dispatching z. but no python implementation is found. Please file an issue on this when you encounter this error. This error can happen when you export or compile the model. It can still happpen even if a C++ implementation for zz.  has been registered. That's because FakeScriptObject purely lives in python and cannot work  with a C++ implementation.)r&   r'   r`   rg   r{   r|   r   r   r0   r3   r   r6   r   r5   r   r.   )	r   r    r!   Zfallthrough_keysra   r   r}   rd   ru   r   r   r   r     s0    

   
z'TorchBindOpOverload._dispatch_in_pythonN)rK   rL   rM   r   r3   r   r   r   r   r"   r   r   r   r   r   r   F  s
   
r   c                 C   s   t dd | |fS )Nc                 S   s   t | tjjjS r   )r0   r&   r   Zfake_class_registryZFakeScriptObject)objr   r   r   <lambda>  s    z*_must_dispatch_in_python.<locals>.<lambda>)r   Ztree_anyr>   r   r   r   r     s    r   )r   r   c                 C   s   t dd | jD S )Nc                 s   s   | ]}t |jtjV  qd S r   )r0   rn   r&   Z	ClassType)r   argr   r   r   	<genexpr>  s     z)_has_script_object_arg.<locals>.<genexpr>)anyr   )r   r   r   r   _has_script_object_arg  s    r   c                   @   sn   e Zd Zdd ZdddZdd Zdd	 Zd
d Zedd Z	edd Z
dd Zdd Zdd Zdd ZdS )OpOverloadPacketc                 C   s<   || _ || _|| _|| _g | _tdd | j D | _d S )Nc                 s   s   | ]}t |V  qd S r   )r   )r   r   r   r   r   r     s    z,OpOverloadPacket.__init__.<locals>.<genexpr>)	_qualified_op_namerK   r   _overload_names_dirr   _schemasvalues_has_torchbind_op_overload)r   qualified_op_nameop_namerO   overload_namesr   r   r   r     s    zOpOverloadPacket.__init__Nc                 C   s   | S r   r   r   r   r   r   r     s    zOpOverloadPacket.__deepcopy__c                 C   s   dj | jd S )Nz<OpOverloadPacket(op='{}.{}')>r   r   r   r   r   r   r   r   r     s    
zOpOverloadPacket.__repr__c                 C   s
   t | jS r   r   r   r   r   r   r     s    zOpOverloadPacket.__hash__c                 C   s   dj | jd S )Nz{}.{}r   r  r   r   r   r   r     s    zOpOverloadPacket.__str__c                 C   s   | j S r   r   r   r   r   r   rO     s    zOpOverloadPacket.opc                    s    fdd j D S )Nc                    s   i | ]}|t j j|qS r   )r&   r'   _get_schemar   )r   r   r   r   r   
<dictcomp>  s    z-OpOverloadPacket._schemas.<locals>.<dictcomp>r   r   r   r   r   r    s    
zOpOverloadPacket._schemasc                 C   s  |dkrdS z| dr&t| j|W S W n< tk
rd   tdt|  dt| j d| dd Y nX z||dkrtd	n|}tj| j|\}}}tj	| j|}t
|st| ||||nt| ||||}t| || | j| |W S  tk
r   td
t|  d| dd Y nX d S )N__file__	torch.ops__'zH' can't have an overload name beginning with '__' and the underlying op z has no attribute z either.r   rZ   zThe underlying op of 'z' has no overload name ')
startswithgetattrr   AttributeErrorstrr&   r'   Z_get_operation_overloadr   r  r   r   r   setattrr   appendr5   )r   r   Zuse_keyZop_Zop_dk_r   r   overloadr   r   r   __getattr__  s>    	
  
zOpOverloadPacket.__getattr__c                 C   s
   t | jS r   iterr   r   r   r   r   __iter__  s    zOpOverloadPacket.__iter__c                 O   s,   | j rt||rt| ||S | j||p(i S r   )r  r   !_call_overload_packet_from_pythonr   r   r   r   r   r"     s    zOpOverloadPacket.__call__c                 C   s   dd | j D S )Nc                 S   s   g | ]}|r|nd qS )r   r   )r   nr   r   r   r   )  s     z.OpOverloadPacket.overloads.<locals>.<listcomp>r
  r   r   r   r   	overloads(  s    zOpOverloadPacket.overloads)N)rK   rL   rM   r   r   r   r   r   r   rO   r  r  r  r"   r  r   r   r   r   r     s   


/r   )rO   c                 C   s   t jj| f||\}}|r |S i }d }|  D ]^}t| |}z$t jj|jf||}	|}W  qW q0 tk
r }
 z|
||< W 5 d }
~
X Y q0X q0|r|||S d|  d}t|	 D ]"\}\}}|d| d| d7 }qt|d S )Nz'Fail to match any TorchBindOverload of z with following exceptions:
zOverload name z:
 
)
r&   r'   Z(_maybe_call_torch_function_for_op_packetr  r  Z&_check_schema_allow_fake_script_objectr   r5   	enumerateitems)rO   r    r!   Ztorch_function_calledret
exceptionsZfound_opr   r   _eerr_msgr   r   msgr   r   r   r  .  s@    



r  c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )_OpNamespacea0  
    An op namespace to dynamically bind Operators into Python.

    Say a user has created a custom Operator called "my_namespace::my_op". To
    call this op, the user will write torch.ops.my_namespace.my_op(...).
    At startup, this operation will not yet be bound into Python. Instead, the
    following sequence of magic tricks will occur:
    1. `torch.ops.my_namespace` will invoke the `__getattr__` magic method
       on the `torch.ops` object, which will create a new `_OpNamespace`
       object called `my_namespace` and set it as an attribute on the `ops`
       object.
    2. `torch.ops.my_namespace.my_op` will then invoke `__getattr__` on
       the `my_namespace` object, which will retrieve the operation via
       `torch.get_operation`, a function bound from C++, and then in a similar
       fashion bind this new object onto the `my_namespace` object.
    3. `torch.ops.my_namespace.my_op(...)` then calls this new operation
        and subsequent accesses will incur no further lookup (the namespace and
        operation will already exist).
    c                    s    t  d|  || _g | _d S )Nz
torch.ops.)r[   r   r6   r   )r   r6   re   r   r   r   x  s    z_OpNamespace.__init__c                 C   s
   t | jS r   r  r   r   r   r   r  }  s    z_OpNamespace.__iter__c           	   
   C   s   |dkrdS |dkr,t d| d| j d| j}| d| }| jd | }z2t||\}}|d kr~t d	| j d
| dW n< tk
r } zt d	| j d
| d|W 5 d }~X Y nX ||_t||||}| jd | |_t| || | j| |S )Nr  r  )
__origin____self__zInvalid attribute 'z' for '_OpNamespace' 'r  r   rY   z'_OpNamespace' '' object has no attribute ')	r  r6   rL   _get_packetr5   r   r  r   r  )	r   r  Znamespace_namer  module_namerO   r  r#  Zopoverloadpacketr   r   r   r    s@       z_OpNamespace.__getattr__)rK   rL   rM   rN   r   r  r  r   r   r   re   r   r&  c  s   r&  c                 C   s6   t j| \}}|d k	r.t jj||  ||_||fS r   )r&   r'   Z_jit_get_operationZjitZ	_builtinsZ_register_builtinrL   )qualnameZ	op_modulerO   r  r   r   r   r*    s
    r*  c                 C   s0   t | j| jj\}}|d k	s t|| _|| _d S r   )r*  r   r   rL   r.   r   )packetrO   r  r   r   r   _refresh_packet  s    r.  c                       s$   e Zd Z fddZdd Z  ZS )_PyOpNamespacec                    s   t  | || _d S r   )r[   r   _ops)r   r6   opsre   r   r   r     s    z_PyOpNamespace.__init__c                 C   s>   | j |d }|d kr.td| j d| dt| || |S )Nz'_PyOpNamespace' 'r)  r  )r0  r   r  r6   r  )r   r6   rO   r   r   r   r    s    z_PyOpNamespace.__getattr__)rK   rL   rM   r   r  r   r   r   re   r   r/    s   r/  c                       s@   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Z  Z	S )_Opsz_ops.pyc                    s*   t  d t | _tdt| _g | _d S )Nr  ztorch.ops.higher_order)r[   r   r   loaded_librariesr/  rW   _higher_order_op_namespacer   r   re   r   r   r     s     z_Ops.__init__c                 C   s2   |dkr| j S t|}t| || | j| |S )NrX   )r4  r&  r  r   r  )r   r6   r_   r   r   r   r    s    z_Ops.__getattr__c                 C   s
   t | jS r   r  r   r   r   r   r    s    z_Ops.__iter__c                 C   s   t | dS )a{  
        Imports a Python module that has torch.library registrations.

        Generally, to extend PyTorch with custom operators, a user will
        create a Python module whose import triggers registration of
        the custom operators via a torch.ops.load_library call or a call
        to one or more torch.library.* APIs.

        It is unexpected for Python modules to have side effects, so some
        linters and formatters will complain. Use this API to import Python
        modules that contain these torch.library side effects.

        Args:
            module (str): The name of the Python module to import

        N)	importlibimport_module)r   moduler   r   r   r6    s    z_Ops.import_modulec              	   C   sB   t  rdS t|}t  t| W 5 Q R X | j| dS )a  
        Loads a shared library from the given path into the current process.

        The library being loaded may run global initialization code to register
        custom operators with the PyTorch JIT runtime. This allows dynamically
        loading custom operators. For this, you should compile your operator
        and the static registration code into a shared library object, and then
        call ``torch.ops.load_library('path/to/libcustom.so')`` to load the
        shared object.

        After the library is loaded, it is added to the
        ``torch.ops.loaded_libraries`` attribute, a set that may be inspected
        for the paths of all libraries loaded using this function.

        Args:
            path (str): A path to a shared library to load.
        N)	r&   Z_running_with_deployr	   Zresolve_library_pathr   r   CDLLr3  rf   )r   pathr   r   r   load_library  s    
z_Ops.load_library)
rK   rL   rM   r  r   r  r  r6  r:  r   r   r   re   r   r2    s   r2  r1  )F)Or   r   r5  r+   r   typestypingr   r   r   r   r   r   r   Ztorch._Cr&   Ztorch.utils._pytreer   Z_pytreer   r	   Ztorch._functorch.pyfunctorchr
   rm   r   hasattrr   r   r   r   r'   Z_dispatch_is_included_in_aliasrQ   r3   rU   rW   r  r   r   r   r   r   ZAutocastCPUZAutocastCUDArb   rV   rz   r{   r   r   r   r   r   r   r   rq   r   rs   r   r   r   r   r   r   r   r   r   ZFunctionSchemaboolr   r   r  
ModuleTyper&  r*  r.  r/  r2  r1  r   r   r   r   <module>   sx    $
 5
 
&) oi	p5E
K