Ë
    [^(hZ4  ã                   ó¾  — d Z ddlmZmZ ddlmZ ddlmZ ddlZddl	m
c mZ ddlmZmZmZmZ ddlmZ ddlmZmZmZmZ g d	¢Zej4                  j7                  e«       ej4                  j7                  e«       ej4                  j7                  e«       ej4                  j7                  e«        G d
„ de«      Z G d„ dej:                  «      Zdefd„Zdefd„Z y)zCDefines bias subclasses that work with scaled_dot_product_attentioné    )ÚautoÚIntEnum)ÚOptional)ÚwarnN)Úcan_use_efficient_attentionÚcan_use_flash_attentionÚis_flash_attention_availableÚ
SDPAParams)Ú_raise_kernel_warnings)Ú_calculate_scaleÚ_input_requires_gradÚ_postprocess_flash_outputÚ_validate_sdpa_input)Úcausal_upper_leftÚcausal_lower_rightÚCausalVariantÚ
CausalBiasc                   ó,   — e Zd ZdZ e«       Z e«       Zy)r   a#  
    Enum for causal variants used in attention mechanisms.

    Defines two types of causal biases:

    `UPPER_LEFT`: Represents upper-left triangular bias for standard causal attention.
    The equivalent pytorch code for constructing this bias is:

    .. code-block:: python

        torch.tril(torch.ones(size, dtype=torch.bool))

    For instance, with `shape=(3,4)`, the materialized bias tensor will be:

    .. code-block:: text

        [[1, 0, 0, 0],
         [1, 1, 0, 0],
         [1, 1, 1, 0]]


    `LOWER_RIGHT`: Represents lower-right triangular bias, the include values are aligned to the lower
    right corner of the matrix.

    The equivalent pytorch code for constructing this bias is:

    .. code-block:: python

        diagonal_offset = size[1] - size[0]
        torch.tril(
            torch.ones(size, dtype=torch.bool),
            diagonal=diagonal_offset,
        )

    For instance, with `shape=(3,4)`, the materialized bias tensor will be:

    .. code-block:: text

        [[1, 1, 0, 0],
         [1, 1, 1, 0],
         [1, 1, 1, 1]]

    Note that these variants are equivalent to each other when the sequence lengths of the query and key/value
    tensors are equal since the triangular matrix is square.

    .. warning:: This enum is a prototype and subject to change.
    N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú
