
    .`iJ              &          d dl mZmZ d dlZd dlZd dlZej        j        Z	ej
         G d d                      Zdeedf         fdZ	 	 	 	 	 	 	 	 	 	 d:dej        d	ej        d
eej                 deej                 dededddee         dededeej                 deej                 deej                 deej                 deej                 deej                 deej        ej        f         f"dZ	 	 	 d;dej        dej        dej        dededeej                 deej                 deej        ej        ej        f         fdZ	 	 	 	 	 d<dej        dej        d ej        d!ej        d"ej        d#ed$ed%eej                 d&eej                 dedee         d'edeej        ej        f         fd(Z	 	 	 	 	 	 d=d)ej        dej        dej        d ej        d%ej        d&ej        d!ej        d"ej        d#ed$ed*eej                 d+eej                 d,eej                 dedee         d'edeej        ej        ej        f         f"d-Z G d. d/ej        j                  Z	 	 	 	 	 d>dej        dej        d ej        d!ej        d"ej        d#ed$ed1edee         ded2ed'edeej        ej        f         fd3Z	 	 	 	 	 d>d4ej        d5ej        d6ed7ed1edee         ded2ed'edeej        ej        f         fd8Z	 	 	 	 	 d>dej        dej        d!ej        d"ej        d#ed$ed7ed1edee         ded2ed'edeej        ej        f         fd9ZdS )?    )OptionalTupleNc                       e Zd ZU dZej         G d d                      ZdZee	d<   dZ
ee         e	d<   dZeej                 e	d<   dZeej                 e	d	<   dS )
FlashMLASchedMetazE
    A class that stores the tile scheduler metadata of FlashMLA
    c                       e Zd ZU eed<   eed<   eed<   eed<   eed<   eed<   eed<   ee         ed<   ee         ed	<   ee         ed
<   dS )FlashMLASchedMeta.Configbs_qh_qpage_block_sizeh_kcausalis_fp8_kvcachetopkextra_page_block_size
extra_topkN)__name__
__module____qualname__int__annotations__boolr        /home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/vllm/third_party/flashmla/flash_mla_interface.pyConfigr      s         sm'},,,SM!!!!!r   r   Fhave_initializedNconfigtile_scheduler_metadata
num_splits)r   r   r   __doc__dataclasses	dataclassr   r   r   r   r   r   r   torchTensorr    r   r   r   r   r   	   s           " " " " " " " " #d"""#FHV###6:Xel3:::)-J&-----r   r   returnc                  "    t                      dfS )a  
    Returns an empty instance of FlashMLASchedMeta. The actual scheduling metadata will be generated during the first invocation of flash_mla_with_kvcache.

    Arguments:
        This function does not need any arguments, but we keep *args and **kwargs to be compatible with the old interface.

    Return:
        A tuple. Due to historical reasons, we return a tuple of (FlashMLASchedMeta, None) now. Only the first element is useful.
    N)r   )argskwargss     r   get_mla_metadatar*   &   s     $$r   Fqk_cacheblock_tablecache_seqlens
head_dim_vr   r    softmax_scaler   r   indices	attn_sinkextra_k_cacheextra_indices_in_kvcachetopk_lengthextra_topk_lengthc                    |}|
}t          |t                    s
J d            |
J d            ||j        d         nd}||j        d         nd}||j        d         nd}|| j        d         dz  }|j        sv||r
J d            d|_        t                              | j        d	         | j        d         | j        d
         |j        d         |j        d
         ||	|||
  
        |_        ndd}|j        J |j        j        | j        d	         k    sJ d|z               |j        j        | j        d         k    sJ d|z               |j        j        | j        d
         k    sJ d|z               |j        j	        |j        d         k    sJ d|z               |j        j
        |j        d
         k    sJ d|z               |j        j        |k    sJ d|z               |j        j        |	k    sJ d|z               |j        j        |k    sJ d|z               |j        j        |k    sJ d|z               |j        j        |k    sJ d|z               |M|r
J d            |	s
J d            t                               | |||||j        |j        |||||          \  }}}}nU|
|||||
J d            ||
J d            t                               | |||||||j        |j        	  	        \  }}}}||_        ||_        ||fS )a  
    Arguments:
        q: (batch_size, seq_len_q, num_heads_q, head_dim).
        k_cache: (num_blocks, page_block_size, num_heads_k, head_dim).
                Different modes (including fp8/bf16, and sparsity) has different KV cache layouts. See comments below for details.
                The KV cache must be contiguously valid for sparse attention on sm100. Here "contiguously valid" means that every byte, from the very beginning of the KV cache, till the last byte in the KV cache, is valid memory address to visit (i.e. won't IMA). In other words, the KV cache could be a slice of a larger array, but cannot be a list of disjoint memory blocks.
        block_table: (batch_size, max_num_blocks_per_seq), torch.int32. Can be None when sparse attention is used.
        cache_seqlens: (batch_size), torch.int32. Can be None when sparse attention is used.
        head_dim_v: Head_dim of v. Must be 512
        sched_meta: FlashMLASchedMeta, return by get_mla_metadata. You may reuse the same sched_meta across different invocations, but only when the tensor shapes and the values of cache_seqlens, topk_length, and extra_topk_length remain the same.
        num_splits_placeholder: must be "None" (to be compatible with the old interface).
        softmax_scale: float. The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim_k).
        causal: bool. Whether to apply causal attention mask. Only valid for dense attention
        is_fp8_kvcache: bool.
        indices: (batch_size, seq_len_q, topk). KV indices when sparse attention is enabled.
                    Pay attention that indices_in_kvcache[i][j][k] = (the index of the page block where token t resides) * block_size + (the offset of token t among the page block),
                    where t is the k-th token of the j-th q-sequence in the i-th batch.
        attn_sink: Optional[torch.Tensor], (num_heads_q, ), torch.float32. If presented, the final output will be scaled by exp(lse) / (exp(lse) + exp(attn_sink)). Have no affect on the returned softmax_lse. +inf will cause the result to become 0.
        extra_k_cache and extra_indices_in_kvcache: If provided, will attend to these extra tokens in addition to those in k_cache and indices_in_kvcache. Their format requirements are the same as k_cache and indices_in_kvcache respectively.
        topk_length/extra_topk_length: (batch_size, ), torch.int32. If provided, only the leftmost topk_length indices will be processed. Useful when the actual topk for different queries are different so that we can save some computation, compared to masking.
    
    For DeepSeek V3, DeepSeek V3.1, and DeepSeek V3.2:
        head_dim should be 576 while head_dim_v should be 512.
        In FP8+sparse mode, each token's KV cache is 656 Bytes, structured as:
            - The shape of the tensor `k_cache` is (num_blocks, page_block_size, num_heads_k, head_dim), and num_heads_k must be 1.
            - First 512 bytes: The "quantized NoPE" part, containing 512 float8_e4m3 values.
            - Next 16 bytes: Scale factors, containing 4 float32 values. The first float32 is the scale for the first 128 float8_e4m3 values, the second for the next 128, and so on.
            - Last 128 bytes: The "RoPE" part, containing 64 bfloat16 values. This part is not quantized for accuracy.

    Return:
        out: (batch_size, seq_len_q, num_heads_q, head_dim_v).
        softmax_lse: (batch_size, num_heads_q, seq_len_q), torch.float32.
    z9tile_scheduler_metadata must be of type FlashMLASchedMetaNznum_splits must be None         z[causal must be False when indices_in_kvcache is not None (i.e. sparse attention is enabled)Tr      z Your input arguments are inconsistent with sched_meta. Please make sure the input arguments are consistent across different invocations of flash_mla_with_kvcache on the same sched_meta.z0sched_meta.config.b must be equal to batch_size.z1sched_meta.config.s_q must be equal to seq_len_q.z3sched_meta.config.h_q must be equal to num_heads_q.zCsched_meta.config.page_block_size must be equal to page_block_size.z3sched_meta.config.h_k must be equal to num_heads_k.z1sched_meta.config.causal must be equal to causal.zAsched_meta.config.is_fp8_kvcache must be equal to is_fp8_kvcache.zKsched_meta.config.topk must be equal to the last dim of indices_in_kvcache.z^sched_meta.config.extra_page_block_size must be equal to the page_block_size of extra_k_cache.zWsched_meta.config.extra_topk must be equal to the last dim of extra_indices_in_kvcache.z5causal must be False when sparse attention is enabledz<is_fp8_kvcache must be True when sparse attention is enabledzindices_in_kvcache, attn_sink, extra_k_cache, extra_indices_in_kvcache, topk_length and extra_topk_length must be None when dense attention is used.zLblock_table and cache_seqlens must be provided when dense attention is used.)
isinstancer   shaper   r   r   r	   r
   r   r   r   r   r   r   r   r   flash_mla_cudasparse_decode_fwdr   r    dense_decode_fwd)r+   r,   r-   r.   r/   r   r    r0   r   r   r1   r2   r3   r4   r5   r6   
sched_metaindices_in_kvcacher   extra_k_page_block_sizer   
helper_msgoutlsenew_tile_scheduler_metadatanew_num_splitss                             r   flash_mla_with_kvcacherI   6   s[   f )J j"344qq6qqq48+=+I#B''tD8E8Qm1!44W[7O7[)/33aeJ-& "b)|||||: '+
#-44GAJGAJGAJM!M!#
 

  R
 ,,, "agaj0002dgq2q000 $
2224gjt4t222 $
2224ilv4v222 0GM!4DDDD  GL  OY  GYDDD $a(8888:or|:|888 '61113fis3s111 />AAA  DG  JT  DTAAA %---/|  @J  0J--- 6:QQQQ  Tt  wA  TAQQQ +z999  <U  Xb  <b999RRRRRz]]]]]~@N@`@`w*K.
0E35F	A
 A
=S-~~ ")i.?MDY^v^~  DO  DW  \m  \u  \u  wM  \u  \u  u&=+D+D  GU+D+DD@N@_@_w
;6.
0E	A
 A
=S-~ *EJ&*J:r      kvsm_scaled_vc           	      F    t                               | ||||||          }|S )a  
    Sparse attention prefill kernel

    Args:
        q: [s_q, h_q, d_qk], bfloat16
        kv: [s_kv, h_kv, d_qk], bfloat16
        indices: [s_q, h_kv, topk], int32. Invalid indices should be set to -1 or numbers >= s_kv
        sm_scale: float
        d_v: The dimension of value vectors. Can only be 512
        attn_sink: optional, [h_q], float32.
            If attn_sink is provided, when computing output, output will be additionally multiplied by exp(lse) / (exp(lse) + exp(attn_sink)).
            +-inf in attn_sink will be handled normally (i.e., -inf has no effect, +inf will make corresponding output all zeros).
            This argument has no effect on lse and max_logits.
        topk_length: optional, [s_q], int32. If provided, the i-th q token will only attend to k tokens specified by indices[i, :, :topk_length[i]], ignoring later k/v tokens (even if provided in indices).
            In extremely rare cases (topk_length provided, there is a valid topk index between topk_length[i] ~ s_kv, and that topk index points to a k token containing NaN), operator output will contain NaN, so please avoid this situation.

    Returns:
        (output, max_logits, lse)
        Please refer to tests/ref.py for the precise definitions of these parameters.
        - output: [s_q, h_q, d_v], bfloat16
        - max_logits:  [s_q, h_q], float
        - lse: [s_q, h_q], float, log-sum-exp of attention scores
    )r>   sparse_prefill_fwd)r+   rK   r1   rL   rM   r2   r5   resultss           r   flash_mla_sparse_fwdrQ      s0    @ //	2w#y+ G Nr   Tkvcu_seqlens_qocu_seqlens_kvmax_seqlen_qomax_seqlen_kvrE   rF   	is_varlenc                    | j         \  }}}|j         \  }}}|	rdnd}|
|dz  }
|#t          j        |||| j        | j                  }|,t          j        ||| j        t          j                  j        }t          j        dt          j        | j                  }t          	                    || ||||||||
|||           ||fS )Nr9   r   r:   devicedtypei   r\   r[   )
r=   r$   emptyr[   r\   float32Tuint8r>   dense_prefill_fwd)r+   rR   rS   rT   rU   rV   rW   rE   rF   r   r0   rX   qo_total_lennum_qo_headshead_dim_qkkv_total_lennum_kv_headshead_dim_vomask_mode_codeworkspace_buffers                       r   _flash_attn_varlen_forwardrk      s     /0g+L,./g+L, 'QQaN#-
{k,k!(Z[Zabbb
{k,QXU][[[]{#35;qxXXX$$			    8Or   dodqdkdvc                    |j         \  }}}|j         \  }}}||k    rt          d| d| d          |rdnd}||dz  }|
#t          j        ||||j        |j                  }
|#t          j        ||||j        |j                  }|#t          j        ||||j        |j                  }|dz   d	z  d	z  }|j         d         dz
  }d}|d
|z  |z  |z  |z  z  }|d
|z  |z  |z  dz  z  }||k    r|d|z  |z  ||z   z  z  }t          j        |t          j        |j                  }t                              || ||||||||
||||||	|           |
||fS )Nz1SM100 bwd doesn't support GQA now. num_qo_heads: z, num_kv_heads: .r9   r   r:   rZ            r;   r]   )	r=   
ValueErrorr$   r^   r[   r\   ra   r>   dense_prefill_bwd)rl   r+   rR   rS   rE   rF   rT   rU   rV   rW   rm   rn   ro   r   r0   rX   rc   rd   re   rf   rg   rh   ri   max_seqlen_qo_alignedbsworkspace_bytesrj   s                              r   _flash_attn_varlen_backwardrz     s   $ /0g+L,./g+L, |##z\zzkwzzz{{{ 'QQaN#-	z[|[YZY`aaa	z[|[YZY`aaa	z[|[YZY`aaa*Q.14q8		Q	!	#BOq2v 55D{RROq0025DqHHO|##1|+l:kK>WXX{?%+ahWWW$$
			


#  ( r2:r   c                       e Zd Z	 	 	 ddej        dej        dej        dej        dej        d	ed
ededee         dede	ej        ej        f         fdZ
dej        dej        fdZdS )FlashAttnVarlenFuncFNTr+   rR   rS   rT   rU   rV   rW   r   r0   rX   r&   c                     t          |||||||||	|

  
        \  }}|                     |||||||           || _        || _        || _        |	| _        |
