
    sg@@                        d dl Z d dlmZ d dlmZ d dlZg dZd Z G d d      Z G d d	      Z	 G d
 d      Z
 G d d      Zej                  j                  j                  ej                  j                  j                  ej                  j                  j                   dZdj%                  ej'                               Z	 d0dedeej                  j                  f   dej                  j                  fdZej                  j.                  j0                  ej                  j.                  j2                  ej                  j.                  j2                  dZdj%                  ej'                               Z	 d0dedeej                  j.                  f   dej                  j.                  fdZd dlmZm Z! de_"        de_#        d Z$de%fdZ&d Z'de%fdZ(d Z)de%fdZ*de%fdZ+d  Z,de%fd!Z-d1d"ed#e%de%fd$Z.d1d"ed#e%de%fd%Z/d1d"ed#e%de%fd&Z0d' Z1de%fd(Z2e jf                   ed)e4*      	 	 	 	 d2d+e%d,e%d-e%d.e%fd/              Z5 e
       Z6 e       Z7y)3    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"allow_fp16_bf16_reduction_math_sdp$fp16_bf16_reduction_math_sdp_allowedis_flash_attention_availablecan_use_flash_attentioncan_use_efficient_attentioncan_use_cudnn_attention
sdp_kernelc                  6    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_C	_has_cuda     O/var/www/html/venv/lib/python3.12/site-packages/torch/backends/cuda/__init__.pyr   r   &   s     88r#   c                       e Zd Zd Zd Zd Zy)r   c                      || _         || _        y N)gettersetter)selfr(   r)   s      r$   __init__z&cuFFTPlanCacheAttrContextProp.__init__3   s    r#   c                 8    | j                  |j                        S r'   )r(   device_index)r*   objobjtypes      r$   __get__z%cuFFTPlanCacheAttrContextProp.__get__7   s    {{3++,,r#   c                     t        | j                  t              rt        | j                        | j                  |j                  |       y r'   )
isinstancer)   strRuntimeErrorr-   )r*   r.   vals      r$   __set__z%cuFFTPlanCacheAttrContextProp.__set__:   s3    dkk3't{{++C$$c*r#   N)__name__
__module____qualname__r+   r0   r6   r"   r#   r$   r   r   0   s    -+r#   r   c                   |    e Zd ZdZd Z eej                  d      Z eej                  ej                        Zd Zy)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                     || _         y r'   )r-   )r*   r-   s     r$   r+   zcuFFTPlanCache.__init__H   s
    (r#   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                 @    t        j                  | j                        S r'   )r   _cufft_clear_plan_cacher-   r*   s    r$   clearzcuFFTPlanCache.clearU   s    ,,T->->??r#   N)r7   r8   r9   __doc__r+   r   r   _cufft_get_plan_cache_sizesize_cufft_get_plan_cache_max_size_cufft_set_plan_cache_max_sizemax_sizer?   r"   r#   r$   r   r   @   sJ    ) )((	ND -,,e.R.RH@r#   r   c                   8     e Zd ZdZdZd Zd Zd Z fdZ x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                      g | _         d| _        y )NT)caches#_cuFFTPlanCacheManager__initializedr>   s    r$   r+   zcuFFTPlanCacheManager.__init__d   s    !r#   c                    t         j                  j                  j                  |      }|dk  s!|t         j                  j	                         k\  r-t        dt         j                  j	                          d|       t        | j                        dk(  rG| j                  j                  d t        t         j                  j	                               D               | j                  |   S )Nr   z/cufft_plan_cache: expected 0 <= device index < z, but got device with index c              3   2   K   | ]  }t        |        y wr'   )r   ).0indexs     r$   	<genexpr>z4cuFFTPlanCacheManager.__getitem__.<locals>.<genexpr>p   s      */u%s   )
r   cuda_utils_get_device_indexdevice_countr4   lenrH   extendrange)r*   devicerM   s      r$   __getitem__z!cuFFTPlanCacheManager.__getitem__h   s    

