a
    df;                     @   s  d dl Z d dlmZ d dlmZmZmZmZ d dlm	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Z
d dlZ
d dlmZ d dlmZ d dlmZ e ddd	 Ze dd
d ZG dd de
jjZG dd de
jjZdd ZddddZ G dd deZ!dS )    N)nullcontext)AnyCallableDictSequence)warn)NvfuserPrimOperatorSupport)torch_function_passthrough)get_isolated_graphmodulec               *   C   s   t t jft jt jjft jjt jjjft jt jjft jt jjft jt jjfg} t jjt jj	t jj
t jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jjt jj t jj t jj!t jj!t jj"t jj"t jj#t jj#t jj$t jj$t jj%t jj%t jj&t j'j(t jj)t j'j)i}| D ]0\}}|j*D ]}|j+,|||j+,|< q^qPt-t jD ].}|t jj*v rt jj+,||t.t j|< qt jj/j*D ]4}t.t j|dpt.t |}t jj/j+,|||< q|S )z}
    Mapping of torch API functions to torch._refs functions.
    E.g. torch_to_refs_map()[torch.add] == torch._refs.add
    N)0torchZ_refsnnZ
functionalZspecialZfftZlinalgZTensor
__invert__Zbitwise_not__xor__Zbitwise_xor__and__Zbitwise_and__or__Z
bitwise_or__eq__eq__rsub__Zrsub__rtruediv__Zrtruediv__floordiv__Zfloor_divide__rfloordiv__Z	rfloordiv__pow__pow__rpow__ZrpowZ	new_emptyZnew_full	new_zerosZnew_onesZfill_Zzero_toZsum_to_sizeZcopy__primsZcopy_toresize__all____dict__getdirgetattrZ_conversions)modulesrZ	mod_torchZmod_refssZtensor_attr r&   ]/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torch/_prims/context.pytorch_to_refs_map   sN    	
 r(   c                   C   s   dd t jjD S )zJ
    Set of all prim functions, e.g., torch._prims.add in all_prims()
    c                 S   s   h | ]}t jj|qS r&   )r   r   r   r    ).0r%   r&   r&   r'   	<setcomp>R       zall_prims.<locals>.<setcomp>)r   r   r   r&   r&   r&   r'   	all_primsM   s    r,   c                   @   s8   e Zd ZdZddddZd
