
    Vh$                        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ZddlmZ ddl	m
Z
mZmZmZ ddlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ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#	 	 	 d[d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$eef   fd%Z.d"ed#efd&Z/d'ed(ed)e%d*e%fd+Z0 G d, d-      Z1d. Z2d/ Z3e+e+dfd0ed1e'de$eee   f   fd2Z4d3e!de!fd4Z5d3e!de!fd5Z6e+e+fdefd6Z7e+e+fd7e$eee   f   d8ee   d9e$e%e%f   d:e%d;e%de1fd<Z8	 d\d>ee e!f   d?ee%   d@ee%   dAe%dBe%dCe9defdDZ:d=e+dfd8e!d?ee%   d@ee%   dAe%dBe%dCe9dEee%e$e%e%f   f   de1fdFZ;dGedHede1fdIZ<dJee e!f   dKej                  dLej                  dMe'dee e!f   f
dNZ=de+dfd8e!d?ee%   d@ee%   dKej                  dLeej                     dEee%e$e%e%f   f   de1fdOZ>dGedHedPedQe'fdRZ?dGedHedPefdSZ@dGedHedPefdTZAdGedHedPefdUZB	 	 	 	 	 	 d]dGedHedPedVee    d7ee1   dWeeC   dXe'dQe'dYeeDe9e
f      deee$eef   f   fdZZy)^zIThis module implements the user facing API for flex_attention in PyTorch.    N)Enum)AnyCallableOptionalUnion)Tensor)TransformGetItemToIndex)flex_attention)_set_compilation_env))_temp_remove_metadata_torch_function_mode-_temp_remove_pre_dispatch_torch_function_mode)_supported_head_dim_validate_sdpa_input)tree_map_only)	BlockMaskr
   create_block_maskcreate_maskcreate_nested_block_maskor_masks	and_masks	noop_maskc                       e Zd ZdZdZdZdZy)_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     Q/home/dcms/DCMS/lib/python3.12/site-packages/torch/nn/attention/flex_attention.pyr   r   )   s     IHGr%   r   fnreturnc                    t        d t        j                  |       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(  rd  / yw)r   N)defaultinspect	Parameterempty).0params     r&   	<genexpr>z _get_mod_type.<locals>.<genexpr><   s0      ==G--333 	
s   35      )	sumr,   	signature
parametersvaluesr   r!   r"   r#   )r'   num_positional_argss     r&   _get_mod_typer9   5   s      &&r*55<<> 
 !#':a'???a ***		! ))) (((r%   Fprefix.suffixout_dims	group_dimc                 x    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   NNr?   )r   NNN)in_dimsr<   )torchvmap)r'   r:   r;   r<   r=   
dimensionsdimss          r&   _vmap_for_bhqkvrE   K   sp    2 OQJJ !
 	

  J  OZZFTMF$:XNOIr%   scorebatchheadtoken_qtoken_kvc                     | S Nr$   )rF   rG   rH   rI   rJ   s        r&   	_identityrM   y   s	     Lr%   c                 Z    | j                  dt        j                  | j                        S )zReturns a noop mask_modr$   )sizedtypedevice)new_onesrA   boolrQ   )rG   rH   rI   rJ   s       r&   r   r      s!     >>rELL>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                    |j                  	dz   t        j                        }t        j                  	t        j                        j                  d      }t        j                  t        j                        }|| j                  d      k  }t        j                  ||      }|j                  d      |||f<   |d d d f   j                         S )Nr   rP   rP   rQ   rY   r$   )		new_zerosrA   int32arangeint	unsqueezewhererR   
contiguous)
kv_num_blocks
kv_indices
dense_maskrow_indices	col_range
index_maskvalid_indicesrQ   num_colsnum_rowss
          r&   create_dense_onez+_ordered_to_dense.<locals>.create_dense_one   s    ))(HqL)T
ll8599VLVV
 LL6J	!8!8!<<
 J
HE 2<1D1DR1H
;-.!YhY,'2244r%   )r   r   )r@   )shaperQ   rangelenrA   rB   )
rU   rV   
batch_dimsrm   create_dense_batched_outrQ   rk   rl   s
          @@@r&   _ordered_to_denseru      s      $H  $H"(("-J%%F5  ,3z?# P$zz*>OP 0+
