o
    hE                     @   s  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Zd dlmZm	Z	m
Z
mZmZmZ d dlmZmZ d dlZd dlm  mZ d dlmZ d dlmZmZ d dlmZmZ d dlmZ erfd dl m!Z! ed	Z"ed
Z#e$edowe$edZ%ej&dd Z'G dd dZ(de(defddZ)i Z*e+e,df e-d< ej.ej/ej0ej1ej2ej3gZ4G dd de(e j5Z6dd Z7dd Z8dd Z9dd Z:G d d! d!Z;e; a<dQd#d$Z=d%d& Z>d'd( Z?d)d* Z@d+d, ZAd-d. ZBd/d0 ZCeD aEeDd1 e-d2< d3d4 ZFd5d6 ZGd7d8 ZHG d9d1 d1e(ZIG d:d; d;eIZJd<d= ZKd>ejLd?eMfd@dAZNG dBdC dCZOdeOfdDdEZPG dFdG dGejQZRdHdI ZSdJdK ZTG dLdM dMeRZUG dNdO dOejQZVeV ZWeVe-dP< dS )R    N)AnyCallableOptionalTYPE_CHECKINGTypeVarUnion)Concatenate	ParamSpec)_utils_internal)_dispatch_is_included_in_aliasDispatchKey)dispatch_functorchTransformType)TorchDispatchMode)BaseFunctionalizeAPI_T_Pgetdlopenflagssetdlopenflagsc               	   c   sL    t sdV  dS t } t| tjB  zdV  W t|  dS t|  w )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)	old_flags r   ^/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/_ops.pydl_open_guard    s   r   c                   @   s   e Zd ZdZdd Zdd Zdd Zdd	 Zd
ee	e
 e	ej eef deeeef geeef f fddZdeedef ef deedef ef f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_tablefunctorch_tableselfr   r   r   __init__7   s   

zOperatorBase.__init__c                 O      t r   NotImplementedErrorr$   argskwargsr   r   r   __call__c      zOperatorBase.__call__c                 C   s
   || j v S r   )r    r$   kr   r   r   has_kernel_for_dispatch_keyf      
z(OperatorBase.has_kernel_for_dispatch_keyc                 C   s,   | j D ]}tj|s||r dS qdS )NTF)r    torch_C_dispatch_is_alias_keyhas)r$   ksr/   r   r   r   has_kernel_for_any_dispatch_keyi   s
   
z,OperatorBase.has_kernel_for_any_dispatch_keyr/   returnc                    s,   dt ttf dt ttf f fdd}|S )Nfnr8   c                    s   t  r#t tst tjr# jvsJ | j < j  | S t	 t
r6 jvs/J | j < | S t	 ts=J  tjksFJ d jv rWtd  d  | j < j  | S )Nz>Please register a mode for the DispatchKey.Python key instead.z%Trying to override a python impl for z on operator )inspectisclass
issubclassr   r2   Tensorr!   r   clear
isinstancer   r"   r   Pythonr    RuntimeErrorname)r9   r/   r$   r   r   innerx   s0   








