+
    &j5                        R t ^ RIHtHt ^ RIHt ^ RIt^ RIHu H	t
 ^ RIHtHtHtHt ^ RIHt ^ RIHtHtHtHt . ROt]P0                  P3                  ]4       ]P0                  P3                  ]4       ]P0                  P3                  ]4       ]P0                  P3                  ]4        ! R	 R]4      t ! R
 R]P6                  4      tR R ltR R ltR# )zCDefines bias subclasses that work with scaled_dot_product_attention)autoIntEnum)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CausalVariant
CausalBiasc                   6    ] tR t^!tRt]! 4       t]! 4       tRtR# )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____firstlineno____doc__r   
UPPER_LEFTLOWER_RIGHT__static_attributes__r       o/Users/jameslopez/projects/CWCArchive/cwc-podcast/.venv/lib/python3.14/site-packages/torch/nn/attention/bias.pyr   r   !   s    .` J&Kr   c                      a a ] tR t^Vt oRtV3R lV 3R lltV3R lR ltV3R lR ltRV3R lR	 llt]	RV3R
 lR ll4       t
]RV 3R ll4       tV3R lR ltRtVtV ;t# )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.
c                0   < V ^8  d   QhRS[ RS[RS[RR/# )   variant	seq_len_q
seq_len_kvreturnN)r   int)format__classdict__s   "r   __annotate__CausalBias.__annotate__w   s*       # 3 SW r   c                  < \        V\        4      '       g"   \        R\        V4      P                   24      h\
        SV `  4        Wn        W n        W0n	        W#8  d'   V\        P                  8X  d   \        R^R7       R# R# R# )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.