>CJr%   c                 T   | j                  t        j                        } | j                  d      }t        j                  | ddd      }|j                  t        j                  t        j
                        |j                  t        j                  t        j
                        fS )Nr[   rY   dimT)rx   
descendingstable)memory_format)torA   r^   r4   argsortcontiguous_format)rf   rU   rV   s      r&   _dense_to_orderedr      s|    U[[1J"2.--
tDQKU[[8O8OPu{{%2I2IJ r%   c                 P    t        | |      }t        |j                  dd            S )NrX   rY   )ru   r   	transpose)rU   rV   denses      r&   _transpose_orderedr      s%    /=EU__R455r%   
num_blocksindicesnew_num_rowsnew_num_colsc                    |d d d d d |d |f   }| d d d d d |f   } t        j                  | |k  | |      } t        j                  || d d d d d d d f   k  d      j                  t         j                        } | |fS )NrY   rw   )rA   rb   r4   r|   r^   )r   r   r   r   s       r&   _adjust_num_blocks_and_indicesr      s     aM\M=L=89GAq-<-/0JZ,6
LQJ7Z1a%>>BGJJ5;;WJwr%   c                   *   e Zd ZU dZeeef   ed<   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eef   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dfdededee   dee   deeeeef   f   dee	   deeeef      fd       Zd defdZed        Zd Zd!dZd Zdedef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y)#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.
    seq_lengthsrd   re   full_kv_num_blocksfull_kv_indicesq_num_blocks	q_indicesfull_q_num_blocksfull_q_indices
BLOCK_SIZEmask_modc                 b   |j                         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       || _        || _        || _        || _        || _        || _        || _        || _	        |	| _
        |
| _        || _        y )	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)rx   RuntimeErrorr   rd   re   r   r   r   r   r   r   r   r   )selfr   rd   re   r   r   r   r   r   r   r   r   s               r&   __init__zBlockMask.__init__  s    >>aJKK(J*JJ(%D'DD%'H)HH'$B&BB$"d*t#
 	UT	U 
 "T)d"
 	SR	S 
 '*$"4.("!2,$ r%   Nc                 t   |j                         dk  rt        d      |du |du k(  sJ d       t        ||      \  }}	||J t        ||      \  }
}nd\  }
}t        |t              r||f}||nt
        }|.|j                  d   |d   z  }|	j                  d   |d   z  }||f} | |||||||	|