z#OperatorBase.py_impl.<locals>.inner)r   r   r   )r$   r/   rD   r   rC   r   py_implo   s   (	zOperatorBase.py_implr9   r   c                    s   ddl m m}mm dtjdtjdtf fdd}dt	| dtjdtjdtffd	d
}dtjdtjdtffdd}| 
tj| | 
|| | 
tj| S )Nr   )CppFunctionalizeAPIFunctionalTensorModeFunctorchFunctionalizeAPIPythonFunctionalizeAPIr*   r+   r8   c                     s     g| R i |S r   r   r*   r+   )rF   r9   r   r   functionalize_dk_fn   s   z?OperatorBase.py_functionalize_impl.<locals>.functionalize_dk_fnmodec                        | g|R i |S r   r   )rL   r*   r+   )rI   r9   r   r   functionalize_dispatch_mode_fn      zJOperatorBase.py_functionalize_impl.<locals>.functionalize_dispatch_mode_fnc                    rM   r   r   )interpreterr*   r+   )rH   r9   r   r   functionalize_functorch_fn   rO   zFOperatorBase.py_functionalize_impl.<locals>.functionalize_functorch_fn)#torch._subclasses.functional_tensorrF   rG   rH   rI   r   r*   r+   r   r   rE   r   Functionalizer   )r$   r9   rG   rK   rN   rQ   r   )rF   rH   rI   r9   r   py_functionalize_impl   s,    	z"OperatorBase.py_functionalize_implc                 C   r&   r   r'   r#   r   r   r   rB      r-   zOperatorBase.nameN)__name__
__module____qualname____doc__r%   r,   r0   r7   r   typer   r2   r=   r   r   r   r   r   rE   r   rT   rB   r   r   r   r   r   1   s.    ,
2
r   opr/   c                 C   sT  |  |r|S tj}|tjkst||r|  |r|S tj}|tjks(t||r/|  |r/|S | tj	|p=|  tj}tj
}|tjkrTt||rT|  |rT|sT|S tj}|tjksat||rz|  |rz|tjkrv| tjjrvtd|sz|S tj}t||r|  |r|S tj}t||r|  |r|S tj|r|S td|  d| )Nzambiguous autogradother kernelzcould not find kernel for  at dispatch key )r0   r   &CompositeExplicitAutogradNonFunctional	Undefinedis_included_in_aliasCompositeExplicitAutogradr7   r2   r3   *_dispatch_get_backend_keyset_from_autograd%CompositeImplicitAutogradNestedTensorCompositeImplicitAutogradAutogradOther _dispatch_autogradother_backendsrA   AutogradFuncTorchBatchedDecomposition_dispatch_has_backend_fallbackr(   )rZ   r/   candhas_backend_kernelr   r   r   resolve_key   sV   


rj   HigherOrderOperator_higher_order_opsc                       s   e Zd Zdd fdd
Zdeee eej e	e
f deeeef geeef f f fddZed	d
 Zdd Zdd Zdd Zejdd Zdd Zdd Z  ZS )rk   F)	cacheablec                   sh   t    t| tu rtd|| _|| _| t|< d| _d| _	|| _
tj | _tD ]}| | q*d S )NzODirect instantiation of HigherOrderOperator is not allowed. Please subclass it.higher_ordertorch.ops.higher_order)superr%   rY   rk   rA   _namerU   rl   _nsrV   
_cacheabler2   r3   _dispatch_keyset_fullnon_fallthrough_keys2_HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYSfallthrough)r$   rB   rm   dispatch_key	__class__r   r   r%     s   
zHigherOrderOperator.__init__r/   r8   c                    s0   t |tr| j|s| j|| _t |S r   )r?   r   ru   r5   addrp   rE   r.   ry   r   r   rE   (  s   	zHigherOrderOperator.py_implc                 C      | j S r   )rr   r#   r   r   r   	namespace5     zHigherOrderOperator.namespacec                 C   r|   r   )rs   r#   r   r   r   rm   9     zHigherOrderOperator.cacheablec                 C   s   | j || _ d S r   )ru   remove)r$   rx   r   r   r   rw   <     zHigherOrderOperator.fallthroughc                   sn  ddl m} || jv r| j| }t|trJ ||i |S |tjkr)t| ||S |tjkrg dd   fdd}g || R D ]}|| t|t	t
fr[|D ]}|| qTqEt
}	ddl m}
 | }|d urt|| jv r| jt| }|
 }||g|R i |}W d    n1 sw   Y  ntd| j d	| d
|tur|S |	D ]V}t|}|jtjjkrq|tjjju rtjjj}| j| }||jg|R i |}|  S || jv r| j| }||i |}ntd| j d| d
|tur|  S qtd| j d| ddd |	D  tj|}|tjkr{ddl m}
 t dkr{tjtjs{t }|d usDJ dt|| jv sTJ d| d| jt| }|
|}||g|R i |W  d    S 1 svw   Y  t | |}|| j!vrtd| j d| d| d|tjkr| j!| | j|< | j!| }t|trJ ||i |S )Nr   _get_current_dispatch_modec                 S   s   t j| dS )Nr@   )r2   r3   _dispatch_keysr5   )tensorr   r   r   has_python_keyR  r   z4HigherOrderOperator.dispatch.<locals>.has_python_keyc                    s*   t | tjr | r|  d S d S d S r   )r?   r2   r=   append)argr   overloaded_args_listr   r   check_overloadedU  s   z6HigherOrderOperator.dispatch.<locals>.check_overloaded)_pop_mode_temporarilyz%There was no rule registered for HOP z
 and mode z. We recommend filing an issue.z and subclass zMultiple dispatch failed for zl. There was no registered that did not return NotImplemented. Use HOP.py_impl to register some. Tried mode: z) and subclasses: c                 S   s   g | ]}t |qS r   )rY   ).0ar   r   r   
