
    9i                       % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSK	J
r
JrJrJrJr  SSKrSSKJr   SSK	Jr   SSK	Jr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJ r   SSK!J"r"  Sr#\$" 5       r%\$\&   \'S'   \(4S\&S\&S\)\*   SS4S jjr+/ SQr,\\\\\\/\4   r-\\\\\/\4   r. " S S\SS9r/ " S S\5      r0 " S S\5      r1 " S S\5      r2S\S\24S  jr3   SlS\S!\4\\5   S"4   S#\4\\5   S"4   S$\\5\6\\5      4   S%\74
S& jjr8S'\S(\S)\S*\S+\S\4S, jr9S(\S)\S*\S+\S\4
S- jr:S.r;S/r<S0\S1\4S2 jr=S\4\\4   4S3 jr>S0\S1\4S4 jr?S5\S6\S7\5S8\54S9 jr@ " S: S;5      rAS< rBS= rC\;\;S4S>\S?\7S\4\\\   4   4S@ jjrDSA\.S\.4SB jrESA\.S\.4SC jrF\;\;4S\4SD jjrG\;\;4SE\4\\\   4   SF\\   SG\4\5\54   SH\5SI\5S\A4SJ jjrH SmSL\\-\.4   SM\\5   SN\\5   SO\5SP\5SQ\S\4SR jjrISK\;S4SF\.SM\\5   SN\\5   SO\5SP\5SQ\SS\\5\4\5\54   4   S\A4ST jjrJSU\SV\S\A4SW jrKSX\\-\.4   SY\R                   SZ\R                   S[\7S\\-\.4   4
S\ jrLS\;S4SF\.SM\\5   SN\\5   SY\R                   SZ\\R                      SS\\5\4\5\54   4   S\A4S] jjrM SnSU\SV\S^\S_\7S`\\0   4
Sa jjrNSU\SV\S^\4Sb jrOSU\SV\S^\4Sc jrPSU\SV\S^\4Sd jrQSU\SV\S^\S\4\R                   \R                   \R                   4   4Se jrR      SoSSf.SU\SV\S^\Sg\\-   SE\\A   Sh\\S   Si\7S_\7Sj\\/   S`\\0   S\\\4\\4   \4\\14   4   4Sk jjjrg! \ a
    SSKJr   GNf = f! \ a
    SSKJr   GNf = f)pzIThis module implements the user facing API for flex_attention in PyTorch.    N)Enum)AnyCallable
NamedTupleOptionalUnion)Tensor)	TypedDict)NotRequired)flex_attention)_set_compilation_env)DeviceLikeType))_temp_remove_metadata_torch_function_mode-_temp_remove_pre_dispatch_torch_function_mode)_validate_sdpa_input)tree_map_onlyF_WARNINGS_SHOWN
warning_idmessagecategoryreturnc                 n    U [         ;  a+  [        R                  " XSS9  [         R                  U 5        gg)z=Helper to ensure each warning is shown only once per process.   )
stacklevelN)r   warningswarnadd)r   r   r   s      a/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/torch/nn/attention/flex_attention.py
_warn_oncer   <   s-     (gA6J' )    )	BlockMaskr   	AuxOutput
AuxRequestFlexKernelOptionscreate_block_maskcreate_maskcreate_nested_block_maskor_masks	and_masks	noop_maskc                   J   \ rS rSr% Sr\\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S	'    \\   \S
'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'    \\   \S'   Sr	g)r$   W   ab  Options for controlling the behavior of FlexAttention kernels.

These options are passed to the underlying Triton kernels to control performance
and numerical behavior. Most users will not need to specify these options as the
default autotuning provides good performance.

The options can be prefixed with ``fwd_`` or ``bwd_`` to apply only to forward or
backward pass respectively. For example: ``fwd_BLOCK_M`` and ``bwd_BLOCK_M1``.

Note:
  We currently do not provide any backward compatibility guarantees for these options.
  That being said most of these have remained pretty stable since their introduction. But
  We do not consider this part of the public API just yet. We think that some documentation
  Is better than secret hidden flags, but we may change these options in the future.

Example Usage:
    .. code-block:: python

        # Using dictionary (backward compatible)
        kernel_opts = {"BLOCK_M": 64, "BLOCK_N": 64, "PRESCALE_QK": True}
        output = flex_attention(q, k, v, kernel_options=kernel_opts)

        # Using TypedDict (recommended for type safety)
        from torch.nn.attention.flex_attention import FlexKernelOptions

        kernel_opts: FlexKernelOptions = {
            "BLOCK_M": 64,
            "BLOCK_N": 64,
            "PRESCALE_QK": True,
        }
        output = flex_attention(q, k, v, kernel_options=kernel_opts)

        # Forward/backward specific options
        kernel_opts: FlexKernelOptions = {
            "fwd_BLOCK_M": 64,
            "bwd_BLOCK_M1": 32,
            "PRESCALE_QK": False,
        }
        output = flex_attention(q, k, v, kernel_options=kernel_opts)
	num_warps
num_stagesBLOCK_MBLOCK_NBLOCK_M1BLOCK_N1BLOCK_M2BLOCK_N2PRESCALE_QKROWS_GUARANTEED_SAFEBLOCKS_ARE_CONTIGUOUSWRITE_DQFORCE_USE_FLEX_ATTENTIONUSE_TMAkpackmatrix_instr_nonkdimwaves_per_eu N)
__name__
__module____qualname____firstlineno____doc__r   int__annotations__bool__static_attributes__r>   r    r   r$   r$   W   s7   'T 3L C  N b b #, #, #, #, T""6 &d++Q
 't,,A $G *$//- /
 s1%c**;c""1r    r$   )totalc                   6    \ rS rSr% SrSr\\S'   Sr\\S'   Sr	g)r#      zRequest which auxiliary outputs to compute from flex_attention.

Each field is a boolean indicating whether that auxiliary output should be computed.
Flse
max_scoresr>   N)
r?   r@   rA   rB   rC   rK   rF   rE   rL   rG   r>   r    r   r#   r#      s    
 CJr    r#   c                   B    \ rS rSr% SrSr\\   \S'   Sr	\\   \S'   Sr
g)r"      z|Auxiliary outputs from flex_attention operation.

Fields will be None if not requested, or contain the tensor if requested.
NrK   rL   r>   )r?   r@   rA   rB   rC   rK   r   r	   rE   rL   rG   r>   r    r   r"   r"      s'    
 !C&	 #'J 'r    r"   c                   $    \ rS rSrSrSrSrSrSrg)_ModificationType   zEnum for the type of modification function.
