
    Χg                        d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZ ddlZddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlm Z  g dZ!eeeeeegef         Z"eeeeegef         Z# G d de	          Z$dede$fdZ%	 	 	 dPdedeee&         df         deee&         df         dee&eee&                  f         de'f
dZ(dedededededefdZ)dededededef
d Z*d!Z+d"Z,d#ed$efd%Z-defd&Z.d#ed$efd'Z/ G d( d)          Z0d* Z1d+ Z2e+e+dfd,ed-e'deeee         f         fd.Z3d/e#de#fd0Z4d/e#de#fd1Z5e+e+fdefd2Z6e+e+fd3eeee         f         d4ee         d5e&d6e&de0f
d7Z7	 	 dQd9ee"e#f         d:ee&         d;ee&         d<e&d=e&d>e8d?e'defd@Z9d4ed:e&d;e&d<e&d=e&d>e8d5e&d6e&fdAZ:d8e+dfd4e#d:ee&         d;ee&         d<e&d=e&d>e8dBee&ee&e&f         f         de0fdCZ;dDedEede0fdFZ<dDedEedGedHe'fdIZ=dDedEedGefdJZ>	 	 	 	 	 	 dRdDedEedGedKee"         d3ee0         dLee?         dMe'dHe'dNeee8ef                  deeeeef         f         fdOZdS )SzIThis module implements the user facing API for flex_attention in PyTorch.    N)nullcontext)Enum)AnyCallableDictListOptionalTupleUnion)Tensor)flex_attentionTransformGetItemToIndex)_set_compilation_env)-_temp_remove_pre_dispatch_torch_function_mode)_supported_head_dim_validate_sdpa_input)tree_map_only)	BlockMaskr   create_block_maskcreate_maskor_masks	and_masks	noop_maskc                       e Zd ZdZdZdZdZdS )_ModificationTypezEnum 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
             N)__name__
__module____qualname____doc__	SCORE_MODMASK_MODUNKNOWN     ]/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/nn/attention/flex_attention.pyr   r   *   s)          IHGGGr'   r   fnreturnc                    t          d t          j        |           j                                        D                       }|dk    s|dk    sJ |dk    rt
          j        S |dk    rt
          j        S t
          j        S )a\  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   N   K   | ] }|j         t          j        j        k    d V  !dS )r   N)defaultinspect	Parameterempty).0params     r(   	<genexpr>z _get_mod_type.<locals>.<genexpr>=   sA        =G-333 	
3333 r'         )	sumr.   	signature
parametersvaluesr   r#   r$   r%   )r)   num_positional_argss     r(   _get_mod_typer;   6   s       &r**5<<>>    
 !##':a'?'?'?'?a **		!	! )) ((r'   r&   Fprefix.suffixout_dims	group_dimc                 r    g }g d}|r|dgz  }|dgz  }|D ]}t          j        | ||z   |z   |          }  | S )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   NNrA   )r   NNN)in_dimsr>   )torchvmap)r)   r<   r=   r>   r?   
dimensionsdimss          r(   _vmap_for_bhqkvrG   L   s    2 OQJ  J  
!
 	

  J  O OZFTMF$:XNNNIr'   scorebatchheadtoken_qtoken_kvc                     | S Nr&   )rH   rI   rJ   rK   rL   s        r(   	_identityrO   z   s	     Lr'   c                 P    |                      dt          j        | j                  S )zReturns a noop mask_modr&   )sizedtypedevice)new_onesrC   boolrS   )rI   rJ   rK   rL   s       r(   r   r      s      >>rEL>IIIr'      i   @num_blocks_in_rowcol_indicesc                    	 |j         d         	|j         d         | j         d d         }| j        	fd}|}t          t          |                    D ]}t	          j        |d          } || |          }|S )Nc                    |                     	dz   t          j                  }t          j        	t          j                                      d          }t          j        t          j                  }||                     d          k     }t          j        ||          }d|||f<   |d d d f                                         S )Nr   rR   rR   rS   r[   )	new_zerosrC   int32arangeint	unsqueezewhere
contiguous)
kv_num_blocks
kv_indices
dense_maskrow_indices	col_range
index_maskvalid_indicesrS   num_colsnum_rowss
          r(   create_dense_onez+_ordered_to_dense.<locals>.create_dense_one   s    ))(HqL)TT