<listcomp>  s    z0HigherOrderOperator.dispatch.<locals>.<listcomp>zIIllegal invocation of dispatch on DispatchKey.PreDispatch without a mode.zCurrent active mode z not registeredz.could not find kernel for HigherOrderOperator r[   z (resolved from ))"torch.utils._python_dispatchr   r   r?   r   FuncTorchDynamicLayerFrontModer   r@   valueslisttupler   rY   r!   r(   rq   NotImplemented__torch_dispatch__r2   r3   _disabled_torch_dispatch_impl_subclassesfake_tensor
FakeTensorFakeTensorMode	fake_mode	TypeError_to_functionality_keyPreDispatch&_len_torch_dispatch_stack_pre_dispatch&_dispatch_tls_is_dispatch_key_excluded'_get_current_dispatch_mode_pre_dispatchrj   r    )r$   rx   r*   r+   r   kernelr   r   r   overloaded_argsr   	curr_modehandlerrL   resultsubclass_typefunctionality_key	final_keyr   r   r   dispatchA  s   











"

	
zHigherOrderOperator.dispatchc                   s    fdd}| S )Nc                     s\   t  } tj| rtjj| g R i S t j}j| g R i S r   )	_to_flat_tupler2   	overrideshas_torch_functionhandle_torch_function_compute_keysetru   r   highestPriorityTypeId)	flat_argsdispatch_key_setr*   r+   r$   r   r   wrapper  s"   
z-HigherOrderOperator.__call__.<locals>.wrapperr   )r$   r*   r+   r   r   r   r   r,     s   zHigherOrderOperator.__call__c                 C   s
   |    S r   )rB   r#   r   r   r   __str__  r1   zHigherOrderOperator.__str__c                 C   r|   r   rq   r#   r   r   r   rB     r   zHigherOrderOperator.name)rU   rV   rW   r%   r   rY   r   r2   r=   r   r   r   r   r   rE   propertyr}   rm   rw   r   abcabstractmethodr,   r   rB   __classcell__r   r   ry   r   rk     s.    
 	
c                 C   s   t j| i |S r   )pytreearg_tree_leavesrJ   r   r   r   r        r   c                 C   s   t | |}t||S r   )_get_tensorskey_extractor)r*   r+   ru   tensorsr   r   r   r        

r   c                 C   s    t | |}dd |D }t|S )Nc                 S   s   g | ]
}t |tjr|qS r   )r?   r2   r=   )r   tr   r   r   r     s    z _get_tensors.<locals>.<listcomp>)r   r   )r*   r+   flat_alltensor_argsr   r   r   r     s   
r   c                 C   s>   t j }| D ]
}|t j|B }q|t j  }||@ }|S r   )r2   r3   _dispatch_tls_local_include_setr   _dispatch_tls_local_exclude_set)r   key_maskkey_setr   r   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%     r   z&_ModeStackStateForPreDispatch.__init__c                 C   s    |t | jk s	J || j|< d S r   lenr   )r$   indexrL   r   r   r   set  s   z!_ModeStackStateForPreDispatch.setc                 C   s   |t | jk s	J | j| S r   r   )r$   r   r   r   r   get  s   
z!_ModeStackStateForPreDispatch.getc                 C   s"   t dd | jD t| jd u S )Nc                 S   s   g | ]}|d ur|qS r   r   )r   ir   r   r   r         z7_ModeStackStateForPreDispatch.count.<locals>.<listcomp>)r   r   intr   r#   r   r   r   count  s   z#_ModeStackStateForPreDispatch.countN)rU   rV   rW   r%   r   r   r   r   r   r   r   r     s
    r   Fc                    sp   t   d u stjjjtjjjfv sJ |rd u sJ  fdd}| }t }|dkr6tjtj	d |S )Nc                     sh   t jjjkr d} t dd  | S t jjjkr* d} t dd  | S t j} d t _| S Nr      )	r2   r3   _TorchDispatchModeKeyPROXYr   !mode_stack_state_for_pre_dispatchr   
FUNCTIONALr   )current_modecurrent_mode_stack_pre_dispatchmode_keyr   r   _unset_mode&  s   