- SCORE_MOD: score_mod function which accepts a score as the first argument
- mask_mod: mask function which does not accept a score and is only used for generating
block mask
   r      r>   N)	r?   r@   rA   rB   rC   	SCORE_MODMASK_MODUNKNOWNrG   r>   r    r   rP   rP      s     IHGr    rP   fnc                    [        S [        R                  " U 5      R                  R	                  5        5       5      nUS:X  d  US:X  d   eUS:X  a  [
        R                  $ US:X  a  [
        R                  $ [
        R                  $ )aH  Get the type of modification function.
This function inspects the number of positional arguments of the function to determine
the type of modification function. If the function has 5 positional arguments, it is
considered as a score_mod function. If the function has 4 positional arguments, it is
considered as a mask function.
c              3   z   #    U  H1  nUR                   [        R                  R                  :X  d  M-  S v   M3     g7f)rR   N)defaultinspect	Parameterempty).0params     r   	<genexpr> _get_mod_type.<locals>.<genexpr>   s1      >E==G--333 	
>s   ,;	;      )	sumr[   	signature
parametersvaluesrP   rT   rU   rV   )rW   num_positional_argss     r   _get_mod_typeri      s      &&r*55<<> 
 !#':a'???a ***		! ))) (((r    prefix.suffixout_dims	group_dimc                     / n/ SQnU(       a  US/-  nUS/-  nU H  n[         R                  " XU-   U-   US9n M      U $ )a[  Used to vmap both score_mods and mask_mods over 4-dimensional/5-dimension inputs.
Mapping over the [b, hq, q_idx, kv_idx] or [b, hkv, g, q_idx, kv_idx] dimensions.

Args:
    fn (callable): The function to vmap.
    prefix (tuple): The prefix of the vmap. For score mod functions,
                    this should be set to (0,). For mask_mods = ()
    suffix (tuple): We need to add (0,) if gradOut is being mapped over,
                    and (None,) * len(other_buffers).
    out_dims (tuple): For forward cases, keep this as the default 0 since
                      we are only returning 1 output. For backwards, the joint
                      graph returns grads for B, H, Q_idx, KV_idx and other_buffers,
                      so we set this to (0, None, None, None, None) + (None,) * len(other_buffers).

Returns:
    callable: The vmapped function.
))NNNr   )NNr   NNr   NNro   )r   NNN)in_dimsrl   )torchvmap)rW   rj   rk   rl   rm   
dimensionsdimss          r   _vmap_for_bhqkvru     sg    2 OQJJ !
 	

  J ZZTMF$:XN Ir    scorebatchheadtoken_qtoken_kvc                     U $ Nr>   )rv   rw   rx   ry   rz   s        r   	_identityr}   0  s	     Lr    c                 T    U R                  S[        R                  U R                  S9$ )zReturns a noop mask_modr>   )sizedtypedevice)new_onesrq   rF   r   )rw   rx   ry   rz   s       r   r*   r*   :  s!     >>rELL>IIr       i   @num_blocks_in_rowcol_indicesc                   ^^^	 UR                   S   m	UR                   S   mU R                   S S nU R                  mUUU	4S jnUn[        [        U5      5       H  n[        R
                  " USS9nM     U" X5      nU$ )Nc                   > UR                  T	TS-   [        R                  S9n[        R                  " T	[        R                  TS9R                  S5      n[        R                  " T[        R                  TS9nX@R                  S5      :  n[        R                  " XQT5      nUR                  S5      X#U4'   US S 2S T24   R                  5       $ )NrR   r   r   r   r   r>   )		new_zerosrq   int32arangerD   	unsqueezewherer   
contiguous)
kv_num_blocks
kv_indices
dense_maskrow_indices	col_range
index_maskvalid_indicesr   num_colsnum_rowss
          r   create_dense_one+_ordered_to_dense.<locals>.create_dense_oneN  s    ))(HqL)T
ll8599VLVV
 LL6J	!8!8!<<
 JHE 2<1D1DR1H
-.!YhY,'2244r    )r   r   )rp   )shaper   rangelenrq   rr   )
r   r   
batch_dimsr   create_dense_batched_outr   r   r   s
          @@@r   _ordered_to_denser   H  s      $H  $H"(("-J%%F5  ,3z?#$zz*>O $ 0
>CJr    c                 8   U R                  [        R                  S9n U R                  SS9n[        R                  " U SSSS9nUR                  [        R                  [        R
                  S9UR                  [        R                  [        R
                  S94$ )Nr   r   dimT)r   
descendingstable)memory_format)torq   r   rd   argsortcontiguous_format)r   r   r   s      r   _dense_to_orderedr   f  s|    U[[1J"2.--
tDQKU[[8O8OPu{{%2I2IJ r    c                 N    [        X5      n[        UR                  SS5      5      $ )Nr   r   )r   r   	transpose)r   r   denses      r   _transpose_orderedr   p  s#    /=EU__R455r    
num_blocksindicesnew_num_rowsnew_num_colsc                     US S 2S S 2S U2S U24   nU S S 2S S 2S U24   n [         R                  " X:  X5      n [         R                  " XS S 2S S 2S S 2S 4   :  SS9R                  [         R                  5      n X4$ )Nr   r   )rq   r   rd   r   r   )r   r   r   r   s       r   _adjust_num_blocks_and_indicesr   u  s     aM\M=L=89GAq-<-/0JZ6
QJ71a%>>BGJJ5;;WJr    c                   N   \ rS rSr% Sr\\\4   \S'   \\S'   \\S'   \	\   \S'   \	\   \S'   \	\   \S'   \	\   \S	'   \	\   \S
'   \	\   \S'   \\\4   \S'   \
\S'   S\\\4   S\S\S\	\   S\	\   S\	\   S	\	\   S
\	\   S\	\   S\\\4   S\
4S jr\SS\SSS4S\S\S\	\   S\	\   S\\\\\4   4   S\	\
   S\	\\\4      S\4S jj5       rS$S\4S jjr\S 5       rS rS%S jrS rS\S\4S jrS rS\4S jrS\4S jrS&S  jrS!\\R<                  \4   SS 4S" jr S#r!g)'r!   i  a	  
BlockMask is our format for representing a block-sparse attention mask.
It is somewhat of a cross in-between BCSR and a non-sparse format.

**Basics**

A block-sparse mask means that instead of representing the sparsity of
individual elements in the mask, a KV_BLOCK_SIZE x Q_BLOCK_SIZE block is
considered sparse only if every element within that block is sparse.
This aligns well with hardware, which generally expects to perform
contiguous loads and computation.

This format is primarily optimized for 1. simplicity, and 2. kernel
efficiency. Notably, it is *not* optimized for size, as this mask is always
reduced by a factor of KV_BLOCK_SIZE * Q_BLOCK_SIZE. If the size is a
concern, the tensors can be reduced in size by increasing the block size.

The essentials of our format are:

num_blocks_in_row: Tensor[ROWS]:
Describes the number of blocks present in each row.

col_indices: Tensor[ROWS, MAX_BLOCKS_IN_COL]:
`col_indices[i]` is the sequence of block positions for row i. The values of
this row after `col_indices[i][num_blocks_in_row[i]]` are undefined.

For example, to reconstruct the original tensor from this format:

.. code-block:: python

    dense_mask = torch.zeros(ROWS, COLS)
    for row in range(ROWS):
        for block_idx in range(num_blocks_in_row[row]):
            dense_mask[row, col_indices[row, block_idx]] = 1

Notably, this format makes it easier to implement a reduction along the
*rows* of the mask.

**Details**

The basics of our format require only kv_num_blocks and kv_indices. But, we
have up to 8 tensors on this object. This represents 4 pairs:

1. (kv_num_blocks, kv_indices): Used for the forwards pass of attention, as
we reduce along the KV dimension.

2. [OPTIONAL] (full_kv_num_blocks, full_kv_indices): This is optional and
purely an optimization. As it turns out, applying masking to every block
is quite expensive! If we specifically know which blocks are "full" and
don't require masking at all, then we can skip applying mask_mod to these
blocks. This requires the user to split out a separate mask_mod from the
score_mod. For causal masks, this is about a 15% speedup.

3. [GENERATED] (q_num_blocks, q_indices): Required for the backwards pass,
as computing dKV requires iterating along the mask along the Q dimension. These are autogenerated from 1.

4. [GENERATED] (full_q_num_blocks, full_q_indices): Same as above, but for
the backwards pass. These are autogenerated from 2.
seq_lengthsr   r   full_kv_num_blocksfull_kv_indicesq_num_blocks	q_indicesfull_q_num_blocksfull_q_indices
BLOCK_SIZEmask_modc                 2   UR                  5       S:  a  [        S5      eUc   S5       eUc   S5       eUS L US L :X  d   S5       eUS L U	S L :X  d   S5       eXl        X l        X0l        X@l        XPl        X`l        Xpl        Xl	        Xl
        Xl        Xl        g )Nr   )BlockMask must have at least 2 dimensionszkv_num_blocks must be providedzkv_indices must be providedGfull_kv_num_blocks and full_kv_indices must be both provided or omittedzEfull_q_num_blocks and full_q_indices must be both provided or omitted)r   RuntimeErrorr   r   r   r   r   r   r   r   r   r   r   )selfr   r   r   r   r   r   r   r   r   r   r   s               r   __init__BlockMask.__init__  s     >>aJKK(J*JJ(%D'DD%"d*40GH 	
U	
H "T)~/EF 	
S	
F '*$"4.("!2,$ r    NTcompute_q_blocksc	                    UR                  5       S:  a  [        S5      eUSL USL :X  d   S5       eU(       a(  [        X5      u  pUb  Uc   e[        X45      u  pOSu  pOSu  pSu  p[        U[        5      (       a  XU4nUb  UO[
        nUc-  UR                  S   US   -  nUR                  S   US	   -  nX4nU " UUUUUU	U
UUUUS
9$ )a'  
Creates a BlockMask instance from key-value block information.

Args:
    kv_num_blocks (Tensor): Number of kv_blocks in each Q_BLOCK_SIZE row tile.
    kv_indices (Tensor): Indices of key-value blocks in each Q_BLOCK_SIZE row tile.
    full_kv_num_blocks (Optional[Tensor]): Number of full kv_blocks in each Q_BLOCK_SIZE row tile.
    full_kv_indices (Optional[Tensor]): Indices of full key-value blocks in each Q_BLOCK_SIZE row tile.
    BLOCK_SIZE (Union[int, tuple[int, int]]): Size of KV_BLOCK_SIZE x Q_BLOCK_SIZE tiles.
    mask_mod (Optional[Callable]): Function to modify the mask.

Returns:
    BlockMask: Instance with full Q information generated via _transposed_ordered

Raises:
    RuntimeError: If kv_indices has < 2 dimensions.
    AssertionError: If only one of full_kv_* args is provided.
r   r   Nr   NNr   r   r   rR   )r   r   r   r   r   r   r   r   r   r   r   )r   r   r   
isinstancerD   r*   r   )clsr   r   r   r   r   r   r   r   r   r   r   r   q_length	kv_lengths                  r   from_kv_blocksBlockMask.from_kv_blocks  s%   < >>aJKK"d*40GH 	
U	
H
 &8&S#L!-&2224F&51!> 5?1!>&0#L0:-j#&&$1J'38!''+jm;H"((,z!}<I#/K#'!1+%/)!
 	
r    flattenc                    U(       a=  U R                   S   U R                   S   4nU R                  S   U R                  S   4nOU R                   4nU R                  4n/ UQU R                  PU R                  PU R                  PU R
                  PU R                  PU R                  PU R                  PU R                  PUQU R                  P7$ )z
Returns a tuple of the attributes of the BlockMask.

Args:
    flatten (bool): If True, it will flatten the tuple of (KV_BLOCK_SIZE, Q_BLOCK_SIZE)
r   rR   )r   r   r   r   r   r   r   r   r   r   r   )r   r   
block_sizer   s       r   as_tupleBlockMask.as_tuple:  s    //!,dooa.@AJ++A.0@0@0CDK//+J++-K


 OO
 ##	

   
 
 NN
 ""
 
 
 MM
 	
r    c                 f    U R                   R                  Gt n  n[        U5      U R                  -   $ r|   )r   r   tupler   )r   r   r   s      r   r   BlockMask.shapeV  s.     OO11QZ 4#3#333r    c                     SU R                    SU R                  5       S S3nU R                  5       R                  5       nX-  nUS-  nU$ )NzBlockMask(shape=z, sparsity=.2fz%, 

))r   sparsity	to_stringstrip)r   smask_strs      r   __str__BlockMask.__str__[  sM    tzzl+dmmoc5J%P>>#))+		U
r    r   c                    [        U[        5      (       d  U4OUn/ UQ[        S5      P[        S5      P[        S5      P7SS nU R                  R                  SS n[        S [        X#5       5       5      nU R                  U   nU R                  U   nU R                  b.  U R                  c   eU R                  U   nU R                  U   nOSnSn[        R                  UUUUU R                  SU R                  U R                  SLS9$ )am  
Returns a new BlockMask instance by getting the mask for the given index position.

Args:
    index: Index to apply to all attributes.

Example Usage:
    .. code-block:: python

        def causal_mask(b, h, q_idx, kv_idx):
            return q_idx >= kv_idx


        block_mask = create_block_mask(
            causal_mask, 4, 2, 512, 512, device="cuda"
        )
        assert block_mask.kv_num_blocks.shape == (4, 2, 4)
        assert block_mask.kv_indices.shape == (4, 2, 4, 4)

        # Index on batch dimension
        new_block_mask = block_mask[0]
        assert new_block_mask.kv_num_blocks.shape == (2, 4)
        assert new_block_mask.kv_indices.shape == (2, 4, 4)

        # Index on batch and head dimension
        new_block_mask = block_mask[0, 1]
        assert new_block_mask.kv_num_blocks.shape == (4,)
        assert new_block_mask.kv_indices.shape == (4, 4)

        # slicing on batch and head dimension
        new_block_mask = block_mask[0:2, 1:2]
        assert new_block_mask.kv_num_blocks.shape == (2, 1, 4)
        assert new_block_mask.kv_indices.shape == (2, 1, 4, 4)

        # slicing on batch, head, and query dimension
        new_block_mask = block_mask[
            0:2, 1:2, torch.tensor([1], dtype=torch.int32)
        ]
        assert new_block_mask.kv_num_blocks.shape == (2, 1, 1)
        assert new_block_mask.kv_indices.shape == (2, 1, 1, 4)
NrS   c              3      #    U  HP  u  p[        U[        5      (       a2  U* Us=::  a  S :  a  O  O[        X-   X-   S-   5      O[        XS-   5      OUv   MR     g7f)r   rR   N)r   rD   slice)r^   ins      r   r`   (BlockMask.__getitem__.<locals>.<genexpr>  sY      
 + !S!! *+a!U15!%!)$qa% +s   AA)r   r   r   r   )r   r   r   r   r   zipr   r   r   r!   r   r   r   r   )r   indexpaddedsizesnew_kv_num_blocksnew_kv_indicesnew_full_kv_num_blocksnew_full_kv_indicess           r   __getitem__BlockMask.__getitem__b  s,   T !+5% 8 8e@5@%+@uT{@E$K@!D""((!, 
 F*	
 
 !..u5/"".''333%)%<%<U%C""&"6"6u"=%)""&''"((!^^47 ( 	
 		
r    c                 T   S[         [        R                     4S jnSU R                  R                   SU R
                  R                   SU" U R                  5       SU" U R                  5       SU" U R                  5       SU" U R                  5       S	U" U R                  5       S
U" U R                  5       SU R                   SU R                   SU R                  5       S S[        U R                  S5      (       a  U R                  R                   OU R                   S3$ )Nxc                 $    U b  U R                   $ S $ r|   r   )r   s    r   shape_or_none)BlockMask.__repr__.<locals>.shape_or_none  s    m17755r    zBlockMask(
    kv_num_blocks=z,
    kv_indices=z,
    full_kv_num_blocks=z,
    full_kv_indices=z,
    q_num_blocks=z,
    q_indices=z,
    full_q_num_blocks=z,
    full_q_indices=z,
    BLOCK_SIZE=z,
    shape=z,
    sparsity=r   z%,
    mask_mod=r?   r   )r   rq   r	   r   r   r   r   r   r   r   r   r   r   r   hasattrr   r?   )r   r   s     r   __repr__BlockMask.__repr__  s8   	6Xell3 	6!!%!3!3!9!9 : ;"oo334 5&&3D4K4K&L%M N##01E1E#F"G H  -d.?.? @A B*4>>:; <%%243I3I%J$K L""/0C0C"D!E F"oo. / % MMOC0 16=dmmZ6X6XDMM22^b^k^kl m	
r    	new_q_len
new_kv_lenc                    XR                   S   -   S-
  U R                   S   -  nX R                   S   -   S-
  U R                   S   -  n[        U R                  U R                  X45      u  pVU R                  b5  U R
                  c   e[        U R                  U R
                  UU5      u  nnOS nS nU R                  UUUUU R                   U R                  5      $ )Nr   rR   )r   r   r   r   r   r   r   r   )	r   r   r   r   r   r   r   r   r   s	            r   _adjustBlockMask._adjust  s    !OOA$66:tq?QQ"__Q%77!;PQ@RR,J-
) "".''333 /''$$	&# &*""&"""OOMM
 	
r    c                 0    U R                   nS nU" U5      $ )zIReturns the number of elements (not accounting for sparsity) in the mask.c                 N    [         R                  " [        R                  U S5      $ NrR   )	functoolsreduceoperatormul)xss    r   _prodBlockMask.numel.<locals>._prod  s    ##HLL"a88r    r   )r   r   r  s      r   numelBlockMask.numel  s    

	9 U|r    c                     U R                  5       nU R                  R                  5       nU R                  b  X R                  R                  5       -  nUR	                  5       U R
                  S   -  U R
                  S   -  nX1-  nSSU-
  -  $ )zEComputes the percentage of blocks that are sparse (i.e. not computed)r   rR   d   )r  r   rd   r   itemr   )r   
total_sizecomputed_blockscomputed_sizedense_ratios        r   r   BlockMask.sparsity  s    ZZ\
,,002"".66::<<O',,.1CCdooVWFXX#0a+o&&r    c                     [        U R                  U R                  5      nU R                  b2  U R                  c   eU[        U R                  U R                  5      -  $ U$ )z;Returns a dense block that is equivalent to the block mask.)r   r   r   r   r   )r   partial_denses     r   to_denseBlockMask.to_dense  sd    )$*<*<dooN"".''333 #4'')=)=$   r    c           
        ^
^^^^ U R                  5       m
T
R                  Gt nmm[        U[        5      (       a  UmUmOUS:X  a  TmTmOUu  mmU
UUUU4S jn/ n[	        [
        R                  " U Vs/ s H  n[        U5      PM     sn6 5       HU  u  pxXr:X  a5  UR                  S5        UR                  S5        UR                  S5          OU" U6 n	UR                  U	5        MW     SR                  U5      $ s  snf )zReturns a string representation of the block mask. Quite nifty.

If grid_size is -1, prints out an uncompressed version. Warning, it can be quite big!
r   c            	      p  > / nUR                  U  5        SR                  [        U5      5      S-   nS nS n[        SU" TT5      5      n[        SU" TT5      5      n[	        STU5       HF  n[	        STU5       H-  nTn	U  H  n
X   n	M	     U" XXu-   2XU-   24   5      nX+S-  -  nM/     US-  nMH     U$ )Nz, 
c                 x    U R                  5       R                  5       R                  5       nUS:X  a  gUS:X  a  gg)NrR   u   █r    u   ░)floatmeanr  )section
percentages     r   summarize_sectionHBlockMask.to_string.<locals>.create_block_vis.<locals>.summarize_section  s6    $]]_11388:
? 1_ r    c                     XS-
  -   U-  $ r  r>   )abs     r   cdiv;BlockMask.to_string.<locals>.create_block_vis.<locals>.cdiv  s    U))r    rR   r   r   )appendjoinreversedmaxr   )	batch_idxdescriptorsvisr$  r)  row_stepcol_steprccur_maskidxcharr   max_colsmax_rowsr   r   s               r   create_block_vis-BlockMask.to_string.<locals>.create_block_vis	  s    K).))H[12T9C!* 1d8X67H1d8X67H1h1q(H5A)H(#+=  ), Q\!118|3C!CDD !8OC 6 t 2 Jr    z...z3To print out more, set BlockMask.to_string(limit=N)zNYou can also index (BlockMask[batch, head]) to choose a specific batch or headr  )
r  r   r   rD   	enumerate	itertoolsproductr   r+  r,  )r   	grid_sizelimitr   r;  	total_visr   r7  r/  	block_visr   r9  r:  r   r   s             @@@@@r   r   BlockMask.to_string  s    
 ]]_