l859VLLLVV
 
 L6JJJ	!8!8!<!<<
 J
HEE 23
;-.!!!YhY,'22444r'   )r   r   )rB   )shaperS   rangelenrC   rD   )
rW   rX   
batch_dimsro   create_dense_batched_outrS   rm   rn   s
          @@@r(   _ordered_to_denserw      s     $H $H"("-J%F5 5 5 5 5 5 5  ,3z??## P P$z*>OOO

0+
>
>CJr'   c                 b   |                      t          j                  } |                     d          }t          j        | ddd          }|                     t          j                                                  |                     t          j                                                  fS )Nr]   r[   dimT)rz   
descendingstable)torC   r`   r6   argsortre   )rh   rW   rX   s      r(   _dense_to_orderedr      s    U[11J"2..-
tDQQQKU[))4466u{##..00 r'   c                 h    t          | |          }t          |                    dd                    S )NrZ   r[   )rw   r   	transpose)rW   rX   denses      r(   _transpose_orderedr      s.    /==EU__R44555r'   c                   ^   e Zd ZU dZeed<   eed<   ee         ed<   ee         ed<   ee         ed<   ee         ed<   ee         ed<   ee         ed	<   eeef         ed
<   e	ed<   dededee         dee         dee         dee         dee         d	ee         d
eeef         de	fdZ
eddedfdededee         dee         d
eeeeef         f         dee	         fd            ZddefdZd Zd dZd Zed             Zd ZdefdZdefdZd!dZdeej        ef         dd fdZdS )"r   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.
    rf   rg   full_kv_num_blocksfull_kv_indicesq_num_blocks	q_indicesfull_q_num_blocksfull_q_indices
BLOCK_SIZEmask_modc                    |                                 dk     rt          d          |
J d            |
J d            |
J d            |
J d            |d u |d u k    s
J d            |d u |d u k    s
J d            || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        d S )	Nr   )BlockMask must have at least 2 dimensionszkv_num_blocks must be providedzkv_indices must be providedzq_num_blocks must be providedzq_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)rz   RuntimeErrorrf   rg   r   r   r   r   r   r   r   r   )selfrf   rg   r   r   r   r   r   r   r   r   s              r(   __init__zBlockMask.__init__  s2    >>aJKKK((*J(((%%'D%%%'')H'''$$&B$$$"d*t#
 
 
T
 
 
 "T)d"
 
 
R
 
 
 +$"4.("!2,$ r'   Nc                 N   |                                 dk     rt          d          |du |du k    s
J d            t          ||          \  }}||J t          ||          \  }	}
nd\  }	}
t          |t                    r||f}||nt
          } | |||||||	|
||
  
        S )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   NN)
rf   rg   r   r   r   r   r   r   r   r   )rz   r   r   
isinstancerb   r   )clsrf   rg   r   r   r   r   r   r   r   r   s              r(   from_kv_blockszBlockMask.from_kv_blocks+  s   8 >>aJKKK"d*t#
 
 
T
 
 

 #5]J"O"Oi)"...0B"O1 1-~~ 1;-~j#&& 	2$j1J'388s'!1+%/)!
 
 
 	
r'   Tflattenc                     |r| j         d         | j         d         fn| j         f}| j        | j        | j        | j        | j        | j        | j        | j        g|| j	        R S )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   r   )
r   rf   rg   r   r   r   r   r   r   r   )r   r   
block_sizes      r(   as_tuplezBlockMask.as_tuplej  s     9@WT_Q!344doEW 	
 O# N"
 
 M
 
 	
r'   c                     d| j          d|                                 dd}|                                                                 }||z  }|dz  }|S )NzBlockMask(shape=z, sparsity=.2fz%, 

))rp   sparsity	to_stringstrip)r   smask_strs      r(   __str__zBlockMask.__str__  sY    PtzPPdmmooPPPP>>##))++	X	U
r'   r*   c                     | j         |         }| j        |         }| j        $| j        J | j        |         }| j        |         }nd}d}t                              ||||| j        d          S )a  
        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)
        Nr   r   )rf   rg   r   r   r   r   r   )r   indexnew_kv_num_blocksnew_kv_indicesnew_full_kv_num_blocksnew_full_kv_indicess         r(   __getitem__zBlockMask.__getitem__  s    J !.u5/".'333%)%<U%C""&"6u"=%)""&''" ( 
 
 	
r'   c                    dt           t          j                 fd}d| j        j         d| j        j         d || j                   d || j                   d || j                   d || j	                   d	 || j
                   d
 || j                   d| j         d| j         d|                                 ddt          | j        d          r| j        j        n| j         dS )Nxc                     | | j         nd S rN   rp   )r   s    r(   shape_or_nonez)BlockMask.__repr__.<locals>.shape_or_none  s    m177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	   rC   r   rf   rp   rg   r   r   r   r   r   r   r   r   hasattrr   r   )r   r   s     r(   __repr__zBlockMask.__repr__  si   	6Xel3 	6 	6 	6 	6!%!3!9 "o3  '4mD4K&M&M  $1=1E#F#F	 
 !.d.? @ @  +]4>::  &3]43I%J%J  #0-0C"D"D  #o    !MMOO5  7>dmZ6X6XkDM22^b^k  	
r'   c                     | j         j        ^ }}}| j         j        d         | j        d         z  }| j         j        d         | j        d         z  }t          |||gz             S )zReturns the shape of the mask.rZ   r   r[   r   )rg   rp   r   tuple)r   rs   q_lengthru   	kv_lengths        r(   rp   zBlockMask.shape  sc     $(?#8 Xq?(,tq/AAO)"-0BB	Z8Y"77888r'   c                 ,    | j         }d } ||          S )zIReturns the number of elements (not accounting for sparsity) in the mask.c                 B    t          j        t          j        | d          S Nr   )	functoolsreduceoperatormul)xss    r(   _prodzBlockMask.numel.<locals>._prod  s    #HL"a888r'   r   )r   rp   r   s      r(   numelzBlockMask.numel  s(    
	9 	9 	9 uU||r'   c                    |                                  }| j                                        }| j        || j                                        z  }|                                | j        d         z  | j        d         z  }||z  }dd|z
  z  S )zEComputes the percentage of blocks that are sparse (i.e. not computed)Nr   r   d   )r   rf   r6   r   itemr   )r   
total_sizecomputed_blockscomputed_sizedense_ratios        r(   r   zBlockMask.sparsity  s    ZZ\\
,0022".t6::<<<O',,..1CCdoVWFXX#j0a+o&&r'   c                     t          | j        | j                  }| j        &| j        J |t          | j        | j                  z  S |S )z;Returns a dense block that is equivalent to the block mask.)rw   rf   rg   r   r   )r   partial_denses     r(   to_densezBlockMask.to_dense  s[    )$*<doNN".'333 #4')=$ $   r'      r   r5   c                   	
 |                                  		j        ^ }t          |t                    r||
n|dk    r
n|\  
	
fd}g }t	          t          j        d |D                        D ]f\  }}||k    rA|                    d           |                    d           |                    d            n || }|                    |           gd                    |          S )zReturns a string representation of the block mask. Quite nifty.

        If grid_size is None, prints out an uncompressed version. Warning, it can be quite big!
        r[   c            	         g }|                     |             d                    t          |                    dz   }d }d }t          d |                    }t          d |                    }t	          d|          D ]O}t	          d|          D ]6}}	| D ]
}
|	|
         }	 ||	|||z   |||z   f                   }||dz  z  }7|dz  }P|S )Nz, 
c                     |                                                                                                  }|dk    rdS |dk    rdS dS )Nr   u   █r    u   ░)floatmeanr   )section
percentages     r(   summarize_sectionzHBlockMask.to_string.<locals>.create_block_vis.<locals>.summarize_section  sH    $]]__113388::
?? 51__3 5r'   c                     | |dz
  z   |z  S r   r&   )abs     r(   cdivz;BlockMask.to_string.<locals>.create_block_vis.<locals>.cdiv  s    QU))r'   r   r   r   )appendjoinreversedmaxrq   )	batch_idxdescriptorsvisr   r   row_stepcol_steprccur_maskidxcharrh   max_colsmax_rowsrm   rn   s               r(   create_block_visz-BlockMask.to_string.<locals>.create_block_vis  s9   K)~...))H[1122T9C! ! !* * * 1dd8X6677H1dd8X6677H1h11 	 	q(H55 $ $A)H( 1 1#+C=,, Q\!11q8|3C!CD D 4!8OCCtJr'   c                 ,    g | ]}t          |          S r&   )rq   )r1   is     r(   
<listcomp>z'BlockMask.to_string.<locals>.<listcomp>/  s    ===Qa===r'   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   rp   r   rb   	enumerate	itertoolsproductr   r   )r   	grid_sizelimitrs   r   	total_visr   r   	block_visrh   r   r   rm   rn   s            @@@@@r(   r   zBlockMask.to_string  sZ   
 ]]__
*4*:'Xxi%% 	+ H HH"__HHH!*Hh 	  	  	  	  	  	  	  	  	D 	'==*===>
 
 	( 	(NC e||  '''  !VWWW  d   (()4IY''''yy###r'   rS   c                 z    t          t          j        fd|                     d                    }t	          | S )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 invidual tensor attributes
            may or may not be moved to the specified device, depending on their
            current device placement.
        c                 .    |                                S rN   )r}   )r   rS   s    r(   <lambda>zBlockMask.to.<locals>.<lambda>P  s    add6ll r'   F)r   )r   rC   r   r   r   )r   rS   mapped_attributess    ` r(   r}   zBlockMask.to=  sE    " *L""""MM%M((
 

 +,,r'   )T)r*   r   )r   r5   )r   r    r!   r"   r   __annotations__r	   r
   rb   _mask_mod_signaturer   classmethod_DEFAULT_SPARSE_BLOCK_SIZEr   r   rU   r   r   r   r   propertyrp   r   r   r   r   r   rC   rS   strr}   r&   r'   r(   r   r      s        : :v  ((((f%%%%6""""''''V$$$$c3h!!!!#!#! #! %V,	#!
 "&)#! v&#! F##! $F+#! !(#! #s(O#! &#! #! #! #!J 
 04,02L26<
 <