| _        ||fS N)r   r0   rX   )rk   save_for_backwardrV   rW   r   r0   rX   )ctxr+   rR   rS   rT   rU   rV   rW   r   r0   rX   rE   rF   s                r   forwardzFlashAttnVarlenFunc.forwardJ  s     .q!=-	
 
 
S 	aAsCNNN))
)!Cxr   rl   dlsec                     ~| j         \  }}}}}}}	t          ||||||||	| j        | j        | j        | j        | j                  \  }
}}|
||d d d d d d d f
S r~   )saved_tensorsrz   rV   rW   r   r0   rX   )r   rl   r   r+   rR   rS   rE   rF   rT   rU   rm   rn   ro   s                r   backwardzFlashAttnVarlenFunc.backwarde  s    
 :=:K71ac=-01ac=#*;S=N:S->m	
 
 

B 2r4tT4tCCr   )FNT)r   r   r   r$   r%   r   r   r   floatr   r   r   r   r   r   r|   r|   I  s         )- < < <	
 | |       
u|U\)	*   6DLD lD D D D D Dr   r|           	dropout_pdeterministicc                 `    |dk    sJ |
rJ t                               | |||||||	||
  
        S Nr   r|   apply)r+   rR   rS   rT   rU   rV   rW   r   r0   r   r   rX   s               r   flash_attn_varlen_funcr   u  sP     $$	1a}m]y  r   qkv
cu_seqlens
max_seqlenre   c	                     |dk    sJ |rJ t                               | d d d d d |f         | d d d d ||dz  f         | d d d d |dz  d f         |||||||
  
        S )Nr   r;   r   )	r   r   r   re   r   r0   r   r   rX   s	            r    flash_attn_varlen_qkvpacked_funcr     s     $$AAAqqq,;,QQQ;{Q+F%F!GQQQPQPQPQS^abSbScScMcIdJ
Jy  r   c                     |dk    sJ |
rJ t                               | |d d d d d |f         |d d d d |d f         |||||	||
  
        S r   r   )r+   rK   rT   rU   rV   rW   re   r   r0   r   r   rX   s               r   flash_attn_varlen_kvpacked_funcr     s     $$	2aaaL[L !2aaaKLL&8#9}m]y  r   )
NNFFNNNNNN)rJ   NN)NNFNT)NNNFNT)r   NFFT)typingr   r   r"   r$   vllm._flashmla_Cvllmops_flashmla_Cr>   r#   r   r*   r%   r   r   r   rI   rQ   rk   rz   autogradFunctionr|   r   r   r   r   r   r   <module>r      s   " " " " " " " "         &. . . . . . . .8% d"#% % % %. %) &*(,,07;*.04!x x|x\x %,'x EL)	x
 x /x x E?x x x el#x %x EL)x 'u|4x %,'x   -!x" 5<%&#x x x x@ (,*.# #|## \# 	#
 
# %# %,'# 5<u|34# # # #\ #'"&%), ,|,|, |, <	,
 <, , , 
%,	, 
%,	, , E?, , 5<%&, , , ,t "&!%!%%)!@ @@|@ |@ |	@
 
@ 
@ <@ <@ @ @ 	@ 	@ 	@ @ E?@  !@" 5<u|34#@ @ @ @F)D )D )D )D )D%.1 )D )D )Dh %) || | <	
 <    E?    5<%&   8 %) 	  	
  E?    5<%&   8 %) | < <	
     E?    5<%&     r   