!!33F;19!8!8!::A%**BYBYB[A\ ]%%*G-  t{{q KK 389P9P9R3S  {{5!!r#   c                 X    t        | t        j                  j                            |      S r'   )getattrr   rO   current_devicer*   names     r$   __getattr__z!cuFFTPlanCacheManager.__getattr__u   s!    tEJJ5578$??r#   c                     | j                   r,t        | t        j                  j	                            ||      S t
        |   ||      S r'   )rI   setattrr   rO   rZ   super__setattr__)r*   r\   value	__class__s      r$   ra   z!cuFFTPlanCacheManager.__setattr__x   s?    4

 9 9 ;<dEJJ7&tU33r#   )
r7   r8   r9   r@   rI   r+   rW   r]   ra   __classcell__)rc   s   @r$   r   r   Y   s)     M""@4 4r#   r   c                       e Zd Zd Zd Zy)r	   c                     |dk(  rt         j                  j                         S |dk(  rt         j                  j                         S |dk(  rt         j                  j	                         S t        d|z         N
allow_tf32&allow_fp16_reduced_precision_reduction&allow_bf16_reduced_precision_reductionzUnknown attribute )r   r    _get_cublas_allow_tf322_get_cublas_allow_fp16_reduced_precision_reduction2_get_cublas_allow_bf16_reduced_precision_reductionAttributeErrorr[   s     r$   r]   zcuBLASModule.__getattr__   sf    <882244==88NNPP==88NNPP1D899r#   c                     |dk(  rt         j                  j                  |      S |dk(  rt         j                  j                  |      S |dk(  rt         j                  j	                  |      S t        d|z         rg   )r   r    _set_cublas_allow_tf322_set_cublas_allow_fp16_reduced_precision_reduction2_set_cublas_allow_bf16_reduced_precision_reductionrn   )r*   r\   rb   s      r$   ra   zcuBLASModule.__setattr__   sl    <8822599==88NNuUU==88NNuUU1D899r#   N)r7   r8   r9   r]   ra   r"   r#   r$   r	   r	      s    ::r#   r	   )defaultcusolvermagmaz, backendreturnc                    | nt        | t              rB| t        vrt        dt         d      t
        j                  j                  t        |           nOt        | t
        j                  j                        r t
        j                  j                  |        nt        d      t
        j                  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`
    "Unknown input value. Choose from: .Unknown input value type.)
r2   r3   _LinalgBackendsr4   _LinalgBackends_strr   r    _set_linalg_preferred_backend_LinalgBackend_get_linalg_preferred_backendrv   s    r$   r
   r
      s    X 	GS	!/)78K7LAN  	..w/GH	GUXX44	5..w7677881133r#   )cublascublaslt	hipblasltc                    | nt        | t              rB| t        vrt        dt         d      t
        j                  j                  t        |           nOt        | t
        j                  j                        r t
        j                  j                  |        nt        d      t
        j                  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.

    ry   rz   r{   )
r2   r3   _BlasBackendsr4   _BlasBackends_strr   r    _set_blas_preferred_backend_BlasBackend_get_blas_preferred_backendr   s    r$   r   r      s    4 	GS	!-'78I7J!L  	,,]7-CD	GUXX22	3,,W567788//11r#   )_SDPAParams_SDPBackendztorch.backends.cudar   c                  >    t         j                  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    _get_flash_sdp_enabledr"   r#   r$   r   r          88**,,r#   enabledc                 B    t         j                  j                  |        y)z|
    .. warning:: This flag is beta and subject to change.

    Enables or disables flash scaled dot product attention.
    N)r   r    _set_sdp_use_flashr   s    r$   r   r          
HH(r#   c                  >    t         j                  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    _get_mem_efficient_sdp_enabledr"   r#   r$   r   r   #  s     882244r#   c                 B    t         j                  j                  |        y)z
    .. warning:: This flag is beta and subject to change.

    Enables or disables memory efficient scaled dot product attention.
    N)r   r    _set_sdp_use_mem_efficientr   s    r$   r   r   ,  s     
HH''0r#   c                  >    t         j                  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    _get_math_sdp_enabledr"   r#   r$   r   r   5  s     88))++r#   c                 B    t         j                  j                  |        y)z{
    .. warning:: This flag is beta and subject to change.

    Enables or disables math scaled dot product attention.
    N)r   r    _set_sdp_use_mathr   s    r$   r   r   >  s     
HHw'r#   c                 B    t         j                  j                  |        y)z
    .. warning:: This flag is beta and subject to change.

    Enables or disables fp16/bf16 reduction in math scaled dot product attention.
    N)r   r    '_set_math_sdp_allow_fp16_bf16_reductionr   s    r$   r   r   G  s     
HH44W=r#   c                  >    t         j                  j                         S )z
    .. warning:: This flag is beta and subject to change.

    Returns whether fp16/bf16 reduction in math scaled dot product attention is enabled or not.
    )r   r    '_get_math_sdp_allow_fp16_bf16_reductionr"   r#   r$   r   r   P  s     88;;==r#   c                  >    t         j                  j                         S )a5  Check if PyTorch was built with FlashAttention for scaled_dot_product_attention.

    Returns:
        True if FlashAttention is built and available; otherwise, False.

    Note:
        This function is dependent on a CUDA-enabled build of PyTorch. It will return False
        in non-CUDA environments.
    )r   r    _is_flash_attention_availabler"   r#   r$   r   r   Y  s     881133r#   paramsdebugc                 B    t         j                  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    _can_use_flash_attentionr   r   s     r$   r   r   f      " 88,,VU;;r#   c                 B    t         j                  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     _can_use_mem_efficient_attentionr   s     r$   r   r   z  s    " 8844VUCCr#   c                 B    t         j                  j                  | |      S )a  Check if cudnn_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 cuDNN attention could not be run.
            Defaults to False.

    Returns:
        True if cuDNN 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    _can_use_cudnn_attentionr   s     r$   r   r     r   r#   c                  >    t         j                  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    _get_cudnn_sdp_enabledr"   r#   r$   r   r     r   r#   c                 B    t         j                  j                  |        y)z|
    .. warning:: This flag is beta and subject to change.

    Enables or disables cuDNN scaled dot product attention.
    N)r   r    _set_sdp_use_cudnnr   s    r$   r   r     r   r#   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.)categoryenable_flashenable_mathenable_mem_efficientenable_cudnnc              #   t  K   ddl m} g }| r|j                  t        j                         |r|j                  t        j
                         |r|j                  t        j                         |r|j                  t        j                          ||      5 }	 | 	 ddd       y# w xY w# 1 sw Y   yxY ww)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)torch.nn.attentionr   append
SDPBackendFLASH_ATTENTIONEFFICIENT_ATTENTIONMATHCUDNN_ATTENTION)r   r   r   r   r   backend_listcontexts          r$   r   r     s     , /LJ667J::;JOO,J667	\	" g	M	  	 s0   BB8B,B'	B8'B))B,,B51B8r'   )F)TTTT)8
contextlibtypingr   typing_extensionsr   r   __all__r   r   r   r   r	   r    r   DefaultCusolverMagmar|   joinkeysr}   r3   r
   r   CublasCublasltr   r   r   torch._Cr   r   r   r   r8   r7   r   boolr   r   r   r   r   r   r   r   r   r   r   r   r   contextmanagerFutureWarningr   r   r   r"   r#   r$   <module>r      s     ( :+ + @ @2#4 #4L: :* xx&&..''00XX$$**
 ii 4 4 67  :>944ehh555694
XX94z hh##**%%..&&//
 IIm0023  8<'24ehh3334'2
XX'2T J .
 "
 -)d )51d 1,(T (> >>
4d 
4<J <t < <(D
 D4 DD D(<J <t < <(-)d ) 	"
  !%	  	 > )* 	r#   