*4*:*:'Xxi%% H H"_HH!*Hh 	  	D 	'*=*Qa*=>
NC |  '  !VW  d ()4IY'
 yy##  >s   5C<r   c                 l   ^ [        [        R                  U4S jU R                  SS95      n[	        U6 $ )a>  Moves the BlockMask to the specified device.

Args:
    device (torch.device or str): The target device to move the BlockMask to.
        Can be a torch.device object or a string (e.g., 'cpu', 'cuda:0').

Returns:
    BlockMask: A new BlockMask instance with all tensor components moved
    to the specified device.

Note:
    This method does not modify the original BlockMask in-place.
    Instead, it returns a new BlockMask instance where individual tensor attributes
    may or may not be moved to the specified device, depending on their
    current device placement.
c                 &   > U R                  T5      $ r|   )r   )r   r   s    r   <lambda>BlockMask.to.<locals>.<lambda>N  s    add6lr    F)r   )r   rq   r	   r   r!   )r   r   mapped_attributess    ` r   r   BlockMask.to;  s6    " *LL"MM%M(

 +,,r    )r   r   r   r   r   r   r   r   r   r   r   )T)r   r!   ))   rK  rc   )"r?   r@   rA   rB   rC   r   rD   rE   r	   r   _mask_mod_signaturer   classmethod_DEFAULT_SPARSE_BLOCK_SIZEr   rF   r   r   propertyr   r   r   r   r  r  r   r   r  r   rq   r   strr   rG   r>   r    r   r!   r!     sS   :x sCx  ((f%%6""''V$$c3h!!#!38_#! #! 	#!
 %V,#! "&)#! v&#! F##! $F+#! !(#! #s(O#! &#!J 
 04,02L2615!%G
G
 G
 %V,	G

 "&)G
 #uS#X./G
 ./G
 eCHo.G
 G
 G
R
 
8 4 4E
N
*
 
# 
:	'% 	'& @$D-u||S01 -k -r    r!   c                 |    U R                  5       U:  a'  U R                  S5      n U R                  5       U:  a  M'  U $ )Nr   )r   r   )r   r   s     r   _broadcast_to_dimrR  T  s0    
%%'C-KKN %%'C-Hr    c                     X-   S-
  U-  U-  $ r  r>   r   multiples     r   _round_up_to_multiplerV  Z  s    L1)H44r    maskseparate_full_blocksc           
         U R                   [        R                  :X  d   e[        U S5      n S n[        R                  R
                  R                  U SU" U R                  S   U5      SU" U R                  S   U5      45      n U R                  u  pVpxXq-  S:X  d   eX-  S:X  d   eU R                  XVXq-  XU-  U5      n U R                  SSSSSS	5      n U R                  SS/S
9n	U(       aO  X-  n
X:H  nU	S:  X:  -  nUR                  [        R                  S9nUR                  [        R                  S9nX4$ U	S:  nUR                  [        R                  S9nUS 4$ )Nrc   c                     [        X5      U -
  $ r|   )rV  rT  s     r   padding_needed_for_multiple@_convert_mask_to_block_mask.<locals>.padding_needed_for_multipleg  s    $Q1A55r    r   r   r   rR   r   rS   rb   r   r   )r   rq   rF   rR  nn
functionalpadr   viewpermuterd   r   int8)rW  Q_BLOCK_SIZEKV_BLOCK_SIZErX  r[  BHQKVmask_block_sumfull_block_sumfull_blockspartial_blockss                r   _convert_mask_to_block_maskrm  ^  s    ::###T1%D6 88""'

2F'

2E		
D **KA!q   """99	a]/BMD <<	1aAqD XXH  N %5$6(1,1PQ'***<!nn5::n6**'!+'***<t##r    	mask_modsc                  ^   ^  [        S T  5       5      (       d  [        ST  35      eU 4S jnU$ )z9Returns a mask_mod that's the union of provided mask_modsc              3   8   #    U  H  n[        U5      v   M     g 7fr|   callabler^   args     r   r`   or_masks.<locals>.<genexpr>       2	x}}	   )All inputs should be callable mask_mods: c                 l   > U R                  S[        R                  S9nT H  nXE" XX#5      -  nM     U$ Nr>   r   )r   rq   rF   r(  hq_idxkv_idxresultrW  rn  s         r   or_maskor_masks.<locals>.or_mask  s9    Ruzz2Dd177F r    allr   )rn  r  s   ` r   r(   r(     s3    2	222FykRSS Nr    c                  ^   ^  [        S T  5       5      (       d  [        ST  35      eU 4S jnU$ )z@Returns a mask_mod that's the intersection of provided mask_modsc              3   8   #    U  H  n[        U5      v   M     g 7fr|   rq  rs  s     r   r`   and_masks.<locals>.<genexpr>  rv  rw  rx  c                 l   > U R                  S[        R                  S9nT H  nXE" XX#5      -  nM     U$ rz  )r   rq   rF   r{  s         r   and_maskand_masks.<locals>.and_mask  s9    Bejj1Dd177F r    r  )rn  r  s   ` r   r)   r)     s3    2	222FykRSS Or    c                     U R                  5       S:X  d   eU R                  u  p4pVU R                  " X!/U R                  Q76 n U R                  SSSSSS5      R	                  X4XR-  Xa-  5      n U $ )Nrc   r   rS   r   rb   rR   )r   r   expandra  reshape)
block_maskrd  rc  re  rf  rg  rh  s          r   _convert_block_mask_to_maskr    s}    
 >>q   ""KA!""<RAQAQRJ##Aq!Q15==	a 2J r    r  r   r   rc  rd  c           
          U u  pV[        U5      nUb  [        U5      nOSn[        R                  US   US   US   US   X44UUS9$ )Nr   r   rR   )r   r   r   )r   r!   r   )	r  r   r   rc  rd  rl  rk  
