U
    yh8                     @   s
  d dl Z d dlmZ d dlmZ d dlZdddddd	d
ddddddddddddddgZdd ZG dd dZG dd dZ	G dd dZ
G dd dZejjjejjjejjjdZde Zd8edeejjf ejjd d!d	Zejjjejjjejjjd"Zde Zd9edeejjf ejjd d#d
Zd d$lmZm Z! d%e_"de_#d&d Z$e%d'd(dZ&d)d Z'e%d'd*dZ(d+d Z)e%d'd,dZ*d:ee%e%d.d/dZ+d;ee%e%d.d0dZ,d1d Z-e%d'd2dZ.e j/ed3e0d4d<e%e%e%e%d6d7dZ1e
 Z2e Z3dS )=    N)Union)
deprecatedis_builtcuFFTPlanCacheAttrContextPropcuFFTPlanCachecuFFTPlanCacheManagercuBLASModulepreferred_linalg_librarypreferred_blas_librarycufft_plan_cachematmul
SDPAParamsenable_cudnn_sdpcudnn_sdp_enabledenable_flash_sdpflash_sdp_enabledenable_mem_efficient_sdpmem_efficient_sdp_enabledmath_sdp_enabledenable_math_sdpcan_use_flash_attentioncan_use_efficient_attention
sdp_kernelc                   C   s   t jjS )z
    Return whether PyTorch is built with CUDA support.

    Note that this doesn't necessarily mean CUDA is available; just that if this PyTorch
    binary were run on a machine with working CUDA drivers and devices, we would be able to use it.
    )torch_CZ	_has_cuda r   r   N/var/www/html/venv/lib/python3.8/site-packages/torch/backends/cuda/__init__.pyr   "   s    c                   @   s$   e Zd Zdd Zdd Zdd ZdS )r   c                 C   s   || _ || _d S N)gettersetter)selfr   r   r   r   r   __init__/   s    z&cuFFTPlanCacheAttrContextProp.__init__c                 C   s   |  |jS r   )r   device_index)r    objobjtyper   r   r   __get__3   s    z%cuFFTPlanCacheAttrContextProp.__get__c                 C   s(   t | jtrt| j| |j| d S r   )
isinstancer   strRuntimeErrorr"   )r    r#   valr   r   r   __set__6   s    
z%cuFFTPlanCacheAttrContextProp.__set__N)__name__
__module____qualname__r!   r%   r*   r   r   r   r   r   ,   s   c                   @   s:   e Zd ZdZdd ZeejdZeej	ej
Zdd ZdS )r   z
    Represent a specific plan cache for a specific `device_index`.

    The attributes `size` and `max_size`, and method `clear`, can fetch and/ or
    change properties of the C++ cuFFT plan cache.
    c                 C   s
   || _ d S r   )r"   )r    r"   r   r   r   r!   D   s    zcuFFTPlanCache.__init__z.size is a read-only property showing the number of plans currently in the cache. To change the cache capacity, set cufft_plan_cache.max_size.c                 C   s   t | jS r   )r   Z_cufft_clear_plan_cacher"   r    r   r   r   clearQ   s    zcuFFTPlanCache.clearN)r+   r,   r-   __doc__r!   r   r   Z_cufft_get_plan_cache_sizesizeZ_cufft_get_plan_cache_max_sizeZ_cufft_set_plan_cache_max_sizemax_sizer/   r   r   r   r   r   <   s    c                       s<   e Zd ZdZdZdd Zdd Zdd Z fd	d
Z  Z	S )r   a  
    Represent all cuFFT plan caches, return the cuFFTPlanCache for a given device when indexed.

    Finally, this object, when used directly as a `cuFFTPlanCache` object (e.g.,
    setting the `.max_size`) attribute, the current device's cuFFT plan cache is
    used.
    Fc                 C   s   g | _ d| _d S )NT)caches#_cuFFTPlanCacheManager__initializedr.   r   r   r   r!   `   s    zcuFFTPlanCacheManager.__init__c                 C   sv   t jj|}|dk s$|t j kr>tdt j  d| t| jdkrl| jdd t	t j D  | j| S )Nr   z/cufft_plan_cache: expected 0 <= device index < z, but got device with index c                 s   s   | ]}t |V  qd S r   )r   ).0indexr   r   r   	<genexpr>l   s    z4cuFFTPlanCacheManager.__getitem__.<locals>.<genexpr>)