UPPER_LEFTÚLOWER_RIGHT© ó    úU/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/torch/nn/attention/bias.pyr   r   !   s   „ ñ.ñ` “€JÙ“&�Kr   r   c                   ó‚  — e Zd ZdZdededefd„Zdej                  dej                  fd„Z
dej                  dej                  fd	„Zddeej                     dej                  fd„Ze	 	 	 	 ddej                  dej                  dej                  dd dededee   dedej                  fd„«       Zedd„«       Zd„ Zy
)r   a  
    A bias representing causal attention patterns. For an overview of the bias structure, see the :class:`CausalVariant` enum.

    This class is used for defining causal (triangular) attention biases. For construing the bias, there exist
    two factory functions: :func:`causal_upper_left` and :func:`causal_lower_right`.

    Example:

    .. code-block:: python

        from torch.nn.attention.bias import causal_lower_right

        bsz, num_heads, seqlen_q, seqlen_kv, head_dim = 32, 8, 4, 12, 8

        # Create a lower-right causal bias
        attn_bias = causal_lower_right(seqlen_q, seqlen_kv)

        q = torch.randn(bsz, num_heads, seqlen_q, head_dim, device="cuda", dtype=torch.float16)
        k = torch.randn(bsz, num_heads, seqlen_kv, head_dim, device="cuda", dtype=torch.float16)
        v = torch.randn(bsz, num_heads, seqlen_kv, head_dim, device="cuda", dtype=torch.float16)

        out = F.scaled_dot_product_attention(q, k, v, attn_bias)

    .. warning:: This class is a prototype and subject to change.
    ÚvariantÚ	seq_len_qÚ
seq_len_kvc                 óœ   — t        |t        «      sJ ‚|| _        || _        || _        ||kD  r |t        j
                  k(  rt        d«       yyy)aÞ  
        Initializes the CausalBias instance with a specified variant and sequence lengths.

        Args:
            variant (CausalVariant): The type of causal bias to use (either UPPER_LEFT or LOWER_RIGHT).
            seq_len_q (int): The sequence length of the query tensor.
            seq_len_kv (int): The sequence length of the key/value tensor.

        Raises a warning if the LOWER_RIGHT variant is used with seq_len_q > seq_len_kv, as it may produce NaNs.
        zTLower right causal bias will produce NaNs in the output when seq_len_q > seq_len_kv!N)Ú
isinstancer   r   r    r!   r   r   )Úselfr   r    r!   s       r   Ú__init__zCausalBias.__init__q   sR   € ô ˜'¤=Ô1Ð1Ð1ØˆŒØ"ˆŒØ$ˆŒØ�zÒ! g´×1JÑ1JÒ&JÜØfõð 'KÐ!r   ÚdeviceÚreturnc                 óž   — t        j                  t        j                  | j                  | j                  |t         j
                  ¬«      «      S )zUpper left causal bias©r&   Údtype)ÚtorchÚtrilÚonesr    r!   Úbool©r$   r&   s     r   Ú_upper_leftzCausalBias._upper_left…   s1   € ä�z‰zÜ�J‰J�t—~‘~ t§¡¸vÌUÏZÉZÔXó
ð 	
r   c                 óÔ   — | j                   | j                  z
  }t        j                  t        j                  | j                  | j                   |t        j
                  ¬«      |¬«      S )zLower right causal biasr)   )Údiagonal)r!   r    r+   r,   r-   r.   )r$   r&   Údiagonal_offsets      r   Ú_lower_rightzCausalBias._lower_right‹   sK   € àŸ/™/¨D¯N©NÑ:ˆÜ�z‰zÜ�J‰JØ—‘ §¡¸ÄeÇjÁjôð %ô	
ð 	
r   Nc                 óê   — |€t        j                  d«      }| j                  t        j                  k(  r| j                  |«      S | j                  t        j                  k(  r| j                  |«      S y)a˜  
        Materializes the causal bias into a tensor form.

        Depending on the variant, this method generates either an upper-left or lower-right
        triangular matrix to represent the causal bias.

        Args:
            device (Optional[torch.device]): The device on which to create the tensor. Defaults to CPU.

        Returns:
            torch.Tensor: The materialized bias tensor.
        NÚcpu)r+   r&   r   r   r   r0   r   r4   r/   s     r   Ú_materializezCausalBias._materialize•   sb   € ð ˆ>Ü—\‘\ %Ó(ˆFØ�<‰<œ=×3Ñ3Ò3Ø×#Ñ# FÓ+Ð+Ø�\‰\œ]×6Ñ6Ò6Ø×$Ñ$ VÓ,Ð,ð 7r   ÚqueryÚkeyÚvalueÚ	attn_maskÚ	dropout_pÚ	is_causalÚscaleÚ
enable_gqac                 óÌ  — |rt        d«      ‚|j                  |j                  k(  s|j                  t        j
                  k(  rt        j                  | ||d|d||¬«      S |j                  t        j                  k(  �rOt        | ||d|||«       t        | ||d|||«      }t        |«      �r8| j                  d«      dz  dk7  }	| j                  d«      }
t        |
|«      }|	rÃt        j                  j                   j#                  | dd| j                  d«      dz  z
  f«      } t        j                  j                   j#                  |dd|j                  d«      dz  z
  f«      }t        j                  j                   j#                  |dd|j                  d«      dz  z
  f«      }t        j$                  j&                  j)                  | |||dd|¬	«      d   }t+        ||
«      S t-        |«      r�d}t/        | ||«      rd}t        j$                  j&                  j1                  | j3                  d
d«      |j3                  d
d«      |j3                  d
d«      ddddd|t5        |j                  «      ||d¬«      d   j3                  d
d«      S t7        |«       t        j                  | |||j9                  | j:                  «      |d||¬«      S t        d|j                  › �«      ‚)a8  
        Handles the logic for computing attention with the specified causal bias.

        Args:
            query (Tensor): Query tensor; shape :math:`(N, ..., L, E)`.
            key (Tensor): Key tensor; shape :math:`(N, ..., S, E)`.
            value (Tensor): Value tensor; shape :math:`(N, ..., S, Ev)`.
            attn_mask (CausalBias): The type of causal attention to apply.
                A boolean mask where a value of True indicates that the element *should* take part in attention.
                A float mask of the same type as query, key, value that is added to the attention score.
            dropout_p (float): Dropout probability; if greater than 0.0, dropout is applied
            is_causal (bool): If true, assumes upper left causal attention masking and errors if both attn_mask and is_causal
                are set.
            scale (optional float): Scaling factor applied prior to softmax. If None, the default value is set
                to :math:`\frac{1}{\sqrt{E}}`.
            enable_gqa (optional bool): If set to True, Grouped Query Attention (GQA) is enabled, by default it is set to False.

        Returns:
            output (Tensor): Attention output; shape :math:`(N, ..., L, Ev)`.

        Raises:
            ValueError: If the causal bias variant is not a CausalVariant type.

        z.CausalBias should not be used with causal=TrueNT)r;   r<   r=   r>   r?   éÿÿÿÿé   r   F)r=   Úreturn_debug_maskr>   é   é   )
ÚbiasÚcu_seqlens_qÚcu_seqlens_kÚmax_seqlen_qÚmax_seqlen_kr<   Úcustom_mask_typeÚcompute_log_sumexpr>   Úseqlen_kz<CausalBias.variant must be a CausalVariant type, but found: )Ú
ValueErrorr    r!   r   r   r   ÚFÚscaled_dot_product_attentionr   r   r
   r   Úsizer   r+   ÚnnÚ
functionalÚpadÚopsÚatenÚ#_scaled_dot_product_flash_attentionr   r   r   Ú_efficient_attention_forwardÚ	transposeÚintr   r7   r&   )r8   r9   r:   r;   r<   r=   r>   r?   Úsdpa_paramsÚneeds_paddingÚog_head_sizeÚog_scaleÚoutrL   s                 r   Ú	_dispatchzCausalBias._dispatch©   sà  € ñF ÜÐMÓNÐNð ×Ñ 9×#7Ñ#7Ò7Ø× Ñ ¤M×$<Ñ$<Ò<ä×1Ñ1ØØØØØ#ØØØ%ô	ð 	ð ×Ñ¤-×";Ñ";Ó;Ü  ¨¨U°D¸)ÀYÐPUÔVÜ$Ø�s˜E 4¨°I¸zóˆKô ' {Õ3Ø %§
¡
¨2£°Ñ 2°aÑ 7�Ø$Ÿz™z¨"›~�Ü+¨L¸%Ó@�Ù Ü!ŸH™H×/Ñ/×3Ñ3°E¸A¸qÀ5Ç:Á:ÈbÃ>ÐTUÑCUÑ?UÐ;VÓW�EÜŸ(™(×-Ñ-×1Ñ1°#¸¸1¸s¿x¹xÈ»|ÈaÑ?OÑ;OÐ7PÓQ�CÜ!ŸH™H×/Ñ/×3Ñ3°E¸A¸qÀ5Ç:Á:ÈbÃ>ÐTUÑCUÑ?UÐ;VÓW�EÜ—i‘i—n‘n×HÑHØØØØØ"Ø&+Ø"ð Ió ð ñ�ô 1°°lÓCÐCÜ*¨;Ô7Ø%*Ð"Ü'¨¨s°EÔ:Ø)-Ð&Ü—y‘y—~‘~×BÑBØ—O‘O A qÓ)Ø—M‘M ! QÓ'Ø—O‘O A qÓ)ØØ!%Ø!%Ø!%Ø!%Ø'Ü%(¨×):Ñ):Ó%;Ø'9ØØ!ð Có ð ñ÷ ‘Y˜q !“_ð%ô  ' {Ô3ä×5Ñ5ØØØØ'×4Ñ4°U·\±\ÓBØ'Ø#ØØ)ô	ð 	ô ØNÈy×O`ÑO`ÐNaÐbóð r   c                 ó’   — |€i }|t         j                  j                  j                  k7  rt	        d«      ‚ | j
                  |i |¤ŽS )zjDefines the behavior of torch.nn.functional.scaled_dot_product_attention when the attn_bias is an AttnBiasz5CausalBias only supports scaled_dot_product_attention)r+   rR   rS   rP   ÚNotImplementedErrorr`   )ÚclsÚfuncÚtypesÚargsÚkwargss        r   Ú__torch_function__zCausalBias.__torch_function__  sN   € ð ˆ>ØˆFØ”5—8‘8×&Ñ&×CÑCÒCÜ%ØGóð ð ˆs�}‰}˜dÐ- fÑ-Ð-r   c                 ó>   — | j                  «       j                  «       S ©N)r7   Ú__repr__)r$   s    r   rk   zCausalBias.__repr__$  s   € Ø× Ñ Ó"×+Ñ+Ó-Ð-r   rj   )g        FNF)r   N)r   r   r   r   r   rZ   r%   r+   r&   ÚTensorr0   r4   r   r7   ÚstaticmethodÚfloatr.   r`   Úclassmethodrh   rk   r   r   r   r   r   V   s(  „ ñð4 ð ¸#ð È3ó ð(
 %§,¡,ð 