partial_bmfull_bms	            r   $_create_sparse_block_from_block_maskr    sp     #-N">2J=N>
 ##11

 0 $  r    cudamod_fnre  rf  Q_LENKV_LENr   c                 p   Uc  SnUc  Sn[         R                  " SXS9n[         R                  " SX%S9n[         R                  " SX5S9n[         R                  " SXES9n	[        U 5      n
SSKJn  U" 5          U
[
        R                  :X  aa  U n[        USS9nU" [         R                  " XX4US9XgX5      n[         R                  " [         R                  " U5      SS	5      nUsSSS5        $ U
[
        R                  :X  a   U n[        US
S9nU" XgX5      nUsSSS5        $ [        e! , (       d  f       g= f)a  This function creates a mask tensor from a mod_fn function.

Args:
    mod_fn (Union[_score_mod_signature, _mask_mod_signature]): Function to modify attention scores.
    B (int): Batch size.
    H (int): Number of query heads.
    Q_LEN (int): Sequence length of query.
    KV_LEN (int): Sequence length of key/value.
    device (str): Device to run the mask creation on.

Returns:
    mask (Tensor): A mask tensor with shape (B, H, M, N).
NrR   r   )r   )TransformGetItemToIndex)r   )rj   FTr>   )rq   r   ri   ,torch._dynamo._trace_wrapped_higher_order_opr  rP   rT   ru   zerosr   isneginfrU   AssertionError)r  re  rf  r  r  r   r(  r|  mr   mod_typer  	score_modr   rW  r   s                   r   r&   r&     s   * 	yyQ)AQ)AQ-AQ.AV$HT	 	"(222I'	$?IEKKeFKQSTXC;;u~~c2E4@D 
#	" *333H&x;HA!'D 
#	" !  
#	"s   7A,D'-*D'!D''
D5r   c           	         [        U 5      nU[        R                  :X  d
   SU  35       eUc  SnUc  Sn[        U[        5      (       a  Un	Un
OUu  pU(       a>  [
        R                  " S[        5        [        R                  " [        5      " XX#XEU5      $ [        XX#XE5      n[        UU	U
SS9u  p[        X4U X44U	U
5      nU$ )a  This function creates a block mask tuple from a mask_mod function.

Args:
    mask_mod (Callable): mask_mod function. This is a callable that defines the
        masking pattern for the attention mechanism. It takes four arguments:
        b (batch size), h (number of heads), q_idx (query index), and kv_idx (key/value index).
        It should return a boolean tensor indicating which attention connections are allowed (True)
        or masked out (False).
    B (int): Batch size.
    H (int): Number of query heads.
    Q_LEN (int): Sequence length of query.
    KV_LEN (int): Sequence length of key/value.
    device (str): Device to run the mask creation on.
    BLOCK_SIZE (int or tuple[int, int]): Block size for the block mask. If a single int is provided it is used for both query and key/value.

Returns:
    BlockMask:  A BlockMask object that contains the block mask information.

Example Usage:
    .. code-block:: python

        def causal_mask(b, h, q_idx, kv_idx):
            return q_idx >= kv_idx


        block_mask = create_block_mask(causal_mask, 1, 1, 8192, 8192, device="cuda")
        query = torch.randn(1, 1, 8192, 64, device="cuda", dtype=torch.float16)
        key = torch.randn(1, 1, 8192, 64, device="cuda", dtype=torch.float16)
        value = torch.randn(1, 1, 8192, 64, device="cuda", dtype=torch.float16)
        output = flex_attention(query, key, value, block_mask=block_mask)
z4create-block_mask requires a mask_mod function! Got rR   a  _compile flag on create_block_mask was originally added to work around a torch.compile limitation. That limitation has since been addressed. So, to compile create_block_mask, we suggest doing torch.compile(create_block_mask). This still works for now, but will be removed in the future.T)rc  rd  rX  )ri   rP   rU   r   rD   r   r   DeprecationWarningrq   compiler%   r&   rm  r  )r   re  rf  r  r  r   r   _compiler  rc  rd  mask_tensorpartial_block_maskfull_block_maskr  s                  r   r%   r%     s    R X&H(111 
>xjI1 	yy*c""!"&0# m	
 }}./6:
 	
 h1VDK*E!#!	+' 6	-	J r    querykeyc           	          U R                   n[        R                  [        R                  " / SQ[        R
                  US9[        R                  " / SQ[        R
                  US9[        SS9$ )zDefault block mask for flex attention.
If users don't specify any block sparse mask info, we create this
empty block sparse mask. Which creates a BlockMask with 1 block that is the full length
of the query and key tensors.
)rR   rR   rR   r   )rR   rR   rR   rR   )rR   rR   )r   r   r   r   )r   r!   r   rq   onesr   r  _LARGE_SPARSE_BLOCK_SIZE)r  r  r   s      r   _create_empty_block_maskr  T  sS     \\F##jj%++fM;;|5;;vN+	 $  r    orig_mod_funcq_ntkv_ntis_score_modc                 B  ^ ^^^	^
 S nUR                   m	UR                   mU" T	UR                  R                  UR                  S-
     5      m