|||	      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   NNrX   r   r   )r   rd   re   r   r   r   r   r   r   r   r   )rx   r   r   
isinstancer`   r   rn   )clsrd   re   r   r   r   r   r   r   r   r   r   q_length	kv_lengths                 r&   from_kv_blockszBlockMask.from_kv_blocks;  s   : >>aJKK"d*t#
 	UT	U 

 #5]J"Oi)"...0B"O1-~ 1;-~j#&$j1J'38!''+jm;H!+jm;I#Y/K#'!1+%/)!
 	
r%   flattenc                    |r=| j                   d   | j                   d   f}| j                  d   | j                  d   f}n| j                   f}| j                  f}g || j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  || j                  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   r   rd   re   r   r   r   r   r   r   r   )r   r   
block_sizer   s       r&   as_tuplezBlockMask.as_tuple  s    //!,dooa.@AJ++A.0@0@0CDK//+J++-K


 OO
 ##	

   
 
 NN
 ""
 
 
 MM
 	
r%   c                 f    | j                   j                  ^ }}}t        |      | j                  z   S rL   )re   rn   tupler   )r   rq   rs   s      r&   rn   zBlockMask.shape  s.     OO11QZ 4#3#333r%   c                     d| j                    d| j                         dd}| j                         j                         }||z  }|dz  }|S )NzBlockMask(shape=z, sparsity=.2fz%, 

))rn   sparsity	to_stringstrip)r   smask_strs      r&   __str__zBlockMask.__str__  sO    tzzl+dmmoc5J%P>>#))+	X	U
r%   r(   c           	         | j                   |   }| j                  |   }| j                  -| j                  J | j                  |   }| j                  |   }nd}d}t        j                  ||||| j                  d| j                        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   r   )rd   re   r   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""&"6"6u"=%)""&''"(( ( 
 	
r%   c                 N   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| j                         ddt        | j                  d      r| j                  j                    dS | j                   dS )Nxc                 "    | | j                   S d S rL   rn   )r   s    r&   shape_or_nonez)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   rA   r   rd   rn   re   r   r   r   r   r   r   r   r   hasattrr   r   )r   r   s     r&   __repr__zBlockMask.__repr__  sL   	6Xell3 	6!!%!3!3!9!9 : ;"oo334 5&&3D4K4K&M%N O##01E1E#F"G H  -d.?.? @A B*4>>:; <%%243I3I%J$K L""/0C0C"D!E F"oo. / % MMOC0 16=dmmZ6XDMM22l m	
 _c^k^kl m	
r%   	new_q_len
new_kv_lenc                    || j                   d   z   dz
  | j                   d   z  }|| j                   d   z   dz
  | j                   d   z  }t        | j                  | j                  ||      \  }}| j                  4| j
                  J t        | j                  | j
                  ||      \  }}nd }d }| j                  ||||| j                   | j                        S )Nr   r   )r   r   rd   re   r   r   r   r   )	r   r   r   r   r   r   r   r   r   s	            r&   _adjustzBlockMask._adjust  s    !DOOA$66:tq?QQ"T__Q%77!;PQ@RR,J|-
)> "".''333 /''$$	&# &*""&"""OOMM
 	
r%   c                 0    | j                   }d } ||      S )zIReturns the number of elements (not accounting for sparsity) in the mask.c                 L    t        j                  t        j                  | d      S Nr   )	functoolsreduceoperatormul)xss    r&   _prodzBlockMask.numel.<locals>._prod  s    ##HLL"a88r%   r   )r   rn   r   s      r&   numelzBlockMask.numel  s    

	9 U|r%   c                 "   | j                         }| j                  j                         }| j                  || j                  j                         z  }|j	                         | j
                  d   z  | j
                  d   z  }||z  }dd|z
  z  S )zEComputes the percentage of blocks that are sparse (i.e. not computed)r   r   d   )r   rd   r4   r   itemr   )r   
total_sizecomputed_blockscomputed_sizedense_ratios        r&   r   zBlockMask.sparsity  s    ZZ\
,,002"".t66::<<O',,.1CCdooVWFXX#j0a+o&&r%   c                     t        | j                  | j                        }| j                  1| j                  J |t        | j                  | j                        z  S |S )z;Returns a dense block that is equivalent to the block mask.)ru   rd   re   r   r   )r   partial_denses     r&   to_densezBlockMask.to_dense&  sd    )$*<*<dooN"".''333 #4'')=)=$   r%   c           
        
 | j                         

j                  ^ }t        |t              r||n|dk(  rn|\  
fd}g }t	        t        j                  |D cg c]  }t        |       c}       D ]U  \  }}||k(  r5|j                  d       |j                  d       |j                  d        n || }	|j                  |	       W dj                  |      S c c}w )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!
        rY   c            	      n   g }|j                  |         dj                  t        |            dz   }d }d }t        d |            }t        d |            }t	        d|      D ]F  }t	        d|      D ]/  }}	| D ]  }
|	|
   }		  ||	|||z   |||z   f         }||dz  z  }1 |dz  }H |S )Nz, 
c                 t    | j                         j                         j                         }|dk(  ry|dk(  ryy)Nr   u   █r    u   ░)floatmeanr   )section
percentages     r&   summarize_sectionzHBlockMask.to_string.<locals>.create_block_vis.<locals>.summarize_sectionG  s6    $]]_11388:
? 1_ r%   c                     | |dz
  z   |z  S r   r$   )abs     r&   cdivz;BlockMask.to_string.<locals>.create_block_vis.<locals>.cdivP  s    QU))r%   r   r   r   )appendjoinreversedmaxro   )	batch_idxdescriptorsvisr   r   row_stepcol_steprccur_maskidxcharrf   max_colsmax_rowsrk   rl   s               r&   create_block_visz-BlockMask.to_string.<locals>.create_block_vis@  s    K).))H[12T9C!* 1d8X67H1d8X67H1h1 	q(H5 $A)H( 1#+C=1, Q\!11q8|3C!CDD 4!8OC$ t	 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   rn   r   r`   	enumerate	itertoolsproductro   r   r   )r   	grid_sizelimitrq   r   	total_visir   r   	block_visrf   r   r   rk   rl   s             @@@@@r&   r   zBlockMask.to_string0  s   
 ]]_