<
 <
 %V,	<

 "&)<
 #uS#X./<
 ./<
 <
 <
 [<
|
 
 
 
 
 
0  5
 5
 5
 5
n
 
 
* 9 9 X9  	'% 	' 	' 	' 	'&    @$ @$ @$ @$D-u|S01 -k - - - - - -r'   r   c                     |                                  |k     r-|                     d          } |                                  |k     -| S )Nr   )rz   rc   )r   rz   s     r(   _broadcast_to_dimr  V  s:    
%%''C--KKNN %%''C--Hr'   c                     | |z   dz
  |z  |z  S r   r&   )r   multiples     r(   _round_up_to_multipler  \  s    L1)H44r'   maskseparate_full_blocksc                 H   | j         t          j        k    sJ t          | d          } | j        \  }}}}||z  dk    sJ ||z  dk    sJ |                     ||||z  |||z  |          } |                     dddddd          } |                     ddg	          }|r\||z  }	||	k    }
|dk    ||	k     z  }|                    t          j	        
          }|
                    t          j	        
          }
||
fS |dk    }|                    t          j	        
          }|d fS )Nr5   r   r   r   r   r4   rZ   r[   ry   r]   )
rR   rC   rU   r  rp   viewpermuter6   r}   int8)r  KV_BLOCK_SIZEQ_BLOCK_SIZEr  BHQKVmask_block_sumfull_block_sumfull_blockspartial_blockss               r(   _convert_mask_to_block_maskr  `  sg    :####T1%%D*KAq!R|q    """"99	1a<r]/BM D <<	1aAq D XXH   N  
$%5$6(1,.1PQ'***<<!nn5:n66{**'!+'***<<t##r'   	mask_modsc                  h     t          d  D                       st          d             fd}|S )z9Returns a mask_mod that's the union of provided mask_modsc              3   4   K   | ]}t          |          V  d S rN   callabler1   args     r(   r3   zor_masks.<locals>.<genexpr>  (      22x}}222222r'   )All inputs should be callable mask_mods: c                 v    |                      dt          j                  }D ]}| || |||          z  }|S Nr&   r]   )r_   rC   rU   r   hq_idxkv_idxresultr  r  s         r(   or_maskzor_masks.<locals>.or_mask  sJ    Ruz22 	8 	8Ddd1a777FFr'   allr   )r  r'  s   ` r(   r   r     sZ    22	22222 TRyRRSSS     Nr'   c                  h     t          d  D                       st          d             fd}|S )z@Returns a mask_mod that's the intersection of provided mask_modsc              3   4   K   | ]}t          |          V  d S rN   r  r  s     r(   r3   zand_masks.<locals>.<genexpr>  r  r'   r  c                 v    |                      dt          j                  }D ]}| || |||          z  }|S r!  )rT   rC   rU   r"  s         r(   and_maskzand_masks.<locals>.and_mask  sJ    Bej11 	8 	8Ddd1a777FFr'   r(  )r  r-  s   ` r(   r   r     sZ    22	22222 TRyRRSSS     Or'   c                     |                                  dk    sJ | j        \  }}}} | j        ||g| j        R  } |                     dddddd                              ||||z  ||z            } | S )Nr5   r   r   r   r4   r   )rz   rp   expandr
  reshape)
block_maskr  r  r  r  r  r  s          r(   _convert_block_mask_to_maskr2    s    
 >>q    "KAq!R""<RAQRRRJ##Aq!Q155==	1a,] 2 J r'   r1  r   r  r  c                     | \  }}t          |          }|t          |          }nd}t                              |d         |d         |d         |d         ||f|          S )Nr   r   r   r   )r   r   r   )r1  r   r  r  r  r  
partial_bmfull_bms           r(   $_create_sparse_block_from_block_maskr6    sy     #-NK">22J#K00##11

!<0 $   r'   cudamod_fnr  r  Q_LENKV_LENrS   _compilec           
         |d}|d}t          j        d||          }t          j        d||          }t          j        d||          }	t          j        d||          }
|rt                      }nt                      }t	          |           }|5  |t
          j        k    ro| }t          |d          } |t          j        |||||          |||	|
          }t          j	        t          j
        |          dd          }|cddd           S |t
          j        k    r/| }t          |d	          } ||||	|
          }|cddd           S t          # 1 swxY w Y   dS )
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).
    Nr   r   )rS   )r   )r<   FTr&   )rC   ra   r   r   r;   r   r#   rG   zerosrd   isneginfr$   AssertionError)r8  r  r  r9  r:  rS   r;  r   r#  mnctxmod_type	score_modrv   r  r   s                    r(   r   r     s   , 	yyQ&)))AQ&)))AQf---AQv...A  (mm%''V$$H	 ! !(222I'	$???I)EK1eVFKKKQPQSTVWXXC;u~c22E4@@D! ! ! ! ! ! ! ! *333H&x;;;H8Aq!Q''D! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !s   A3E2EEE"Ec           	      b    t          | |||||d          }t          |||d          \  }	}
|	|
fS )zWork around for being unable to instantiate __torch_function__ mode under compile.
    `create_block_mask` will compile this inner function and wrap the call to this
    with the __torch_function__ mode.
    T)r;  )r  r  r  )r   r  )r   r  r  r9  r:  rS   r  r  mask_tensorpartial_block_maskfull_block_masks              r(   _create_block_mask_innerrI    sS     h1eVVdSSSK*E#!!	+ + +' ..r'   r   c                    t          |           }|t          j        k    sJ d|              t          }	|d}|d}t	          |t
                    r|}
|}n|\  }
}|dk     r|}
nt          ||
          }t          ||          }|rt          j        |	dd          }	t                      5   |	| |||||||
          \  }}t          ||f|           }ddd           n# 1 swxY w Y   |S )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.
        KV_BLOCK_SIZE (int): Block size of block mask for each query.
        Q_BLOCK_SIZE (int): Block size of block mask for each key/value.
        _compile (bool): Whether to compile the mask creation.

    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 Nr   rV   TF)	fullgraphdynamic)r;   r   r$   rI  r   rb   r  rC   compiler   r6  )r   r  r  r9  r:  rS   r   r;  rC  
inner_funcr  r  rG  rH  r1  s                  r(   r   r     st   T X&&H%....HhHH 	/..)Jyy*c"" 1!"&0#ms{{%e\::"6=99F N]:uMMM
	 	"	" 
 
.8jaE66=,/
 /
+O :18
 

	
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 s   +(CC#&C#querykeyc                     | j         }t                              t          j        g dt          j        |          t          j        g dt          j        |          t                    S )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.
    )r   r   r   r^   )r   r   r   r   )rf   rg   r   )rS   r   r   rC   onesr`   r=  _LARGE_SPARSE_BLOCK_SIZE)rO  rP  rS   s      r(   _create_empty_block_maskrT  [  s_     \F##j%+fMMM;|||5;vNNN+ $   r'   value
return_lsec                     |i nt          |          }|                    dd           |                    dd           d|vsJ d|d<   |s/| j        p|j        p|j        }|ot          j                    }||d<   |S )NROWS_GUARANTEED_SAFEFPRESCALE_QKOUTPUT_LOGSUMEXPT)dict
setdefaultrequires_gradrC   is_grad_enabled)rO  rP  rU  rV  kernel_optionsany_inputs_require_gradoutput_logsumexps          r(   _apply_kernel_optionsrb  i  s     *1RRtN7K7KN4e<<<mU333 ^3333)-N%& >K3#4K8K 	  3Nu7L7N7N-=)*r'   c                    |                      d          |                     d          k    r<t          d|                      d           d|                     d           d          t          |                      d                    r"t          |                     d                    s<t          d|                      d           d|                     d           d          |                     d          |                      d          k    r<t          d|                     d           d|                      d           d          d S )Nr[   zJExpect query and key/value to have the same embedding dimension but got E=z and E=.zKNYI: Currently non power of 2 embedding dimension are not supported. Got E=z and Ev=ziNYI: Currently value embedding dimension must be less than or equal to query embedding dimension. Got Ev=)rQ   
ValueErrorr   )rO  rP  rU  s      r(   _validate_embed_dimrf  ~  sf   zz"~~"%%@B@ @03@ @ @
 
 	
 	EJJrNN++
0CEJJrNN0S0S
 ?ZZ^^? ?-2ZZ^^? ? ?
 
 	
 zz"~~

2&&?jjnn? ?-2ZZ^^? ? ?
 
 	
 '&r'   rD  scale
enable_gqar_  c	                 
   t          | ||           t          | ||           |                                 dk    s0|                                dk    s|                                dk    rt          d          |sh|                     d          |                    d          k    r<t          d|                     d           d|                    d           d          |rI|                     d          }	|                    d          }