XL a  T
mO-U" TUR                  R                  UR                  S-
     5      mU(       a  UUU U	U
4S jnU$ UUU U	U
4S jnU$ )a  Adapter to convert a score_mod / mask_mod to be NJT-compatible. The given mod func
should be written as if operating over a single sequence at a item. This adapter will
handle conversion from indices operating over a "stacked sequence" of length ``sum(S)``
for sequence length ``S`` in the NJT to "sequence relative" indices in range ``[0, S)``.

Args:
    orig_mod_func (Callable): Function to modify attention scores. It takes four or five
        arguments, depending on whether a mask_mod or score_mod func is passed.
    q_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
        structure for query.
    kv_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
        structure for key / value.
    is_score_mod (bool): Indicates whether the mod function is a score_mod.

Returns:
    nt_score_mod: An NJT-compatible version of orig_score_mod
c                     [         R                  " XR                  [         R                  S9n[         R                  " XSS9S-
  nU$ )N)r   r   T)rightrR   )rq   r   r   r   searchsorted)offsetstotal_lengthrange_tensorseq_idxs       r   _build_seq_idx0_nested_mod_func_adapter.<locals>._build_seq_idx}  s;    ||u{{
 $$W$G!Kr    rR   c           
         > TU   nUTTU      -
  nUT	T
U      -
  nTU   T
U   :H  n[         R                  " UT" XX&U5      [        S5      5      $ )Nz-inf)rq   r   r   )rv   r(  r|  r}  r~  b_nestedq_nested	kv_nestedis_same_sequence
kv_offsets
kv_seq_idxr  	q_offsets	q_seq_idxs            r   nt_score_mod._nested_mod_func_adapter.<locals>.nt_score_mod  sq     'Hy5)9::HJv,>!??I(/:f3EE;; eqIFf	 r    c                 h   > TU   nUTTU      -
  nUTT	U      -
  nTU   T	U   :H  nT
" XAXV5      U-  $ r|   r>   )r(  r|  r}  r~  r  r  r  r  r  r  r  r  r  s           r   nt_mask_mod-_nested_mod_func_adapter.<locals>.nt_mask_mod  s]     'Hy5)9::HJv,>!??I(/:f3EE hBEUUUr    )_offsets_valuesr   _ragged_idx)r  r  r  r  r  r  r  r  r  r  r  s   `      @@@@r   _nested_mod_func_adapterr  c  s    4	 IJy$,,*<*<T=M=MPQ=Q*RSI}
 $MM 1 1A 56

 
	 
	 	V 	V r    c                 ,   Uc  UnUR                   UR                   :w  a  [        S5      e[        [        XUSS9UUUR                  R
                  UR                  S-
     UR                  R
                  UR                  S-
     UR                   UUS9$ )a
  This function creates a nested tensor compatible block mask tuple from a mask_mod
function. The returned BlockMask will be on the device specified by the input nested tensor.

Args:
    mask_mod (Callable): mask_mod function. This is a callable that defines the
        masking pattern for the attention mechanism. It takes four arguments:
        b (batch size), h (number of heads), q_idx (query index), and kv_idx (key/value index).
        It should return a boolean tensor indicating which attention connections are allowed
        (True) or masked out (False).
    B (int): Batch size.
    H (int): Number of query heads.
    q_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
        structure for query. The block mask will be constructed to operate on a "stacked
        sequence" of length ``sum(S)`` for sequence length ``S`` from the NJT.
    kv_nt (torch.Tensor): Jagged layout nested tensor (NJT) that defines the sequence length
        structure for key / value, allowing for cross attention. The block mask will be
        constructed to operate on a "stacked sequence" of length ``sum(S)`` for sequence
        length ``S`` from the NJT. If this is None, ``q_nt`` is used to define the structure
        for key / value as well. Default: None
    BLOCK_SIZE (int or tuple[int, int]): Block size for the block mask. If a single int is
        provided it is used for both query and key/value.

Returns:
    BlockMask:  A BlockMask object that contains the block mask information.

Example Usage:
    .. code-block:: python

        # shape (B, num_heads, seq_len*, D) where seq_len* varies across the batch
        query = torch.nested.nested_tensor(..., layout=torch.jagged)
        key = torch.nested.nested_tensor(..., layout=torch.jagged)
        value = torch.nested.nested_tensor(..., layout=torch.jagged)


        def causal_mask(b, h, q_idx, kv_idx):
            return q_idx >= kv_idx


        block_mask = create_nested_block_mask(
            causal_mask, 1, 1, query, _compile=True
        )
        output = flex_attention(query, key, value, block_mask=block_mask)

    .. code-block:: python

        # shape (B, num_heads, seq_len*, D) where seq_len* varies across the batch
        query = torch.nested.nested_tensor(..., layout=torch.jagged)
        key = torch.nested.nested_tensor(..., layout=torch.jagged)
        value = torch.nested.nested_tensor(..., layout=torch.jagged)


        def causal_mask(b, h, q_idx, kv_idx):
            return q_idx >= kv_idx


        # cross attention case: pass both query and key/value NJTs
        block_mask = create_nested_block_mask(
            causal_mask, 1, 1, query, key, _compile=True
        )
        output = flex_attention(query, key, value, block_mask=block_mask)
zLcreate_nested_block_mask(): Expected q_nt and kv_nt to be on the same deviceFr  rR   )r   r   r  )r   
ValueErrorr%   r  r  r   r  )r   re  rf  r  r  r   r  s          r   r'   r'     s    N }{{ell"Z
 	
  UK		4++a/0E--12{{  r    value
return_lse
return_auxc                 `   Uc  0 O
[        U5      nUR                  SS5        UR                  SS5        UR                  SS5        UR                  SS5        U R                  R                  S:H  =(       d9    UR                  R                  S:H  =(       d    UR                  R                  S:H  nUnSnUb  UR                  nUR
                  nSU;  d   eSUS'   U(       d$  [        R                  " 5       US'   U(       a  SUS'   S	U;  d   eXS	'   U(       a  U(       a  [        S
5      eU$ )Nr5   Fr6   r7   r8   TcpuOUTPUT_LOGSUMEXP
OUTPUT_MAXz-Returning max scores is not supported on CPU.)	dict
setdefaultr   typerK   rL   rq   is_grad_enabledNotImplementedError)	r  r  r  r  kernel_optionsr  any_inputs_on_cpu_device
output_lse
output_maxs	            r   _apply_kernel_optionsr    s9    *1RtN7KNmU34e<5u=j$/ 	U" 	&::??e#	&<<%  JJ^^
**
 ^333)-N%& .3-B-B-D)*# 27N-. ~---#-< J ""QRR r    c                     U R                  S5      UR                  S5      :w  a0  [        SU R                  S5       SUR                  S5       S35      eg )Nr   zJExpect query and key/value to have the same embedding dimension but got E=z and E=.)r   r  r  r  r  s      r   _validate_embed_dimr  G  sU    zz"~"%B(~Q@
 	
 &r    c                     1 SknU R                   R                  U;  a#  [        SU R                   R                   S35      eg)zTODO: Remove once non cuda/cpu devices support is added
We only need to check query since we have already that q,k,v are on the same device
>   r  hpuxpur  zTFlexAttention is only supported on CUDA, CPU or HPU devices. Found input tensors on z device.N)r   r  r  )r  r  r  supported_devicess       r   _validate_devicer  O  sL     6|| 11&&+ll&7&7%8B
 	
 2r    c                 N   U R                   UR                   :w  d  UR                   UR                   :w  a  [        S5      eU R                   (       a  U R                  c<  UR                   (       a  UR                  c  UR                   (       a  UR                  b  [        S5      eg g )NzFlexAttention does not support mixed nested tensor / non-nested tensor inputs. Please file an issue requesting this if it is important to you.zFlexAttention does not support nested tensors that are non-contiguous with holes. Please file an issue requesting this if it is important to you.)	is_nestedr  _lengthsr  s      r   _validate_nestednessr  [  s    #--'3==EOO+KN
 	
 
U^^7MMcll6OO :N
 	
 !;Or    c                    S[         S[        4S jnS[         S[        4S jn[        R                  [        R                  4nU R
                  nXe;   =(       an    [        R                  R                  SL=(       aK    [        R                  R                  S5      S:  =(       a"    [        R                  R                  S5      S:  nU(       d  XU4$ U" U 5      (       d  U R                  5       n U" U5      (       d  UR                  5       nU" U5      (       d0  UR                  S	S
5      R                  5       R                  S	S
5      nXU4$ )a  
Enforce memory layouts for query, key, and value tensors.

For non-FP8 dtypes, no action is taken.

For FP8 dtypes, we enforce the following memory layouts:
- Query tensor must be in row-major memory layout, as it will be the left-operand in the FP8 GEMM `q @ k.T`.
- Key tensor must be in row-major memory layout, as it will be transposed when used as the right-operand
  in the FP8 GEMM `q @ k.T`, meaning it will correctly be in column-major memory layout for the GEMM.
- Value tensor must be in column-major memory layout, as it will be the right-operand in the FP8 GEMM `softmax_scores @ v`.

Returns the query, key, and value tensors with the enforced memory layouts.
tensorr   c                 .    U R                  5       S   S:H  $ )Nr   rR   strider  s    r   is_row_major*_enforce_mem_layouts.<locals>.is_row_major      }}r"a''r    c                 .    U R                  5       S   S:H  $ )Nr   rR   r  r  s    r   is_col_major*_enforce_mem_layouts.<locals>.is_col_major  r  r    Nr  )   	   )
   r   r   r   )r	   rF   rq   float8_e4m3fnfloat8_e5m2r   versionr  get_device_capabilityr   r   )r  r  r  r  r  
fp8_dtypesgemm_precisionshould_enforce_mem_layouts           r   _enforce_mem_layoutsr  n  s.   "(V ( ((V ( ( 	J [[N 	$ 	?MMd*	?JJ,,V4>	? JJ,,V4w>	  %5     " nn B'224>>r2Fur    )r  r  scale
enable_gqar  c	                ^   [        XU5        [        XU5        [        XU5        [        XU5        [	        XU5      u  pnU R                  5       S:w  d(  UR                  5       S:w  d  UR                  5       S:w  a  [        S5      eU(       dT  U R                  S5      UR                  S5      :w  a0  [        SU R                  S5       SUR                  S5       S35      eU(       a<  U R                  S5      n
UR                  S5      nX-  S:w  a  [        S	U
 SU S
35      eU R                  S5      UR                  S5      :w  a  Uc0  [        SU R                  S5       SUR                  S5       S
35      eUR                  R                  S5      U R                  S5      :w  aL  [        SU R                  S5       SUR                  S5       SUR                  R                  S5       S
35      eUc  [        nOXU R                  (       aG  U R                  U R                  5      UR                  U R                  5      :X  a  U OUn[        X0USS9nUc  [        X5      nUR                  S   [         :X  a  UR                  S   [         :X  a  GOU R                  (       a|  UR"                  S   U R$                  R                  U R                  S-
  5      :w  aA  ['        SUR"                   SU R$                  R                  U R                  S-
  5       35      eGODUR"                  S   nUR"                  S   nU R                  S5      U:  d  UR                  S5      U:  a=  [        SUR"                   SU R                  S5       SUR                  S5       S35      eU R                  S5      U:  a  UR                  S5      U::  d*  U R                  S5      U::  aR  UR                  S5      U:  a=  [        SUR"                   SU R                  S5       SUR                  S5       S35      eU R                  S5      U:X  d   eUR                  S5      U:X  d   eUc(  S[(        R*                  " U R                  S5      5      -  nU R,                  UR                  R,                  :w  a0  ['        SU R,                   SUR                  R,                   S
35      eU(       a  U	b  [        S5      eU(       a  U	c  [/        S S![0        S"9  [3        U UUUUU	5      nS#[4        [6           S$[8        4S% jn[:        R<                  R?                  5       (       aw  XU4 HC  n[:        R@                  RC                  US5        [:        R@                  RC                  US5        ME     [E        U UUUURG                  5       UU5      u  nnnU" UUUXS&9$ [H        (       d
  [/        S'S(S)9  [:        R@                  RK                  5       (       d  ['        S*5      eSS+K&J'n  S, n[Q        5          [:        R@                  RR                  RU                  5          [W        5          [Y        5        nU(       a	  U" U5      nOS-n[H        (       a  UnO[:        RZ                  " UUSS.9nU" U UUUURG                  5       UU5      u  nnnSSS5        SSS5        SSS5        SSS5        U" WWWXS&9$ ! , (       d  f       N/= f! , (       d  f       N8= f! , (       d  f       NA= f! , (       d  f       NJ= f)/a1  This function implements scaled dot product attention with an arbitrary attention score modification function.

This function computes the scaled dot product attention between query, key, and value tensors with a user-defined
attention score modification function. The attention score modification function will be applied after the attention
scores have been calculated between the query and key tensors. The attention scores are calculated as follows:

The ``score_mod`` function should have the following signature:

.. code-block:: python

    def score_mod(
        score: Tensor,
        batch: Tensor,
        head: Tensor,
        q_idx: Tensor,
        k_idx: Tensor
    ) -> Tensor:

Where:
    - ``score``: A scalar tensor representing the attention score,
      with the same data type and device as the query, key, and value tensors.
    - ``batch``, ``head``, ``q_idx``, ``k_idx``: Scalar tensors indicating
      the batch index, query head index, query index, and key/value index, respectively.
      These should have the ``torch.int`` data type and be located on the same device as the score tensor.

Args:
    query (Tensor): Query tensor; shape :math:`(B, Hq, L, E)`. For FP8 dtypes, should be in row-major memory layout for optimal performance.
    key (Tensor): Key tensor; shape :math:`(B, Hkv, S, E)`. For FP8 dtypes, should be in row-major memory layout for optimal performance.
    value (Tensor): Value tensor; shape :math:`(B, Hkv, S, Ev)`. For FP8 dtypes, should be in column-major memory layout for optimal performance.
    score_mod (Optional[Callable]): Function to modify attention scores. By default no score_mod is applied.
    block_mask (Optional[BlockMask]): BlockMask object that controls the blocksparsity pattern of the attention.
    scale (Optional[float]): Scaling factor applied prior to softmax. If none, the default value is set to :math:`\frac{1}{\sqrt{E}}`.
    enable_gqa (bool): If set to True, enables Grouped Query Attention (GQA) and broadcasts key/value heads to query heads.
    return_lse (bool): Whether to return the logsumexp of the attention scores. Default is False. **Deprecated**: Use ``return_aux=AuxRequest(lse=True)`` instead.
    kernel_options (Optional[FlexKernelOptions]):
        Options to control the behavior of the underlying Triton kernels.
        See :class:`FlexKernelOptions` for available options and usage examples.
    return_aux (Optional[AuxRequest]): Specifies which auxiliary outputs to compute and return.
        If None, only the attention output is returned. Use ``AuxRequest(lse=True, max_scores=True)``
        to request both auxiliary outputs.

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

    When ``return_aux`` is not None:
        aux (AuxOutput): Auxiliary outputs with requested fields populated.

    When ``return_aux`` is None (deprecated paths):
        lse (Tensor): Log-sum-exp of attention scores; shape :math:`(B, Hq, L)`. Only returned if ``return_lse=True``.

Shape legend:
    - :math:`N: \text{Batch size} ... : \text{Any number of other batch dimensions (optional)}`
    - :math:`S: \text{Source sequence length}`
    - :math:`L: \text{Target sequence length}`
    - :math:`E: \text{Embedding dimension of the query and key}`
    - :math:`Ev: \text{Embedding dimension of the value}`

.. warning::
    `torch.nn.attention.flex_attention` is a prototype feature in PyTorch.
    Please look forward to a more stable implementation in a future version of PyTorch.
    Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype

rc   z-NYI: query, key, and value must be 4D tensorszGExpect query and key/value to have the same number of heads but got Hq=z	 and Hkv=z&. Try setting enable_gqa=True for GQA.rR   r   zMExpect number of query heads to be a multiple of kv heads for GQA but got Hq=r  NzlExpect query and key/value to have the same batch size, or non-none block_mask, but got block_mask=None, Bq=z
, and Bkv=zxExpect query and key/value to have the same batch size, or block_mask and query to have the same batch size, but got Bq=z, Bkv=z, B_block_mask=Tr  r   zblock_mask of shape zJ is not compatible with nested tensor input with total sequence length of r   z,block_mask was created for block_mask.shape=z but got q_len=z and kv_len=zz. As the block mask was created for a smaller length than you're using it for, you likely need to create a new block mask.ad  . As the block mask was created for a larger length than you're using it for, you can either 1. create a new block mask with the correct length, or 2. 'adjust' the existing block mask to the correct length by calling block_mask._adjust(q_len, kv_len). This essentially 'crops' the block mask to the upper left corner, which does not work for all mask_mods!g      ?z=Expect q/k/v and block_mask to be on the same device but got z and z|Cannot specify both return_lse and return_aux. return_lse is deprecated, please use return_aux=AuxRequest(lse=True) instead.deprecated_return_lsezjreturn_lse is deprecated and will be removed in v2.10. Please use return_aux=AuxRequest(lse=True) instead.)r   r  r  c                V   [         R                  " S5      nU=(       d    USL=(       a    UR                  nUSL=(       a    UR                  nU(       a  UR	                  5       S:  a  X-  OSnU(       a  UR	                  5       S:  a  X%-  OSnUb  U [        UUS94$ U(       a  X4$ U $ )zFNormalize stats and build return value (aux-aware, legacy-compatible).g       @Nr   )rK   rL   )mathlogrK   rL   r  r"   )	r   rK   rL   r  r  ln2
return_max
lse_scaled
max_scaleds	            r   _finalize_outputs)flex_attention.<locals>._finalize_outputsf  s     hhsmL:T#9#Ljnn
t+E
0E0E
#-#))+/SY
!+
0@0@0BQ0FJT 	 !	%  
 ?"
r    )r  r  flex_attention_performancea  flex_attention called without torch.compile() - this will use an unfused implementation that materializes the full scores matrix instead of generating a fused kernel.

SOLUTION: Use torch.compile(flex_attention)(...)

If you want to debug your score_mod/mask_mod, you can set:
torch.nn.attention.flex_attention._FLEX_ATTENTION_DISABLE_COMPILE_DEBUG = True

This will allow you to use print statements or breakpoints. Note: This doesn't work with the backwards pass and may produce incorrect results.)r   r   z&flex_attention requires dynamo support)+make_eager_backend_with_torch_function_modec                      [        U 0 UD6$ r|   )flex_attention_hop)argskwargss     r   _flex_attention_hop_wrapper3flex_attention.<locals>._flex_attention_hop_wrapper  s    !42622r    eager)backend	fullgraph).r   r  r  r  r  r   r  r   r  r   r}   r  r  r  r  r   r  r   r  r   r  sqrtr   r   FutureWarningr  r   r#   rF   rq   compileris_dynamo_compiling_dynamomark_staticr  r   %_FLEX_ATTENTION_DISABLE_COMPILE_DEBUGis_dynamo_supported torch._dynamo.backends.debuggingr  r   utilsdisable_cache_limitr   r   r  )r  r  r  r  r  r  r  r  r  r  HqHkvkvblock_mask_q_lenblock_mask_kv_lenr  r   r   rK   rL   r  r  metadata_moder  flex_fns                            r   r   r     s   Z U+E*U'U+,U?Eyy{a3779>UYY[A-=!"QRREJJrNchhrl:**R.)388B<. A34
 	

 ZZ]hhqk8q= T3%q2  zz!}#//4zz!}oZQR}TUW  ##((+uzz!}<#jjm_F388A;-zOgOgOlOlmnOoNppqs  		 zz%++,9J9J0KK  	
 -YrPTU	-e9
 	a $<<!!!$(@@ 		B5==#5#5e6G6G!6K#LL&z'7'7&8 91161C1CEDUDUXYDY1Z0[]  M &++B/&,,R0::b>,,?P0P>z?O?O>PP_`e`j`jkm`n_oo{|  }E  }E  FH  }I  |J JK K 
 JJrN--#((2,BS2Sjjn 00SXXb\DU5U>z?O?O>PP_`e`j`jkm`n_oo{|  }E  }E  FH  }I  |J Ju u  zz"~!1111xx|0000}dii

2//||z//666||nE**B*B*I*I)J!M
 	
 j,\
 	
 

*#B"		
 +N
 Z( : ~~))++e$AMM%%a,MM%%a, %  2! 
S* !jZ
 	
 103a		
 ==,,..CDD3 
	]]  446>@>@M$GV   #*<<"="'--7TX# ,3!"++-&,(Cj A A 7 
 6 S* 1 A@ A@ 76 
 	sU   ,)\\ [<+A[+	[<
\\+
[95[<<
\
\
\	\
\,)r>   r   F)r  r|   )NNNFFN)TrC   r  r[   r>  r  r  r   enumr   typingr   r   r   r   r   rq   r	   r
   ImportErrortyping_extensionsr   &torch._higher_order_ops.flex_attentionr   r  torch._higher_order_ops.utilsr   torch._prims_commonr   "torch.fx.experimental.proxy_tensorr   r   torch.nn.attention._utilsr   torch.utils._pytreer   r$  setr   rP  rE   UserWarningr  Warningr   __all___score_mod_signaturerL  r$   r#   r"   rP   ri   r   rD   listrF   ru   r}   r*   rN  r  r   r   r   r   r!   rR  rV  rm  r(   r)   r  r  r&   r%   r  r  r'   r  r  r  r  r  r   r>   r    r   <module>r@     s   P        = =  , ." X > . ; -& ). %ES ! >I((!(-1'](	(   H& PQ ?GH r2	 r2j (
 (	 	)h )#4 )2 )+01++(3-$%+ (3-$%+ Chsm,,-	+
 +\  	
  JJ
J J 	J
 J ! "  f <U66>%: 6& 6v 6



 
 	
O- O-d5 ,,!&	+$
+$ 	+$
 68F##$+$\, 1D - 2E   -+ 	$ 33fhv../x  sCx 	
  D $.!&(;;<.!}.! }.! 	.!
 .! .! .!n $.HN!N}N }N 	N
 N N c5c?*+N NbF  I O-/BBCO
,,O <<O 	O
 !445On %).HX!X}X }X ,,	X
 ELL!X c5c?*+X XB (,44	4 4 	4 $4n
v 
F 
6 
	
F 	
 	
 	

 
V 
F 
&888'-8
5<<u||348~ 15&*!26b (,bb	b b ,-	b
 #b E?b b b ./b $b 65(%	0A*BBCbk,  ,++,
  .--.s#   L9 M 9M	M	MM