z,unset_mode_pre_dispatch.<locals>._unset_moder   F)
r   r2   r3   r   r   r   r   '_dispatch_tls_set_dispatch_key_includedr   r   )r   schema_checkr   r   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sJ t }t| |r5t j	}|dkr0t
d| t _	n,t| |rNt d}|d u sFJ t d|  nt d}|d u sZJ t d|  |dkrotjtjd d S d S )Nr   )rG   )SchemaCheckMode)ProxyTorchDispatchModezYSchemaCheckMode for pre-dispatch must be used exclusively, found other modes on the stackr   T)rR   rG   #torch._subclasses.schema_check_moder   "torch.fx.experimental.proxy_tensorr   r?   r   r   r   AssertionErrorr   r   r2   r3   r   r   r   )rL   rG   r   r   previous_mode_stack_lenr   r   r   r   _set_mode_pre_dispatchA  s8   	


r   c                  C   sn   t  } t }|dkrtd| jd urtd ddS | dd ur'ttjjj	S | dd ur5ttjjj
S d S )Nr   zTrying to pop empty mode stackT)r   r   )r   r   r   r   r   r   r2   r3   r   r   r   )
mode_stackpre_dispatch_lenr   r   r   _pop_mode_from_pre_dispatchh  s   
r   c                   C   s
   t   S r   )r   r   r   r   r   r   r   w  r1   r   c                 C   sB   | t jjjt jjjfv sJ | t jjjkrt dS t dS r   )r2   r3   r   r   r   r   r   )r   r   r   r   _get_dispatch_mode_pre_dispatch{  s   
r   c                  C   sf   t  jd ur
t  jS t   } | dkrt  dS | dkr1t  dd ur+t  dS t  dS d S )N   r   r   )r   r   r   r   )	stack_lenr   r   r   r     s   


r   c                   C      t S r   )"_mode_stack_state_for_pre_dispatchr   r   r   r   r        r   
OpOverload
cached_opsc                 C   s   t |  d S r   )r   r{   )op_overloadr   r   r   add_cached_op  s   r   c                   C   s   t   d S r   )r   r>   r   r   r   r   reset_cached_ops  s   r   c                   C   r   r   )r   r   r   r   r   get_cached_ops  r   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d$d% Zed&d' Zed(d) Zed*d+ Z  ZS )-r   c                    s  t    || _|| _|| _|| _|| _|jdkrdn|j| _|r(t	j
j|v | _| jj| _|jr:|  jd|j 7  _| jjdd  d| j | _|j| _|j|_| j| _i | _d | _| jt	jjv | _d }| jjD ]}|jd u rrqj|d u r{|jj}qj|jjp|}qj|d uo| | _d S )N default.::r   )rp   r%   _op_op_dk_schema_overloadpacket_tagsoverload_name_overloadnamer2   Tagnondeterministic_seeded_nondeterministic_seededrB   rq   splitrU   rV   rW   __annotations___lazy_handlelibrary_defs_defined_in_python	arguments
alias_infois_writeis_view)r$   overloadpacketrZ   op_dkschematagsr  r   ry   r   r   r%     s8   

 

zOpOverload.__init__c                 C      | j jdd S Nr   r   r  rB   r
  r#   r   r   r   
_namespace     zOpOverload._namespacec                 C   r  )Nr   r   r  r#   r   r   r   _opname  r  zOpOverload._opnamec                 C   s(   | j d u rtj| jj| jj| _ | j S r   )r  r2   r3   _dispatch_find_schema_or_throwr  rB   r  r#   r   r   r   _handle  s
   
zOpOverload._handleNc                 C      | S r   r   r$   memor   r   r   __deepcopy__  r-   zOpOverload.__deepcopy__c                 C       dj g | jjd| jR  S )Nz'<OpOverload(op='{}.{}', overload='{}')>r   formatr  rB   r
  r  r#   r   r   r   __repr__  s
   zOpOverload.__repr__c                O   s   | j |i |S r   r   r)   r   r   r   r,     r   zOpOverload.__call__c                O   s   | j j|g|R i |S r   )r  redispatch_boxed)r$   keysetr*   r+   r   r   r   
redispatch  s   zOpOverload.redispatchc                 C   
   t | jS r   hashr   r#   r   r   r   __hash__  r1   zOpOverload.__hash__c                 C   r$  )Nz{}.{}.{}r   r%  r#   r   r   r   r     s    zOpOverload.__str__c                    s   t  |ptj|  |S r   )rp   r0   r2   r3   %_dispatch_has_kernel_for_dispatch_keyrB   r.   ry   r   r   r0     s
   z&OpOverload.has_kernel_for_dispatch_keyc                    s   t j|  |pt |S r   )r2   r3   )_dispatch_has_kernel_for_any_dispatch_keyrB   rp   r7   )r$   r6   ry   r   r   r7     s
   