°5·<±<ó 
ð
 5§<¡<ð 
°E·L±Ló 
ñ- 8¨E¯L©LÑ#9ð -ÀUÇ\Á\ó -ð( ð ØØ!%Ø ñmØ�|‰|ðmà�\‰\ðmð �|‰|ðmð  ð	mð
 ðmð ðmð ˜‰ðmð ðmð 
�‰òmó ðmð^ ò.ó ð.ó.r   r   r'   c                  ól   — t        | «      dk(  sJ d«       ‚| \  }}t        t        j                  ||«      S )a&  
    Creates an upper-left triangular causal bias.

    This function generates a upper-left triangular matrix to represent causal attention bias with a
    diagonal offset set so that the inclusive values are aligned to the upper left corner of the matrix.
    This equivalent to the `is_causal=True` argument in `scaled_dot_product_attention`.

    The equivalent pytorch code for constructing this bias is:

    .. code-block:: python

        torch.tril(torch.ones(size, dtype=torch.bool))

    For instance, with `shape=(3,4)`, the materialized bias tensor will be:

    .. code-block:: text

        [[1, 0, 0, 0],
         [1, 1, 0, 0],
         [1, 1, 1, 0]]

    Args:
        size: The size of the bias matrix.

    Returns:
        CausalBias: The UPPER_LEFT triangular causal bias variant.
    rE   z*causal_upper_left only supports 2D tensors)Úlenr   r   r   ©rQ   r    r!   s      r   r   r   (  s9   € ô8 ˆt‹9˜Š>ÐGÐGÓGˆ>Ø Ñ€IˆzÜ”m×.Ñ.°	¸:ÓFÐFr   c                  ól   — t        | «      dk(  sJ d«       ‚| \  }}t        t        j                  ||«      S )a:  
    Creates a lower-right triangular causal bias.

    This function generates a lower-right triangular matrix to represent causal attention bias with a
    diagonal offset set so that the inclusive values are aligned to the lower right corner of the matrix.

    The equivalent pytorch code for constructing this bias is:

    .. code-block:: python

        diagonal_offset = size[1] - size[0]
        torch.tril(
            torch.ones(size, dtype=torch.bool),
            diagonal=diagonal_offset,
        )

    For instance, with `shape=(3,4)`, the materialized bias tensor will be:

    .. code-block:: text

        [[1, 1, 0, 0],
         [1, 1, 1, 0],
         [1, 1, 1, 1]]

    Args:
        size: The size of the bias matrix.

    Returns:
        CausalBias: The LOWER_RIGHT triangular causal bias variant.
    rE   z+causal_lower_right only supports 2D tensors)rq   r   r   r   rr   s      r   r   r   I  s9   € ô> ˆt‹9˜Š>ÐHÐHÓHˆ>Ø Ñ€IˆzÜ”m×/Ñ/°¸JÓGÐGr   )!r   Úenumr   r   Útypingr   Úwarningsr   r+   Útorch.nn.functionalrR   rS   rO   Útorch.backends.cudar   r   r	   r
   Útorch.nn.attentionr   Útorch.nn.attention._utilsr   r   r   r   Ú__all__Ú_dynamoÚallow_in_graphr   rl   r   r   r   r   r   r   ú<module>r~      sÅ   ðá Iß Ý Ý ã ß Ð ÷ó õ 6÷ó ò U€ð ‡�× Ñ Ð9Ô :Ø ‡�× Ñ Ð4Ô 5Ø ‡�× Ñ Ð8Ô 9Ø ‡�× Ñ ˜ZÔ (ô2�Gô 2ôjO.�—‘ô O.ðdG 
ó GðB!H ô !Hr   