z%variant must be a CausalVariant, got zTLower right causal bias will produce NaNs in the output when seq_len_q > seq_len_kv!)
stacklevelN)
isinstancer   AssertionErrortyper   super__init__r   r    r!   r   r   )selfr   r    r!   	__class__s   &&&&r   r.   CausalBias.__init__w   sz     '=11 7W8N8N7OP  	"$!g1J1J&Jf 'K!r   c                N   < V ^8  d   QhRS[ P                  RS[ P                  /# r   devicer"   torchr4   Tensor)r$   r%   s   "r   r&   r'      s#     
 
%,, 
5<< 
r   c           	         \         P                  ! \         P                  ! V P                  V P                  V\         P
                  R7      4      # )zUpper left causal biasr4   dtype)r6   trilonesr    r!   boolr/   r4   s   &&r   _upper_leftCausalBias._upper_left   s1    zzJJt~~tvUZZX
 	
r   c                N   < V ^8  d   QhRS[ P                  RS[ P                  /# r3   r5   )r$   r%   s   "r   r&   r'      s#     
 
5<< 
ELL 
r   c           	         V P                   V P                  ,
          p\        P                  ! \        P                  ! V P                  V P                   V\        P
                  R7      VR7      # )zLower right causal biasr9   )diagonal)r!   r    r6   r;   r<   r=   )r/   r4   diagonal_offsets   && r   _lower_rightCausalBias._lower_right   sK    //DNN:zzJJejj %	
 	
r   c                \   < V ^8  d   QhRS[ P                  R,          RS[ P                  /# )r   r4   Nr"   r5   )r$   r%   s   "r   r&   r'      s(     - -5<<$#6 -%,, -r   c                    Vf   \         P                  ! R4      pV P                  \        P                  8X  d   V P                  V4      # V P                  \        P                  8X  d   V P                  V4      # R# )aX  
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)r6   r4   r   r   r   r?   r   rE   r>   s   &&r   _materializeCausalBias._materialize   sb     >\\%(F<<=333##F++\\]666$$V,, 7r   c                   < V ^8  d   QhRS[ P                  RS[ P                  RS[ P                  RRRS[RS[RS[R	,          R
S[RS[ P                  /	# )r   querykeyvalue	attn_maskr   	dropout_p	is_causalscaleN
enable_gqar"   )r6   r7   floatr=   )r$   r%   s   "r   r&   r'      s     o o||o\\o ||o  	o
 o o t|o o 
or   c                   V'       d   \        R4      hVP                  VP                  8X  g    VP                  \        P
                  8X  d   \        P                  ! V VVRVRVVR7      # VP                  \        P                  8X  EdM   \        WVRWEV4       \        WVRWEV4      p\        V4      '       Ed$   V P                  P                  R8X  d   ^@M^p	V P                  R
4      p
\        W4      pW,          ^ 8g  pV'       d   WV	,          ,
          p\         P"                  P$                  P'                  V ^ V34      p \         P"                  P$                  P'                  V^ V34      p\         P"                  P$                  P'                  V^ V34      p\         P(                  P*                  P-                  V VVVRRVR7      ^ ,          p\/        W4      # \1        V4      '       d   Rp\3        WV4      '       d   Rp\         P(                  P*                  P5                  V P7                  ^^4      VP7                  ^^4      VP7                  ^^4      RRRRRV\9        VP                  4      VVRR7      ^ ,          P7                  ^^4      # \;        V4       \        P                  ! V VVVP=                  V P                  4      VRVVR7      # \        R	VP                   24      h)a  
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)rP   rQ   rR   rS   rT   xpuF)rR   return_debug_maskrS   )
biascu_seqlens_qcu_seqlens_kmax_seqlen_qmax_seqlen_krQ   custom_mask_typecompute_log_sumexprS   seqlen_kz<CausalBias.variant must be a CausalVariant type, but found: )
ValueErrorr    r!   r   r   r   Fscaled_dot_product_attentionr   r   r   r   r4   r,   sizer
   r6   nn
functionalpadopsaten#_scaled_dot_product_flash_attentionr   r   r   _efficient_attention_forward	transposer#   r	   rJ   )rM   rN   rO   rP   rQ   rR   rS   rT   sdpa_params	alignmentog_head_sizeog_scaleneeds_paddingpad_lenoutr_   s   &&&&&&&&        r   	_dispatchCausalBias._dispatch   s   F MNN 9#7#77  M$<$<<11#%	 	 -";";; UD)PUV$E4zK '{33"',,"3"3u"<B!	$zz"~+L@ , 8A = ')+CDG!HH//33EAw<HE((--11#7|DC!HH//33EAw<HEiinnHH"&+" I   1CC*;77%*"'E::)-&yy~~BBOOAq)MM!Q'OOAq)!%!%!%!%'%():):%;'9! C   Yq!_%  '{355'44U\\B'#)	 	 NyO`O`Nab r   c                   < Vf   / pV\         P                  P                  P                  J d   V P                  ! V/ VB # \
        SV `  WW44      # )zjDefines the behavior of torch.nn.functional.scaled_dot_product_attention when the attn_bias is an AttnBias)r6   rf   rg   rd   ru   r-   __torch_function__)clsfunctypesargskwargsr0   s   &&&&&r   rx   CausalBias.__torch_function__'  sM     >F588&&CCC==$1&11w)$tDDr   c                    < V ^8  d   QhRS[ /# r   r"   )str)r$   r%   s   "r   r&   r'   0  s     . .# .r   c                >    V P                  4       P                  4       # N)rJ   __repr__)r/   s   &r   r   CausalBias.__repr__0  s      "++--r   )r!   r    r   r   )g        FNF)r   N)r   r   r   r   r   r.   r?   rE   rJ   staticmethodru   classmethodrx   r   r   __classdictcell____classcell__)r0   r%   s   @@r   r   r   V   su     @ 2
 

 
- -( o o ob E E. . .r   c                $    V ^8  d   QhR\         /# r   r   )r$   s   "r   r&   r&   4  s     G G
 Gr   c                 t    \        V 4      ^8w  d   \        R4      hV w  r\        \        P                  W4      # )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.
z*causal_upper_left only supports 2D tensors)lenr+   r   r   r   re   r    r!   s   *  r   causal_upper_leftr   4  s6    8 4yA~IJJ Im..	FFr   c                $    V ^8  d   QhR\         /# r   r   )r$   s   "r   r&   r&   V  s     "H "H "Hr   c                 t    \        V 4      ^8w  d   \        R4      hV w  r\        \        P                  W4      # )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.
z+causal_lower_right only supports 2D tensors)r   r+   r   r   r   r   s   *  r   causal_lower_rightr   V  s6    > 4yA~JKK Im//GGr   )r   r   r   r   )r   enumr   r   warningsr   r6   torch.nn.functionalrf   rg   rc   torch.backends.cudar   r   r   r   torch.nn.attentionr	   torch.nn.attention._utilsr
   r   r   r   __all___dynamoallow_in_graphr   r7   r   r   r   r   r   r   <module>r      s    I       6  U   9 :   4 5   8 9   Z (2G 2j[. [.|GD"Hr   