eeee eddd	Z	dS )NvfuserPrimsModea`  
    Switches the interpretation of torch.ops.prims.* functions to
    use nvFuser's prims in torch.ops.nvprims.*

    >>> # xdoctest: +SKIP("undefined vars")
    >>> with NvfuserPrimsMode():
    ...     torch.ops.prims.add(x, y)  # calls torch.ops.nvprims.add(x, y)

    By default, this context manager will fall back on the torch.ops.prims* if the
    nvprim does not exist.
    It's possible to skip certain prims by passing their names to the skip_ops
    argument. skip_ops is expected to be a sequence of strings, e.g.,
    ["prims.add.default"] In order to check the expected name of a prim, one can
    use the `torch.overrides.resolve_name`.

    >>> # xdoctest: +SKIP("undefined vars")
    >>> with NvfuserPrimsMode(skips_ops=("prims.add.default")):
    ...     torch.ops.prims.add.default(x, y)  # does not call torch.ops.nvprims.add.default(x, y)
    r&   skip_opsc                C   s
   || _ d S Nr.   )selfr/   r&   r&   r'   __init__j   s    zNvfuserPrimsMode.__init__N	orig_functypesargskwargsc                 C   s   |d u ri }t j|| jv r,||i |S t|t jjt jjfrt|	dd }t|	dd }|dkrt
t jj|d }|d ur||i |S ||i |S )N.r      Zprims)r   	overridesresolve_namer/   
isinstance_ops
OpOverloadOpOverloadPacketstrsplitr"   opsnvprims)r1   r4   r5   r6   r7   	namespacenameZnvfuncr&   r&   r'   __torch_function__m   s    z#NvfuserPrimsMode.__torch_function__)r&   N)
__name__
__module____qualname____doc__r2   r   r   r   r   rF   r&   r&   r&   r'   r-   U   s     r-   c                   @   s>   e Zd ZdZddd efddZdeeee e	d	d
dZ
dS )TorchRefsModeaB  
    Switches the interpretation of torch.* functions and Tensor methods to
    use PrimTorch refs in torch._refs.  (Direct calls to _refs are unaffected.)

    >>> # xdoctest: +SKIP
    >>> with TorchRefsMode():
    ...     torch.add(x, y)  # calls torch._refs.add(x, y)

    By default, this context manager will fall back on the torch.* if the
    ref does not exist; set strict=True to error if this occurs.
    If the ref exists we still would like to fall back on the torch.* sometimes,
    this behavior can be customized by passing a function to should_fallback_fn.
    Fc                  G   s   dS )NFr&   )_r&   r&   r'   <lambda>   r+   zTorchRefsMode.<lambda>c                 C   s   || _ || _|| _d S r0   strictshould_fallback_fnprims_mode_cls)r1   rO   rP   rQ   r&   r&   r'   r2      s    zTorchRefsMode.__init__r&   Nr3   c                 C   s  |d u ri }|t v s|t v rT|   ||i |W  d    S 1 sJ0    Y  t }||d }|d u rt|tjjrtj	j
|d }|d u r| | ||||r||i |S |  ||i |W  d    S 1 s0    Y  | jrtdtj| ||i |S )Nzno _refs support for )r	   r,   rQ   r(   r    r<   r   r=   r>   _decompdecomposition_tablerP   rO   RuntimeErrorr:   r;   )r1   r4   r5   r6   r7   mappingfuncr&   r&   r'   rF      s&    
,
,z TorchRefsMode.__torch_function__)r&   N)rG   rH   rI   rJ   r   r2   r   r   r   r   rF   r&   r&   r&   r'   rK      s   
  rK   c                 C   s   | j dkot| jdd d uS )Ncall_functionZimpl_nvfuser)opr"   target)noder&   r&   r'   _is_node_supported_nvfuser   s    
r[   r&   r.   c          
         s   t j||v rdS | n zt|||}W nL tyv } z4td|j d t|  W Y d}~W d   dS d}~0 0 W d   n1 s0    Y  t  t	dd |j
j}t fdd|D }	|	S )	a  
    This function traces the `func` under `torch_function_mode` and checks if
    any of the traced nodes are not supported by nvFuser. If so, we should
    fallback to the original function.

    `skip_ops` argument is expected to be a list of strings of function names
    that would match with `torch.overrides.resolve_name`.

    Args:
        torch_function_mode: The torch_function_mode context manager. orig_func:
        The original function, its name will be used to check if
                   it should be skipped.
        func: The function to be traced. args: The args to be passed to the
        function. kwargs: The kwargs to be passed to the function.
    Keyword args:
        skip_ops: A list of ops to skip when checking if the function is
        supported.
    Tz2get_isolated_graphmodule failed on decomposition: z with error message: Nc                 S   s
   | j dkS )NrW   )rX   )nr&   r&   r'   rM      r+   z._is_func_unsupported_nvfuser.<locals>.<lambda>c                 3   s   | ]}  d | V  qd S r0   )Zis_node_supported)r)   rZ   Zsupported_opsr&   r'   	<genexpr>   s   z/_is_func_unsupported_nvfuser.<locals>.<genexpr>)r   r:   r;   r
   	Exceptionr   rG   r@   r   filtergraphnodesany)
Ztorch_function_moder4   rV   r6   r7   r/   ZgmeZcall_function_nodesZany_unsupportedr&   r]   r'   _is_func_unsupported_nvfuser   s,    Bre   c                       sx   e Zd Zdd fdd
Zdd Zdd Zd	d
 Zdd Zdd Zdd Z	dd Z
deeee ed fddZ  ZS )TorchRefsNvfuserCapabilityModer&   r.   c                   sD   d}t || | _t jdtjtt || dtjt|dd d S )N)zaten._log_softmax.defaultz'aten._log_softmax_backward_data.defaultzaten.expand.defaultFr.   rN   )tupler/   superr2   	functoolspartialre   r-   )r1   r/   Zaten_ops_to_skip	__class__r&   r'   r2      s    
z'TorchRefsNvfuserCapabilityMode.__init__c	              
   C   sb   t jj||||||||\}	}
}|r>|	|
||jdt jdfS |	|d|d|jdt jdfS )N)r   )Zdtype)r   rB   rC   native_batch_normr   Zuint8)r1   inputweightZbiasrunning_meanrunning_varZtrainingZexponential_average_factorepsilonabcr&   r&   r'   _cudnn_batch_norm  s"    

z0TorchRefsNvfuserCapabilityMode._cudnn_batch_normc
                 C   s2   t jjt jjjj }
|
|||||||d|g d
S )NT)TTT)r   rR   rS   rB   atenZnative_batch_norm_backwarddefault)r1   rn   Zgrad_outputro   rp   rq   Z	save_meanZsave_varrr   ZreserveSpacerV   r&   r&   r'   _cudnn_batch_norm_backward0  s    
z9TorchRefsNvfuserCapabilityMode._cudnn_batch_norm_backwardc                 C   s2   dt j|kp0t|t jjt jjfo0dt|v S )Nztorch.var_meanzaten.var_mean)r   r:   r;   r<   r=   r>   r?   r@   r1   rV   r&   r&   r'   _is_var_meanL  s    
z+TorchRefsNvfuserCapabilityMode._is_var_meanc                 C   s"   h dt | j }tj||v S )N>   ztorch.view_copyztorch.Tensor.reshapeztorch.Tensor.viewzaten.view_copy.defaultztorch.reshapezaten._unsafe_view.defaultzaten.view.default)setr/   r   r:   r;   )r1   rV   Zallowed_opsr&   r&   r'   _is_view_or_reshapeR  s    	z2TorchRefsNvfuserCapabilityMode._is_view_or_reshapec                 C   s.   dt j|kp,|t jjjjkp,|t jjjkS )Nztorch.native_batch_norm)r   r:   r;   rB   rw   rm   rx   rz   r&   r&   r'   _is_native_batch_norm^  s    z4TorchRefsNvfuserCapabilityMode._is_native_batch_normc                 C   s2   dt j|kp,|t jjjkp,|t jjjjk}|S )Nztorch.rand_like)r   r:   r;   rB   rw   	rand_likerx   r1   rV   resultr&   r&   r'   _is_rand_liked  s    z,TorchRefsNvfuserCapabilityMode._is_rand_likec                 C   s.   dt j|kp(|t jjjt jjjjfv }|S )Nz
torch.full)r   r:   r;   rB   rw   fullnamesr   r&   r&   r'   _is_fullj  s    
z'TorchRefsNvfuserCapabilityMode._is_fullNr3   c                    s  |d u ri }|  |r*tjjj|i |S |tjjjjksH|tjjjkr||   | j|i |W  d    S 1 sr0    Y  |tjjj	jks|tjjj	kr|   | j
|i |W  d    S 1 s0    Y  | |r|^}}tjj|dd}t|dkrtd tjj||S |tjjjjkrZ|\}}}t|dkrJtd tjj||S | |rztjjj|i |S | |rt|dkrtd tjjj| S | |rtjjj|i |S t ||||S )NF)validater   zview has ignored kwargs!zrand_like has ignored kwargs!)r{   r   rB   rC   Zvar_meanrw   Zcudnn_batch_normrx   rv   Zcudnn_batch_norm_backwardry   r}   Z_prims_commonZextract_shape_from_varargslenr   viewZ_reshape_aliasr~   rm   r   r   r   r   rh   rF   )r1   r4   r5   r6   r7   rs   shapeZstriderk   r&   r'   rF   t  sL    
..
z1TorchRefsNvfuserCapabilityMode.__torch_function__)r&   N)rG   rH   rI   r2   rv   ry   r{   r}   r~   r   r   r   r   r   r   rF   __classcell__r&   r&   rk   r'   rf      s      rf   )"ri   
contextlibr   typingr   r   r   r   warningsr   r   Ztorch._decompZtorch._primsZtorch._refsZtorch._refs.nnZtorch._refs.nn.functionalZtorch._refs.specialZtorch.overridesZtorch._prims.nvfuser_executorr   Ztorch._prims_commonr	   Z"torch.fx.experimental.proxy_tensorr
   	lru_cacher(   r,   r:   ZTorchFunctionModer-   rK   r[   re   rf   r&   r&   r&   r'   <module>   s0   
6
1A/