r   cudaZ_utilsZ_get_device_indexZdevice_countr(   lenr3   extendrange)r    Zdevicer6   r   r   r   __getitem__d   s    z!cuFFTPlanCacheManager.__getitem__c                 C   s   t | tj  |S r   )getattrr   r8   current_devicer    namer   r   r   __getattr__q   s    z!cuFFTPlanCacheManager.__getattr__c                    s.   | j rt| tj  ||S t ||S d S r   )r4   setattrr   r8   r>   super__setattr__r    r@   value	__class__r   r   rD   t   s    z!cuFFTPlanCacheManager.__setattr__)
r+   r,   r-   r0   r4   r!   r<   rA   rD   __classcell__r   r   rG   r   r   U   s   c                   @   s   e Zd Zdd Zdd ZdS )r   c                 C   sF   |dkrt j S |dkr$t j S |dkr6t j S td| d S NZ
allow_tf32Z&allow_fp16_reduced_precision_reductionZ&allow_bf16_reduced_precision_reductionzUnknown attribute )r   r   Z_get_cublas_allow_tf32Z2_get_cublas_allow_fp16_reduced_precision_reductionZ2_get_cublas_allow_bf16_reduced_precision_reductionAttributeErrorr?   r   r   r   rA   |   s    


zcuBLASModule.__getattr__c                 C   sL   |dkrt j|S |dkr(t j|S |dkr<t j|S td| d S rJ   )r   r   Z_set_cublas_allow_tf32Z2_set_cublas_allow_fp16_reduced_precision_reductionZ2_set_cublas_allow_bf16_reduced_precision_reductionrK   rE   r   r   r   rD      s    zcuBLASModule.__setattr__N)r+   r,   r-   rA   rD   r   r   r   r   r   {   s   	)defaultZcusolverZmagmaz, )backendreturnc                 C   sl   | dkr
nXt | tr>| tkr,tdt dtjt|   n$t | tjjrZtj|  ntdtj	 S )af  
    Override the heuristic PyTorch uses to choose between cuSOLVER and MAGMA for CUDA linear algebra operations.

    .. warning:: This flag is experimental and subject to change.

    When PyTorch runs a CUDA linear algebra operation it often uses the cuSOLVER or MAGMA libraries,
    and if both are available it decides which to use with a heuristic.
    This flag (a :class:`str`) allows overriding those heuristics.

    * If `"cusolver"` is set then cuSOLVER will be used wherever possible.
    * If `"magma"` is set then MAGMA will be used wherever possible.
    * If `"default"` (the default) is set then heuristics will be used to pick between
      cuSOLVER and MAGMA if both are available.
    * When no input is given, this function returns the currently preferred library.
    * User may use the environment variable TORCH_LINALG_PREFER_CUSOLVER=1 to set the preferred library to cuSOLVER
      globally.
      This flag only sets the initial value of the preferred library and the preferred library
      may still be overridden by this function call later in your script.

    Note: When a library is preferred other libraries may still be used if the preferred library
    doesn't implement the operation(s) called.
    This flag may achieve better performance if PyTorch's heuristic library selection is incorrect
    for your application's inputs.

    Currently supported linalg operators:

    * :func:`torch.linalg.inv`
    * :func:`torch.linalg.inv_ex`
    * :func:`torch.linalg.cholesky`
    * :func:`torch.linalg.cholesky_ex`
    * :func:`torch.cholesky_solve`
    * :func:`torch.cholesky_inverse`
    * :func:`torch.linalg.lu_factor`
    * :func:`torch.linalg.lu`
    * :func:`torch.linalg.lu_solve`
    * :func:`torch.linalg.qr`
    * :func:`torch.linalg.eigh`
    * :func:`torch.linalg.eighvals`
    * :func:`torch.linalg.svd`
    * :func:`torch.linalg.svdvals`
    N"Unknown input value. Choose from: .Unknown input value type.)
r&   r'   _LinalgBackendsr(   _LinalgBackends_strr   r   Z_set_linalg_preferred_backend_LinalgBackendZ_get_linalg_preferred_backendrM   r   r   r   r	      s    ,

)ZcublasZcublasltZ	hipblasltc                 C   sl   | dkr
nXt | tr>| tkr,tdt dtjt|   n$t | tjjrZtj|  ntdtj	 S )a  
    Override the library PyTorch uses for BLAS operations. Choose between cuBLAS and cuBLASLt.

    .. warning:: This flag is experimental and subject to change.

    When PyTorch runs a CUDA BLAS operation it defaults to cuBLAS even if both cuBLAS and cuBLASLt are available.
    For PyTorch built for ROCm, hipBLAS and hipBLASLt may offer different performance.
    This flag (a :class:`str`) allows overriding which BLAS library to use.

    * If `"cublas"` is set then cuBLAS will be used wherever possible.
    * If `"cublaslt"` is set then cuBLASLt will be used wherever possible.
    * When no input is given, this function returns the currently preferred library.
    * User may use the environment variable TORCH_BLAS_PREFER_CUBLASLT=1 to set the preferred library to cuBLASLt
      globally.
      This flag only sets the initial value of the preferred library and the preferred library
      may still be overridden by this function call later in your script.

    Note: When a library is preferred other libraries may still be used if the preferred library
    doesn't implement the operation(s) called.
    This flag may achieve better performance if PyTorch's library selection is incorrect
    for your application's inputs.

    NrO   rP   rQ   )
