U
    zhe?                     @   s|  U d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZ d dlZd dlZd dlmZmZmZ d dlmZ d dlmZ d	d
ddddgZeeZe	ee	ejjef f ed< ed Zed Z ed Z!dd Z"dd Z#d!dddddZ$d"eeejjef  ee	ejjef dddZ%e	ejjef eeeef  ddddZ&d dl'Zd dl(Ze	ejjef dd dZ)dS )#    N)defaultdict)wraps)chain)CallableDictListSequenceUnion)HigherOrderOperator
OpOverloadOpOverloadPacket)CustomOutParamAnnotation)_pytreedecomposition_table pre_autograd_decomposition_table
meta_tableregister_decompositionget_decompositionscore_aten_decompositionsglobal_decomposition_tablepost_autogradpre_autogradmetac                 C   s   g }t |tr|| |< dS t |tr0|| n,t |ts>t| D ]}|t|| qF|D ]2}|| krztd| t	j
| r`|| |< q`dS )z
    This is an internal API for adding an op to the decomposition table.

    If op is OpOverload, it will be added to the registry directly.
    If op is OpOverloadPacket, all the valid op_overloads in the packet will be added to the registry.
    Nzduplicate registrations for )
isinstancer
   r   appendr   AssertionError	overloadsgetattrRuntimeErrortorchZ_CZ_dispatch_has_kernelname)registryopfnr   olop_overload r&   H/var/www/html/venv/lib/python3.8/site-packages/torch/_decomp/__init__.py_add_op_to_registry#   s    