z*OpOverload.has_kernel_for_any_dispatch_keyc                 C   r  r  r  r#   r   r   r   r}     r  zOpOverload.namespacec                 C   s"   t j}|| jv ptj|  |S r   )r   rb   r    r2   r3   r0  rB   )r$   dkr   r   r   _can_decompose  s   zOpOverload._can_decomposec                 O   sR   t j}|| jv r| j| |i |S tj|  |r'| j|g|R i |S tS r   )	r   rb   r    r2   r3   r0  rB   r  r   )r$   r*   r+   r2  r   r   r   	decompose  s   
zOpOverload.decomposec                 C   s   | j |d  d S r   )r   pop)r$   keyr   r   r   _uncache_dispatch+  r   zOpOverload._uncache_dispatchc           	         s6   j vsJ  d   tjkr8tts&js& j  < t  S  fdd}|j  < t |S tj	 }|tj
krYt }|dkrYtjtjsYfdd}|S t } tj
k} tjkrdd lm  m} |jr||}|r|j  < t |S j||}|r|j  < t |S )N c                     s   ddl m} t| }|d usJ d|jvrOttrCtjj	 }tj
jj|g| R i |W  d    S 1 s=w   Y  nj g| R i |S tjj	 }j| |g| R i |W  d    S 1 snw   Y  d S )Nr   r   zDIllegal invocation of dispatch on DispatchKey.Python without a mode.)r   r   rY   r!   r?   TorchBindOpOverloadr2   utils_python_dispatchr   _libraryhandle_dispatch_moder  )r*   r+   r   r   rL   r6  r$   r   r   r   9  s,   




"$z)OpOverload._get_dispatch.<locals>.handlerr   c                     sV   t jdd }| }tjjj| g| R i |W  d    S 1 s$w   Y  d S )Nc                  s   s(    t  } z
| V  W t|  d S t|  w r   )r   r   )top_moder   r   r   (_temporarily_pop_modes_from_pre_dispatchb  s
   z[OpOverload._get_dispatch.<locals>.handler.<locals>._temporarily_pop_modes_from_pre_dispatch)
contextlibcontextmanagerr2   r<  r:  r=  )r*   r+   r@  r   r#   r   r   r   a  s   
$)r   r   r@   r?   r9  r!   r   r2   r3   r   r   r   r   rj   rS   torch._dispatch.python	_dispatchpythonCROSSREF_FUNCTIONALIZEmake_crossref_functionalizer    r   )	r$   r6  r   r   curr_stack_lenr   cache_result
pydispatchrr   r>  r   _get_dispatch/  sF   








zOpOverload._get_dispatchc                 C   r|   r   r   r#   r   r   r   rB     r   zOpOverload.namec                 C   r|   r   )r  r#   r   r   r   r    r~   zOpOverload.overloadpacketc                 C   r|   r   r(  r#   r   r   r   rZ     r~   zOpOverload.opc                 C   r|   r   )r  r#   r   r   r   r    r~   zOpOverload.tagsr   )rU   rV   rW   r%   r   r  r  r  r#  r'  r,   r+  r/  r   r0   r7   r}   r3  r4  r7  rL  rB   r  rZ   r  r   r   r   ry   r   r     s:    (




_

c                   @   s<   e Zd Zdee fddZejdd Zdd Z	dd	 Z
d
S )r9  r8   c                    sD   t jt jt jt jt jt jt jg}dt ffdd  fdd|D S )Nr6  c                    s@   t j  | rt j  | S |  jvp j|  t jju S r   )r2   r3   r0  rB   0_dispatch_kernel_for_dispatch_key_is_fallthroughr    r  fallthrough_kernel)r6  r#   r   r   (_may_use_fallthrough_instead_of_fallback  s   
zWTorchBindOpOverload._fallthrough_keys.<locals>._may_use_fallthrough_instead_of_fallbackc                    s   g | ]} |r|qS r   r   )r   r6  )rO  r   r   r     s    z9TorchBindOpOverload._fallthrough_keys.<locals>.<listcomp>)r   re   AutogradCPUAutogradCUDAADInplaceOrViewBackendSelectPythonTLSSnapshotPythonDispatcher)r$   _DEFAULT_FALLTHROUGH_KEYSr   )rO  r$   r   _fallthrough_keys  s   