*4*:*:'Xxi% H H"_HH!*Hh 	  	D 	'*=Qa=>
 	(NC e|  '  !VW  d ()4IY'	( yy##  >s   -C0rQ   c                 p    t        t        j                  fd| j                  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                 &    | j                        S rL   )r|   )r   rQ   s    r&   <lambda>zBlockMask.to.<locals>.<lambda>  s    add6l r%   F)r   )r   rA   r   r   r   )r   rQ   mapped_attributess    ` r&   r|   zBlockMask.tor  s6    " *LL"MM%M(

 +,,r%   )T)r(   r   ))   r  r3   ) r   r   r   r    r   r`   __annotations__r   r   _mask_mod_signaturer   classmethod_DEFAULT_SPARSE_BLOCK_SIZEr   r   rS   r   propertyrn   r   r   r   r   r   r   r   r   r   rA   rQ   strr|   r$   r%   r&   r   r      sD   :x sCx  ((f%%6""''V$$c3h!!%!38_%! %! 	%!
 %V,%! "&)%! v&%! F#%! $F+%! !(%! #s(O%! &%!N 
 04,02L2615B
B
 B
 %V,	B

 "&)B
 #uS#X./B
 ./B
 eCHo.B
 B
H
 
8 4 46
p
*
 
# 
:	'% 	'& @$D-u||S01 -k -r%   r   c                 v    | j                         |k  r%| j                  d      } | j                         |k  r%| S )Nr   )rx   ra   )r   rx   s     r&   _broadcast_to_dimr
    s0    
%%'C-KKN %%'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           
         | j                   t        j                  k(  sJ t        | d      } d }t        j                  j
                  j                  | d || j                  d   |      d || j                  d   |      f      } | j                  \  }}}}||z  dk(  sJ ||z  dk(  sJ | j                  ||||z  |||z  |      } | j                  dddddd	      } | j                  ddg
      }	|rY||z  }
|	|
k(  }|	dkD  |	|
k  z  }|j                  t        j                        }|j                  t        j                        }||fS |	dkD  }|j                  t        j                        }|d fS )Nr3   c                      t        | |      | z
  S rL   )r  r  s     r&   padding_needed_for_multiplez@_convert_mask_to_block_mask.<locals>.padding_needed_for_multiple  s    $Q1A55r%   r   rY   rX   r   r   r   r2   rw   r[   )rP   rA   rS   r
  nn
functionalpadrn   viewpermuter4   r|   int8)r  Q_BLOCK_SIZEKV_BLOCK_SIZEr  r  BHQKVmask_block_sumfull_block_sumfull_blockspartial_blockss                r&   _convert_mask_to_block_maskr$    s    ::###T1%D6 88""'

2F'

2E		
D **KAq!R|q   """99	1a<r]/BMD <<	1aAqD XXH  N %5$6(1,.1PQ'***<!nn5::n6{**'!+'***<t##r%   	mask_modsc                  R     t        d  D              st        d         fd}|S )z9Returns a mask_mod that's the union of provided mask_modsc              3   2   K   | ]  }t        |        y wrL   callabler/   args     r&   r1   zor_masks.<locals>.<genexpr>       2x}2   )All inputs should be callable mask_mods: c                 t    | j                  dt        j                        }D ]  }| || |||      z  } |S Nr$   r[   )r]   rA   rS   r   hq_idxkv_idxresultr  r%  s         r&   or_maskzor_masks.<locals>.or_mask  sB    Ruzz2 	8Dd1a77F	8r%   allr   )r%  r6  s   ` r&   r   r     s0    2	22FykRSS Nr%   c                  R     t        d  D              st        d         fd}|S )z@Returns a mask_mod that's the intersection of provided mask_modsc              3   2   K   | ]  }t        |        y wrL   r(  r*  s     r&   r1   zand_masks.<locals>.<genexpr>  r,  r-  r.  c                 t    | j                  dt        j                        }D ]  }| || |||      z  } |S r0  )rR   rA   rS   r1  s         r&   and_maskzand_masks.<locals>.and_mask  sB    Bejj1 	8Dd1a77F	8r%   r7  )r%  r<  s   ` r&   r   r     s0    2	22FykRSS Or%   c                     | j                         dk(  sJ | j                  \  }}}} | j                  ||g| j                   } | j                  dddddd      j	                  ||||z  ||z        } | S )Nr3   r   r   r   r2   r   )rx   rn   expandr  reshape)
block_maskr  r  r  r  r  r  s          r&   _convert_block_mask_to_maskrA    s    
 >>q   ""KAq!R"""<RAQAQRJ##Aq!Q15==	1a,] 2J r%   r@  r   r   r  r  c           	          | \  }}t        |      }|t        |      }nd}t        j                  |d   |d   |d   |d   ||f||      S )Nr   r   r   r   )r   r   r   )	r@  r   r   r  r  r#  r"  
partial_bmfull_bms	            r&   $_create_sparse_block_from_block_maskrE    st     #-NK">2J=N>
 ##11

 -0 $  r%   cudamod_fnr  r  Q_LENKV_LENrQ   c           
         |d}|d}t        j                  d||      }t        j                  d||      }t        j                  d||      }t        j                  d||      }	t        |       }
t               5  |
t        j
                  k(  rh| }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 Y   yxY w)
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   )rQ   )r   )r:   FTr$   )rA   r_   r9   r	   r   r!   rE   zerosrb   isneginfr"   AssertionError)rG  r  r  rH  rI  rQ   r   r2  mnmod_type	score_modrt   r  r   s                  r&   r   r   	  s5   * 	yyQ&)AQ&)AQf-AQv.AV$H	 	" !(222I'	$?IEKK1eVFKQPQSTVWXC;;u~~c2E4@D! ! *333H&x;HAq!Q'D! ! ! ! !s   >A2D8:.D82D88Er   c           	         t        |       }|t        j                  k(  s
J d|         |d}|d}t        |t              r|}	|}
n|\  }	}
|r?t        j                  dt                t        j                  t              | ||||||      S t        | |||||      }t        ||	|
d      \  }}t        ||f| ||f|	|
      }|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.
        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 r   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)r  r  r  )r9   r   r"   r   r`   warningswarnDeprecationWarningrA   compiler   r   r$  rE  )r   r  r  rH  rI  rQ   r   _compilerP  r  r  mask_tensorpartial_block_maskfull_block_maskr@  s                  r&   r   r   8  s	   P X&H%...I	=hZHI.yy*c"!"&0#m m	
 0u}}./aE66:
 	
 h1eVVDK*E!#!	+' 6	_-	J r%   querykeyc                     | j                   }t        j                  t        j                  g dt        j
                  |      t        j                  g dt        j
                  |      t        d      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   )r   r   )rd   re   r   r   )rQ   r   r   rA   onesr^   rK  _LARGE_SPARSE_BLOCK_SIZE)r[  r\  rQ   s      r&   _create_empty_block_maskr`    sS     \\F##jj%++fM;;|5;;vN+	 $  r%   orig_mod_funcq_ntkv_ntis_score_modc                 4   	
 d }|j                   	|j                    |	|j                  j                  |j                  dz
           
||u r
n- ||j                  j                  |j                  dz
           |r 	
fd}|S  	
fd}|S )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                     t        j                  || j                  t         j                        }t        j                  | |d      dz
  }|S )N)rQ   rP   T)rightr   )rA   r_   rQ   r^   searchsorted)offsetstotal_lengthrange_tensorseq_idxs       r&   _build_seq_idxz0_nested_mod_func_adapter.<locals>._build_seq_idx  s?    ||u{{
 $$Wl$G!Kr%   r   c           
          |   }||      z
  }|	
|      z
  }|   
|   k(  }t        j                  | | ||||      t        d            S )Nz-inf)rA   rb   r   )rF   r   r2  r3  r4  b_nestedq_nested	kv_nestedis_same_sequence
kv_offsets
kv_seq_idxra  	q_offsets	q_seq_idxs            r&   nt_score_modz._nested_mod_func_adapter.<locals>.nt_score_mod  su     'Hy5)9::HJv,>!??I(/:f3EE;; eXq(IFf	 r%   c                 l    |   }||      z
  }|	|      z
  }|   	|   k(  } 
||||      |z  S rL   r$   )r   r2  r3  r4  ro  rp  rq  rr  rs  rt  ra  ru  rv  s           r&   nt_mask_modz-_nested_mod_func_adapter.<locals>.nt_mask_mod  sa     'Hy5)9::HJv,>!??I(/:f3EE 1h	BEUUUr%   )_offsets_valuesrn   _ragged_idx)ra  rb  rc  rd  rm  rw  ry  rs  rt  ru  rv  s   `      @@@@r&   _nested_mod_func_adapterr}    s    4	 IJy$,,*<*<T=M=MPQ=Q*RSIu}
 $J0C0CEDUDUXYDY0Z[
 
	 
	 	V 	V r%   c           
      6   ||}|j                   |j                   k7  rt        d      t        t        | ||d      |||j                  j
                  |j                  dz
     |j                  j
                  |j                  dz
     |j                   ||      S )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rd  r   )rQ   r   rW  )rQ   
ValueErrorr   r}  r{  rn   r|  )r   r  r  rb  rc  r   rW  s          r&   r   r     s    ~ }{{ell"Z
 	
  4UK		4++a/0E--12{{  r%   value
return_lsec                    |i n
t        |      }|j                  dd       |j                  dd       |j                  dd       |j                  dd       d|vsJ d|d<   |sot        j                         }||d<   | j                  j
                  dk(  xs4 |j                  j
                  dk(  xs |j                  j
                  dk(  }|rd|d<   |S )	NPRESCALE_QKFROWS_GUARANTEED_SAFEBLOCKS_ARE_CONTIGUOUSWRITE_DQTOUTPUT_LOGSUMEXPcpu)dict
setdefaultrA   is_grad_enabledrQ   type)r[  r\  r  r  kernel_optionsoutput_logsumexpany_inputs_on_cpu_devices          r&   _apply_kernel_optionsr  9  s     *1RtN7KNmU34e<5u=j$/ ^333)-N%& !002-=)*LL& *zz%'*||  E) 	!
 $ 27N-.r%   c                     | j                  d      |j                  d      k7  r0t        d| j                  d       d|j                  d       d      y )NrY   zJExpect query and key/value to have the same embedding dimension but got E=z and E=.)rO   r  r   r[  r\  r  s      r&   _validate_embed_dimr  Y  sU    zz"~"%B(~Q@
 	
 r%   c                     | j                   j                  dk7  r=| j                   j                  dk7  r#t        d| j                   j                   d      yy)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
    rF  r  zOFlexAttention is only supported on CUDA or CPU devices. Found input tensors on z device.N)rQ   r  r  r  s      r&   _validate_devicer  k  sZ     ||F"u||'8'8E'A&&+ll&7&7%8B
 	
 (B"r%   c                 &   | j                   |j                   k7  s|j                   |j                   k7  rt        d      | j                   r| j                  0|j                   r|j                  |j                   r|j                  t        d      y y )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  v  s    #--'3==EOO+KN
 	
 
U^^7MMcll6OO :N
 	
 !;Or%   rQ  scale
enable_gqar  c	                    t        | ||       t        | ||       t        | ||       t        | ||       | j	                         dk7  s&|j	                         dk7  s|j	                         dk7  rt        d      |sS| j                  d      |j                  d      k7  r0t        d| j                  d       d|j                  d       d      |r<| j                  d      }	|j                  d      }
|	|
z  dk7  rt        d	|	 d|
 d
      | j                  d      |j                  d      k7  r|0t        d| j                  d       d|j                  d       d
      |j                  j                  d      | j                  d      k7  rLt        d| j                  d       d|j                  d       d|j                  j                  d       d
      |t        }nV| j                  rJ| j                  | j                        |j                  | j                        k(  r| n|}t        || |d      }|t        | |      }|j                  d   t        k(  r|j                  d   t        k(  rn| j                  rz|j                   d   | j"                  j                  | j                  dz
        k7  r}t%        d|j                    d| j"                  j                  | j                  dz
               |j                   d   }|j                   d   }| j                  d      |kD  s|j                  d      |kD  r=t        d|j                    d| j                  d       d|j                  d       d      | j                  d      |k  r|j                  d      |k  s(| j                  d      |k  rQ|j                  d      |k  r=t        d|j                    d| j                  d       d|j                  d       d      | j                  d      |k(  sJ |j                  d      |k(  sJ |'dt'        j(                  | j                  d            z  }| j*                  |j                  j*                  k7  r0t%        d| j*                   d|j                  j*                   d
      t-        | ||||      }t.        j0                  j3                         r| ||fD ]B  }t.        j4                  j7                  |d       t.        j4                  j7                  |d       D t9        | ||||j;                         ||      \  }}|r||t'        j<                  d      z  fS |S t.        j4                  j?                         st%        d       dd!l m!} d" }tE               5  t.        j4                  jF                  jI                         5  tK               5  tM               5 }|r	 ||      }nd#} t/        jN                  ||d$      | ||||j;                         ||      \  }}|r>||t'        j<                  d      z  fcddd       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       cddd       S # 1 sw Y   nxY w	 ddd       n# 1 sw Y   nxY wddd       n# 1 sw Y   nxY wddd       y# 1 sw Y   yxY w)%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

    r3   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=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  rX   zblock_mask of shape zJ is not compatible with nested tensor input with total sequence length of rY   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 r   z&flex_attention requires dynamo support)+make_eager_backend_with_torch_function_modec                      t        | i |S rL   )flex_attention_hop)argskwargss     r&   _flex_attention_hop_wrapperz3flex_attention.<locals>._flex_attention_hop_wrapper@  s    !42622r%   eager)backend	fullgraph)(r   r  r  r  rx   NotImplementedErrorrO   r  rd   rM   r  r|  r}  r`  r   r_  rn   r{  r   mathsqrtrQ   r  rA   compileris_dynamo_compiling_dynamomark_staticr  r   logis_dynamo_supported torch._dynamo.backends.debuggingr  r   utilsdisable_cache_limitr   r   rV  )r[  r\  r  rQ  r@  r  r  r  r  HqHkvkvblock_mask_q_lenblock_mask_kv_lenr   rt   lser  r  metadata_moder  s                        r&   r
   r
     s   @ U+sE*UC'U+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  	
 -YrPTU	-eS9
 	a $<<!!!$(@@ 		B5==#5#5e6G6G!6K#LL&z'7'7&8 91161C1CEDUDUXYDY1Z0[] 
 &++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
 	

 +N ~~))+e$ 	-AMM%%a,MM%%a,	- &3y**=*=*?
S dhhqk)))J==,,.CDD3 
	 #]]  446 	#>@ #>@ #M$"M)# #* u}}3WPT  !"++-&
 HC ""C$((1+$55'# ## #	# 	## #0  #+# ## #	# 	## ## # ## # #	# 	# 	## # #sy   &)[Z9Z$%AZ		Z$	Z9	[(Z	)	Z$2	Z9;	[ZZ$	Z9$Z-)Z90	[9[	>[[)r$   r   F)rF  )NNNFFN)Er    r   r,   r   r  r   rS  enumr   typingr   r   r   r   rA   r   ,torch._dynamo._trace_wrapped_higher_order_opr	   &torch._higher_order_ops.flex_attentionr
   r  torch._higher_order_ops.utilsr   "torch.fx.experimental.proxy_tensorr   r   torch.nn.attention._utilsr   r   torch.utils._pytreer   __all___score_mod_signaturer  r   r9   r   r`   listrS   rE   rM   r   r  r_  ru   r   r   r   r   r
  r  r$  r   r   rA  rE  r  r   r   r`  r}  r   r  r  r  r  r   r  r$   r%   r&   <module>r     s   P        1 1   P W > P -	   H& PQ ?GH 	 	)h )#4 )2 )+01++(3-$%+ (3-$%+ Chsm,,-	+
 +\  	
  JJ
J J 	J
 J ! "  f <U66>%: 6& 6v 6



 
 	
}- }-@5 ,,!&	+$
+$ 	+$
 68F##$+$\, 1D - 2E   -+ 	$ 33fhv../x  sCx 	
  D ,!&(;;<,!},! },! 	,!
 ,! ,! ,!j .HM!M}M }M 	M
 M M c5c?*+M M`F  I L-/BBCL
,,L <<L 	L
 !445Lh %).HP!P}P }P ,,	P
 ELL!P c5c?*+P Pf'-;?@
v 
F 
6 
$
F 
 
 

 
V 
F 
. 15&*!/3R#R#	R# R# ,-	R#
 #R# E?R# R# R# T#s(^,R# 65(()R#r%   