r(   c                    sl  j d}|sS t|dd tkrt}|jjtfdd}dd t	|j
D }tdd |j D |}tj||jd	|_d
d j  D |_ |D ]}|j|j |j< qj|_|S j td   rht fdd}tj tjjd |d}t}tdd |j D |f}tj||jd	|_dd j  D |_ |j|j |j< |S S )Nout
__origin__c                     sV   t fddD }|d d k t fdd|D s<t| d rLd n|iS )Nc                 3   s   | ]}  |d V  qd S Npop.0o)kwargsr&   r'   	<genexpr>P   s     z3_convert_out_params.<locals>._fn.<locals>.<genexpr>r   c                 3   s   | ]}|d k kV  qd S r+   r&   r.   )is_noner&   r'   r2   S   s     r)   )tupleallr   )argsr1   Z
out_kwargs)f	out_names)r3   r1   r'   _fnN   s    z _convert_out_params.<locals>._fnc                 S   s&   g | ]\}}t j|t jjd |dqS )Nkinddefault
annotation)inspect	ParameterKEYWORD_ONLY)r/   r0   tr&   r&   r'   
<listcomp>V   s   z'_convert_out_params.<locals>.<listcomp>c                 s   s   | ]\}}|d kr|V  qdS r)   Nr&   r/   kvr&   r&   r'   r2   `   s      z&_convert_out_params.<locals>.<genexpr>)
parametersreturn_annotationc                 S   s   i | ]\}}|d kr||qS r)   r&   rD   r&   r&   r'   
<dictcomp>e   s       z'_convert_out_params.<locals>.<dictcomp>c                     s   |  d }| |d|iS )Nr)   r,   )r6   r1   Z	out_kwarg)custom_out_param_namer7   r&   r'   r9   t   s    r:   c                 s   s   | ]\}}|d kr|V  qdS rC   r&   rD   r&   r&   r'   r2      s      c                 S   s   i | ]\}}|d kr||qS rI   r&   rD   r&   r&   r'   rJ      s       )__annotations__getr   r4   r>   	signaturerH   _fieldsr   zip__args__r   rG   items	Signature__signature__r=   r    Z!_torch_decompositions_out_wrapperr-   r   r?   r@   )r7   Zout_annotationsigr9   Z
out_paramsparamsr0   Z	out_paramr&   )rK   r7   r8   r'   _convert_out_params@   sX    


 
  rW   F)typeunsafec                   s*   dkst ttd fdd}|S )az  
    A decorator to register a function as a decomposition to the Python
    decomposition table.  Use it like this::

        @register_decomposition(torch.ops.aten.clamp_min)
        def clamp_min(x):
            return torch.clamp(self, min=min)

    If you are writing a new decomposition, consider contributing it
    directly to PyTorch in torch._decomp.decompositions.

    This API is experimental; we are almost certainly going to extend
    the API when we make decompositions eligible for use in transforms (e.g.,
    autograd) and not just backend tracing, where we then need to know if a
    decomposition can be used to simulate a transform.

    By default, we also will register it to the Meta key of dispatcher,
    and replace the c++ Meta implementation if there is already one.

    unsafe kwarg is for reuse of this function for registering non-function
    things
    >   r   r   r   )r#   returnc                    s>    }st   d kr t  fdd}t| |S )Nc                    s   t |   d S r+   )r(   )r"   )r#   r!   r&   r'   register   s    zIregister_decomposition.<locals>.decomposition_decorator.<locals>.register)rW   r   pytreeZ	tree_map_)r#   Zorig_fnr[   aten_opr!   rX   rY   )r#   r'   decomposition_decorator   s    z7register_decomposition.<locals>.decomposition_decorator)r   r   )r^   r!   rX   rY   r_   r&   r]   r'   r      s    )aten_opsrX   rZ   c                 C   s   |dkst t| }tt}|D ]"}t|ttfr ||j | q i }| D ]T}t|tr~||kr~|| D ]}|| ||< qjqLt|t	j
jrL||krL|| ||< qL|S )a,  
    Retrieve a dictionary of decompositions corresponding to the list of
    operator overloads and overload packets passed as input.  Overload
    packets will include all decomposed overloads in the packet.  If there is
    no decomposition for a requested operator, it is silently ignored.

    This API is experimental; we are almost certainly going to give an alternate,
    more recommended formulation, where a user provides the set of operators
    they know how to implement, and we provide decompositions for everything
    not in this set.
    >   r   r   r   )r   r   r   listr   r   r   Zoverloadpacketr   r   _opsOperatorBase)r`   rX   r!   Zpackets_to_overloadsopodecompositionsr"   r%   r&   r&   r'   r      s    )re   r`   rZ   c                 C   sT   |D ]J}t |tr8| D ]}t||}| |d qqt |tr| |d qdS )a=  
    Given a dictionary of decompositions obtained from get_decompositions(), removes
    operators associated with a list of operator overloads and overload packets passed
    as input. If the decomposition dictionary does not contain a decomposition that is
    specified to be removed, it is silently ignored.
    N)r   r   r   r   r-   r   )re   r`   r"   Zoverload_namerd   r&   r&   r'   remove_decompositions   s    



rf   )rZ   c                  C   sd  t jj} t| j| j| j| j| j| j	| j
| j| jj| jj| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j | j!| j"| j#| j$| j%| j&| j'| j(| j)| j*| j+| j,j| j-| j.| j/| j0| j1| j2| j3| j4| j5| j6| j7| j8| j9| j:| j;| j<| j=| j>| j?| j@| jA| jB| jC| jD| jE| jF| jG| jH| jI| jJ| jK| jL| jM| jN| jO| jP| jQ| jR| jS| jT| jU| jV| jW| jX| jY| jZ| j[| j\| j]| j^| j_| j`| jaj| jb| jc| jd| je| jf| jg| jh| ji| jj| jk| jl| jm| jn| jo| jp| jq| jr| js| jt| ju| jv| jw| jx| jy| jz| j{| j|| j}| j~| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| jj| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| j| jj| j| jj| jj| j| j| j| jj| jj| j| j| j| j| j| j| j| jj| j| j| j| j| j| j| j| j| jj| j| j| j| j| j| j| j| j| j| j| j| j| j| j| jgσS r+   )r   Zopsatenr   ZaddcdivZaddcdiv_ZaddcmulZaddcmul_addrZaffine_grid_generatorr5   ZaminmaxZaranger<   startZavg_pool2d_backwardZbaddbmmZbinary_cross_entropyZbinary_cross_entropy_backwardZ binary_cross_entropy_with_logitsZ
block_diagZceluZcelu_Z	clamp_maxZ	clamp_minZcol2imZcount_nonzeroZlinalg_crossZcudnn_batch_normZcudnn_batch_norm_backwardZmiopen_batch_norm_backwardZdeg2radZdeg2rad_detachZ
diag_embedZdiagonal_backwarddotZvdotZeluZelu_Zelu_backwardZ_embedding_bagZembedding_dense_backwardZ
empty_likeZ_euclidean_distZ	expand_aseyefillZfill_Zfloor_dividefracZfrac_Z_fused_moving_avg_obs_fq_helperZgelu_Zgelu_backwardZgluZglu_backwardZ
hardshrinkZhardsigmoidZhardsigmoid_Zhardsigmoid_backwardZ	hardswishZ
hardswish_Zhardswish_backwardZ	hardtanh_Zhardtanh_backwardZ	heavisideZ
heaviside_Z
huber_lossZhuber_loss_backwardZim2colZ	index_addZ
index_add_Z
index_copyZindex_copy_Z
index_fillZindex_fill_isinZisneginfZisposinfZl1_lossZ_lazy_cloneZ_test_parallel_materializeZleaky_relu_Zleaky_relu_backwardZlerpZlerp_ZlinspaceZ	logaddexpZ
logaddexp2ZlogitZlogit_Zlogit_backwardZlog_sigmoid_backwardZlog_sigmoid_forwardZ_log_softmax_backward_dataZlogspaceZ	logsumexpZmasked_fillZmasked_fill_ZmishZmish_Zmse_lossZmse_loss_backwardZmulti_margin_lossZmultilabel_margin_loss_forwardmvZmvlgammaZ	mvlgamma_ZnansumZ
nan_to_numZnan_to_num_ZnarrowZnative_batch_norm_backwardZnative_dropout_backwardZnative_group_norm_backwardZnative_layer_norm_backwardZ	new_emptyZnew_fullZnew_onesZ	new_zerosZnll_loss_backwardZnll_loss_forwardZnormZonesZ	ones_likeZpixel_shuffleZpixel_unshuffleZ_prelu_kernelZ_prelu_kernel_backwardZ_reshape_aliasZrad2degZrad2deg_Zreflection_pad1dZreflection_pad2dZreflection_pad3dZreplication_pad1dZreplication_pad2dZreplication_pad3dZrenormZrenorm_Z	resize_asZrollZrot90Zrrelu_with_noiseZrrelu_with_noise_ZrsubZ+_scaled_dot_product_flash_attention_for_cpuZselect_backwardZselect_scatterZsgnZsgn_Zsigmoid_backwardZsiluZsilu_Zsilu_backwardZsincZsinc_Zslice_backwardZsmooth_l1_lossZsmooth_l1_loss_backwardZsoft_margin_lossZsoft_margin_loss_backwardZ_softmax_backward_dataZsoftplusZsoftplus_backwardZ
softshrinkZspecial_entrZspecial_log_ndtrZspecial_xlog1pysplitZTensorZsplit_with_sizes_copyZsqueezedimZstdZstd_meanstacksumr)   rA   ZtakeZtanh_backward	thresholdZ
threshold_Zthreshold_backwardtraceZ	transposeintZtrilZtril_ZtriuZtriu_ZunbindZunfold_backwardZunfold_copyZ_unsafe_indexZunsafe_splitZunsafe_split_with_sizesZ_unsafe_viewZupsample_linear1dZupsample_bilinear2dZupsample_trilinear3dZupsample_nearest2d_backwardZview_as_complexZxlogyZxlogy_zeroZzero_ZzerosZ
zeros_likeZ
_chunk_catZ_weight_norm_interface)rg   r&   r&   r'   r      s    )N)r   )*r>   collectionsr   	functoolsr   	itertoolsr   typingr   r   r   r   r	   r   Ztorch.libraryZ
torch._opsr
   r   r   Ztorch._prims_commonr   Ztorch.utilsr   r\   __all__dictr   strrb   rc   rL   r   r   r   r(   rW   r   r   rf   Ztorch._decomp.decompositionsZtorch._refsr   r&   r&   r&   r'   <module>   sX    S  1 !