r&   r'   _BlasBackendsr(   _BlasBackends_strr   r   Z_set_blas_preferred_backend_BlasBackendZ_get_blas_preferred_backendrU   r   r   r   r
      s    

)_SDPAParams_SDPBackendztorch.backends.cudac                   C   s
   t j S )z
    .. warning:: This flag is beta and subject to change.

    Returns whether flash scaled dot product attention is enabled or not.
    )r   r   Z_get_flash_sdp_enabledr   r   r   r   r     s    Zenabledc                 C   s   t j|  dS )z|
    .. warning:: This flag is beta and subject to change.

    Enables or disables flash scaled dot product attention.
    N)r   r   Z_set_sdp_use_flashr[   r   r   r   r     s    c                   C   s
   t j S )z
    .. warning:: This flag is beta and subject to change.

    Returns whether memory efficient scaled dot product attention is enabled or not.
    )r   r   Z_get_mem_efficient_sdp_enabledr   r   r   r   r     s    c                 C   s   t j|  dS )z
    .. warning:: This flag is beta and subject to change.

    Enables or disables memory efficient scaled dot product attention.
    N)r   r   Z_set_sdp_use_mem_efficientr[   r   r   r   r   '  s    c                   C   s
   t j S )z
    .. warning:: This flag is beta and subject to change.

    Returns whether math scaled dot product attention is enabled or not.
    )r   r   Z_get_math_sdp_enabledr   r   r   r   r   0  s    c                 C   s   t j|  dS )z{
    .. warning:: This flag is beta and subject to change.

    Enables or disables math scaled dot product attention.
    N)r   r   Z_set_sdp_use_mathr[   r   r   r   r   9  s    F)paramsdebugrN   c                 C   s   t j| |S )a  Check if FlashAttention can be utilized in scaled_dot_product_attention.

    Args:
        params: An instance of SDPAParams containing the tensors for query,
                key, value, an optional attention mask, dropout rate, and
                a flag indicating if the attention is causal.
        debug: Whether to logging.warn debug information as to why FlashAttention could not be run.
            Defaults to False.

    Returns:
        True if FlashAttention can be used with the given parameters; otherwise, False.

    Note:
        This function is dependent on a CUDA-enabled build of PyTorch. It will return False
        in non-CUDA environments.
    )r   r   Z_can_use_flash_attentionr\   r]   r   r   r   r   B  s    c                 C   s   t j| |S )a  Check if efficient_attention can be utilized in scaled_dot_product_attention.

    Args:
        params: An instance of SDPAParams containing the tensors for query,
                key, value, an optional attention mask, dropout rate, and
                a flag indicating if the attention is causal.
        debug: Whether to logging.warn with information as to why efficient_attention could not be run.
            Defaults to False.

    Returns:
        True if efficient_attention can be used with the given parameters; otherwise, False.

    Note:
        This function is dependent on a CUDA-enabled build of PyTorch. It will return False
        in non-CUDA environments.
    )r   r   Z _can_use_mem_efficient_attentionr^   r   r   r   r   V  s    c                   C   s
   t j S )z
    .. warning:: This flag is beta and subject to change.

    Returns whether cuDNN scaled dot product attention is enabled or not.
    )r   r   Z_get_cudnn_sdp_enabledr   r   r   r   r   j  s    c                 C   s   t j|  dS )z|
    .. warning:: This flag is beta and subject to change.

    Enables or disables cuDNN scaled dot product attention.
    N)r   r   Z_set_sdp_use_cudnnr[   r   r   r   r   s  s    z`torch.backends.cuda.sdp_kernel()` is deprecated. In the future, this context manager will be removed. Please see `torch.nn.attention.sdpa_kernel()` for the new context manager, with updated signature.)categoryT)enable_flashenable_mathenable_mem_efficientenable_cudnnc              	   c   sv   ddl m} g }| r |tj |r0|tj |r@|tj |rP|tj ||}z
|V  W 5 X W 5 Q R X dS )a  
    .. warning:: This flag is beta and subject to change.

    This context manager can be used to temporarily enable or disable any of the three backends for scaled dot product attention.
    Upon exiting the context manager, the previous state of the flags will be restored.
    r   )sdpa_kernelN)Ztorch.nn.attentionrd   append
SDPBackendZFLASH_ATTENTIONZEFFICIENT_ATTENTIONZMATHZCUDNN_ATTENTION)r`   ra   rb   rc   rd   Zbackend_listcontextr   r   r   r   |  s    

)N)N)F)F)TTTT)4
contextlibtypingr   typing_extensionsr   r   __all__r   r   r   r   r   r   rT   ZDefaultZCusolverZMagmarR   joinkeysrS   r'   r	   rX   ZCublasZCublasltrV   rW   r
   Ztorch._CrY   r   rZ   rf   r,   r+   r   boolr   r   r   r   r   r   r   r   r   contextmanagerFutureWarningr   r   r   r   r   r   r   <module>   s   
& = *								
    