z%TorchBindOpOverload._fallthrough_keysc                 c   sZ    ddl m}m}m} z| |vr|| |j d V  W | |v r#|| = d S d S | |v r,|| = w )Nr   )_EffectType_register_effectful_opSIDE_EFFECTS)torch._higher_order_ops.effectsrX  rY  rZ  ORDERED)r$   rX  rY  rZ  r   r   r   %_register_as_effectful_op_temporarily  s   
z9TorchBindOpOverload._register_as_effectful_op_temporarilyc                O   sT   t ||r"|   | |||  W  d    S 1 sw   Y  | j|i |S r   )_must_dispatch_in_pythonr]  _dispatch_in_pythonrW  r   r)   r   r   r   r,     s
   

 zTorchBindOpOverload.__call__c           	      C   s   t j }|D ]}||}qt|||}| }|| jvr#| |n| j| }t|t	rNt j
|  |r@| ||||g S td|  d| d| dt|tsUJ ||i |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.)r2   r3   rt   r   r   r   r   rL  r?   r   rM  rB   r_  rA   r   )	r$   r*   r+   fallthrough_keysru   r6  r   rx   r   r   r   r   r_    s.   




z'TorchBindOpOverload._dispatch_in_pythonN)rU   rV   rW   r   r   rW  rA  rB  r]  r,   r_  r   r   r   r   r9    s    
r9  c                 C   s   t dd | |fS )Nc                 S   s   t | tjjjS r   )r?   r2   r<  fake_class_registryFakeScriptObject)objr   r   r   <lambda>  s    
z*_must_dispatch_in_python.<locals>.<lambda>)r   tree_anyrJ   r   r   r   r^    s   r^  r  r8   c                 C   s   t dd | jD S )Nc                 s   s    | ]
}t |jtjV  qd S r   )r?   rY   r2   	ClassType)r   r   r   r   r   	<genexpr>  s    z)_has_script_object_arg.<locals>.<genexpr>)anyr  )r  r   r   r   _has_script_object_arg  s   ri  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   )ri  )r   r  r   r   r   rg  #  s    
z,OpOverloadPacket.__init__.<locals>.<genexpr>)	_qualified_op_namerU   r   _overload_names_dirrh  _schemasr   _has_torchbind_op_overload)r$   qualified_op_nameop_namerZ   overload_namesr   r   r   r%     s   zOpOverloadPacket.__init__Nc                 C   r   r   r   r!  r   r   r   r#  (  r-   zOpOverloadPacket.__deepcopy__c                 C      dj | jd S )Nz<OpOverloadPacket(op='{}.{}')>r   r&  rk  r
  r#   r   r   r   r'  +  s   
zOpOverloadPacket.__repr__c                 C   r,  r   r-  r#   r   r   r   r/  0  r1   zOpOverloadPacket.__hash__c                 C   rs  )Nz{}.{}r   rt  r#   r   r   r   r   3  r   zOpOverloadPacket.__str__c                 C   r|   r   r(  r#   r   r   r   rZ   6  r~   zOpOverloadPacket.opc                    s    fdd j D S )Nc                    s   i | ]}|t j j|qS r   )r2   r3   _get_schemark  )r   r  r#   r   r   
<dictcomp><  s    z-OpOverloadPacket._schemas.<locals>.<dictcomp>rl  r#   r   r#   r   rn  :  s   
zOpOverloadPacket._schemasc           	      C   s.  |dkrdS z| drt| j|W S W n ty/   tdt|  dt| j d| dd w zQ|dkr7d	n|}tj| j|}|d u rRtd
t|  d| d|\}}}tj	| j|}t
|skt| ||||nt| ||||}t| || | j| |W S  ty   td
t|  d| dd w )N__file__	torch.ops__'zH' can't have an overload name beginning with '__' and the underlying op z has no attribute z either.r   r   zThe underlying op of 'z' has no overload name ')
startswithgetattrr   AttributeErrorstrr2   r3   _get_operation_overloadrk  ru  ri  r   r9  setattrrm  r   rA   )	r$   r6  use_key
op_dk_tagsop_op_dk_r  r  overloadr   r   r   __getattr__A  sT   	