|	|
z  dk    rt          d	|	 d|
 d
          |t          }|t          | |          }|*dt          j	        |                     d                    z  }t          | ||||          }t          j                                        r| ||fD ]B}t          j                            |d           t          j                            |d           Ct!          | ||||                                ||          \  }}|r||t          j        d          z  fS |S t          j                                        st)          d          d }t+                      5  t          j        j                                        5  t1                      5   t          j        |dd          | ||||                                ||          \  }}|r=||t          j        d          z  fcddd           cddd           cddd           S |cddd           cddd           cddd           S # 1 swxY w Y   	 ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )a#  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)`.
        key (Tensor): Key tensor; shape :math:`(B, Hkv, S, E)`.
        value (Tensor): Value tensor; shape :math:`(B, Hkv, S, Ev)`.
        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.
        kernel_options (Optional[Dict[str, Any]]): Options to pass into the Triton kernels.

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

    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

    r5   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.r   r   zMExpect number of query heads to be a multiple of kv heads for GQA but got Hq=rd  Ng      ?r[   r   z&flex_attention requires dynamo supportc                      t          | i |S rN   )flex_attention_hop)argskwargss     r(   _flex_attention_hop_wrapperz3flex_attention.<locals>._flex_attention_hop_wrapper  s    !426222r'   eagerT)backendrK  )r   rf  rz   NotImplementedErrorrQ   re  rO   rT  mathsqrtrb  rC   compileris_dynamo_compiling_dynamomark_staticrl  r   logis_dynamo_supportedr   r   utilsdisable_cache_limitr   rM  )rO  rP  rU  rD  r1  rg  rh  rV  r_  HqHkvr   rv   lsero  s                  r(   r   r     s	   @ U+++sE***yy{{a37799>>UYY[[A-=-=!"QRRR 
EJJrNNchhrll::4**R..4 43688B<<4 4 4
 
 	

  ZZ]]hhqkk8q==2 2 2+.2 2 2  
 	-eS99
}di

2///* N ~))++ e$ 	- 	-AM%%a,,,M%%a,,,,%3y**=*=*?*?
 
S  	dhqkk)))J=,,.. ECDDD3 3 3 
		  ] 4466 	 	>@@  5=/D   ''))"
 
S  dhqkk 11      	 	 	 	 	 	 	       "       	 	 	 	 	 	 	               	 	 	 	 	 	 	 	 	 	 	 	 	 	 	                 ss   4$M8M 'AM=M 	M8"M#M /M8MM MM M8 M$	$M8'M$	(M88M<?M<)r&   r   F)r7  F)NNNFFN)@r"   r   r.   r   rs  r   
contextlibr   enumr   typingr   r   r   r   r	   r
   r   rC   r   &torch._higher_order_ops.flex_attentionr   rl  r   torch._higher_order_ops.utilsr   "torch.fx.experimental.proxy_tensorr   torch.nn.attention._utilsr   r   torch.utils._pytreer   __all___score_mod_signaturer   r   r;   rb   rU   rG   rO   r   r   rS  rw   r   r   r   r  r  r  r   r   r2  r6  r   r   rI  r   rT  rb  rf  r   r&   r'   r(   <module>r     s   P O            " " " " " "       D D D D D D D D D D D D D D D D D D               ? > > > > >      P O O O O O O O - - - - - -     H& PQ ?GH 	 	 	 	 	 	 	 	)h )#4 ) ) ) )2 )+01+ ++(3-$%+ (3-$%+ Chsm,,-	+
 + + + +\  	
     JJ
J J 	J
 J J J J ! "  f    <U    6& 6v 6 6 6 6
T- T- T- T- T- T- T- T-n  5 5 5 -+!&	$ $
$ 	$
 68F##$$ $ $ $B, 1D    - 2E      -+  	   " 42	 fhv../x   	
    < 3! 3!&(;;<3!}3! }3! 	3!
 3! 3! 3! 3! 3! 3! 3!l//
/ / 	/
 / / / / / / /< .HG G!G}G }G 	G
 G G c5c?*+G G G G GTF  I    '-;?   *
v 
F 
6 
 
 
 
4 15&*!/3H HH	H H ,-	H
 #H E?H H H T#s(^,H 65(()H H H H H Hr'   