zOpOverloadPacket.__getattr__c                 C   r,  r   iterrm  r#   r   r   r   __iter__v  r1   zOpOverloadPacket.__iter__c                O   s0   | j rt||rt| ||S | j|i |pi S r   )ro  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     r   z.OpOverloadPacket.overloads.<locals>.<listcomp>rw  r#   r   r   r   	overloads  r   zOpOverloadPacket.overloadsr   )rU   rV   rW   r%   r#  r'  r/  r   r   rZ   rn  r  r  r,   r  r   r   r   r   rj    s    


5rj  c                 C   s   t jj| g|R i |\}}|r|S i }d }|  D ]0}t| |}zt jj|jg|R i |}	|}W  n tyK }
 z
|
||< W Y d }
~
qd }
~
ww |rU||i |S d|  d}| D ]\}}|d| d| d7 }q_t|)Nz'Fail to match any TorchBindOverload of z with following exceptions:
zOverload name z:
 
)	r2   r3   (_maybe_call_torch_function_for_op_packetr  r}  &_check_schema_allow_fake_script_objectr  rA   items)rZ   r*   r+   torch_function_calledret
exceptionsfound_opr  r   _eerr_msgr6  msgr   r   r   r    sD   


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.)rp   r%   rB   rm  )r$   rB   ry   r   r   r%     s   
z_OpNamespace.__init__c                 C   r,  r   r  r#   r   r   r   r    r1   z_OpNamespace.__iter__c           	   
   C   s   |dkrdS |dv rt d| d| j d| j}| d| }| jd | }zt||\}}|d u r?t d	| j d
| dW n tyY } zt d	| j d
| d|d }~ww ||_t||||}| jd | |_t| || | j| |S )Nrx  ry  )
__origin____self__zInvalid attribute 'z' for '_OpNamespace' 'r{  r   r   z'_OpNamespace' '' object has no attribute ')	r~  rB   rV   _get_packetrA   rj  r  rm  r   )	r$   rq  namespace_namerp  module_namerZ   rr  r  opoverloadpacketr   r   r   r    s@   z_OpNamespace.__getattr__)rU   rV   rW   rX   r%   r  r  r   r   r   ry   r   r    s
    r  c                 C   s6   t j| \}}|d urt jj||  ||_||fS r   )r2   r3   _jit_get_operationjit	_builtins_register_builtinrV   )qualname	op_modulerZ   rr  r   r   r   r  	  s
   r  c                 C   s0   t | j| jj\}}|d usJ || _|| _d S r   )r  rk  r   rV   rl  )packetrZ   rr  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   )rp   r%   _ops)r$   rB   opsry   r   r   r%     s   
z_PyOpNamespace.__init__c                 C   s>   | j |d }|d u rtd| j d| dt| || |S )Nz'_PyOpNamespace' 'r  r{  )r  r   r~  rB   r  )r$   rB   rZ   r   r   r   r    s   z_PyOpNamespace.__getattr__)rU   rV   rW   r%   r  r   r   r   ry   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 )Nry  ro   )rp   r%   r   loaded_librariesr  rl   _higher_order_op_namespacerm  r#   ry   r   r   r%   -  s   
z_Ops.__init__c                 C   s2   |dkr| j S t|}t| || | j| |S )Nrn   )r  r  r  rm  r   )r$   rB   r}   r   r   r   r  5  s   z_Ops.__getattr__c                 C   r,  r   r  r#   r   r   r   r  @  r1   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   r  C  s   z_Ops.import_modulec                 C   sV   t  rdS t|}t  t| W d   n1 sw   Y  | 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)	r2   _running_with_deployr
   resolve_library_pathr   r   CDLLr  r{   )r$   pathr   r   r   load_libraryV  s   
z_Ops.load_library)
rU   rV   rW   rx  r%   r  r  r  r  r   r   r   ry   r   r  *  s    r  r  )F)Xr   rA  r   r  r:   r   typestypingr   r   r   r   r   r   typing_extensionsr   r	   r2   torch.utils._pytreer:  _pytreer   r
   torch._Cr   r^   r   torch._functorch.pyfunctorchr   r   r   r   rR   r   r   r   hasattrr   rB  r   r   rj   rl   dictr  r  rU  rT  rR  rS  AutocastCPUAutocastCUDArv   ABCrk   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r9  r^  FunctionSchemaboolri  rj  r  
ModuleTyper  r  r  r  r  r  r   r   r   r   <module>   s   
 
 5
 [
$' vg	u5E
K