§
    oF§jñó  ã                   óÌ  — d Z ddlZddlZej        dk    r: eej        d¦  «        r)ej        j                             ¦   «         r ed¦  «        ‚ddl	m
c mZ ddlmZ ddlmZ ddlmc m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 	 dd	l m!Z!  ee!d
¦  «        sej"        j#        Z!n#  ej"        j#        Z!Y nxY w	 ddl m$Z$  ee$d¦  «        sej"        j%        Z$dZ&n	#  dZ&Y nxY w	 ddl m'Z'  ee'd¦  «        sej"        j(        Z'dZ)n	#  dZ)Y nxY w	 ddl m*Z*  ee*d¦  «        sej"        j+        Z*dZ,n	#  dZ,Y nxY wddl-mZ. ddl-m/Z0 ddl-m1Z1 ddl-m2a2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:Z:ddl;Z;d„ Z<ddl=m>Z>  e>d¦  «        Z?e? @                    d¦  «        ZAddlBZBddlCZCddlDZDd„ ZEd„ ZFdeGdeGfd„ZH eI eF¦   «         ¦  «        ZJejK         L                    ¦   «         dk    ZMd ZNd ZOd!ZPdaQi ZRd"ejS        deGfd#„ZTd"ejS        deUfd$„ZVd"ejS        deGfd%„ZWd"ejS        fd&„ZXd"ejS        deYfd'„ZZd(dej[        dfd)„Z\dQd+ej]        dz  d"ejS        eUz  dz  d,eUdeUdz  fd-„Z^dQd"ejS        eUz  dz  d+ej]        dz  d,eUdeYfd.„Z_	 	 	 	 	 dRd,eUd/eYd0e7e`         d1eYd2eYd3e4fd4„Zaejb        jc        	 	 	 	 	 	 	 dSd,eUd6eUd/eYd0e7e`         d7eYd1eYd+e7ej]                 d3e4dej]        fd8„¦   «         Zdejb        jc        	 	 	 dTd9ej]        d:ej]        d;ej]        d<ej]        d=ej]        d>eGd?eGd/eYd0e7e`         d7eYd3e4dej]        fd@„¦   «         Zeejb        jc        	 	 	 	 	 	 	 	 dUd,eUd/eYdCeUd0e7e`         dDeUd7eYdEeYd1eYd3e4dej]        fdF„¦   «         Zfejb        jc        	 	 	 	 	 	 	 	 	 dVd,eUd/eYdCeUd0e7e`         dDeUd7eYdEeYd1eYd2eYd3e4dej]        fdG„¦   «         Zgejb        jc        	 	 	 	 	 	 	 	 	 	 dWd,eUd/eYdCeUd0e7e`         dDeUd7eYdEeYd1eYd2eYd3e4dej]        fdJ„¦   «         Zhejb        jc        	 	 	 	 	 	 	 	 dXd,eUd/eYdCeUd0e7e`         dDeUd7eYd1eYd2eYd3e4dej]        fdK„¦   «         Zitd          Zj	 	 	 dYdMe9ej]        ekf         d,eUdNe`dEeYfdO„ZldP„ Zm em¦   «          dS )Za8  
Copyright (c) 2024 by SageAttention team.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
é    NÚdarwinÚmpsz?SageAttention is CUDA-only and is disabled on Apple Silicon MPS)Úper_block_int8)Úforward)Úper_thread_int8)Ú_fusedÚtranspose_pad_permute_cuda)Ú_qattn_sm80Úqk_int8_sv_f16_accum_f32_attnTF)Ú_qattn_sm89Ú2qk_int8_sv_f8_accum_f32_fuse_v_scale_attn_inst_buf)Ú_qattn_sm90)Úper_warp_int8)Úsub_mean)Úper_channel_fp8)ÚAnyÚListÚLiteralÚOptionalÚTupleÚUnionc                  ó¼   — t           j                             ¦   «         } t          | ¦  «        D ]-}t           j                             |¦  «        \  }}|dk     r dS Œ.dS )Né   FT)ÚtorchÚcudaÚdevice_countÚrangeÚget_device_capability)r   ÚiÚmajorÚminors       ú*C:\Users\johnn\Wan2GP\shared\sage2_core.pyÚis_sage2_supportedr#   K   s_   € Ý”:×*Ò*Ñ,Ô,€LÝ�<Ñ Ô ð ð ˆÝ”z×7Ò7¸Ñ:Ô:‰ˆˆuØ�1Š9ˆ9Ø�5�5ð àˆ4ó    )ÚversionÚsageattentionz2.2c                  óf  — 	 t          j        ddg¦  «                             ¦   «         } t          j        d| ¦  «        }|rHt          |                     d¦  «        ¦  «        t          |                     d¦  «        ¦  «        }}||fS n'# t          $ r}t          d|¦  «         Y d }~nd }~ww xY wdS )NÚnvccz	--versionzrelease (\d+)\.(\d+)é   é   zFailed to get CUDA version:)NN)	Ú
subprocessÚcheck_outputÚdecodeÚreÚsearchÚintÚgroupÚ	ExceptionÚprint)ÚoutputÚmatchr    r!   Úes        r"   Úget_cuda_versionr7   Z   sÄ   € ð0ÝÔ(¨&°+Ð)>Ñ?Ô?×FÒFÑHÔHˆÝ”	Ð1°6Ñ:Ô:ˆØð 	 Ý˜uŸ{š{¨1™~œ~Ñ.Ô.µ°E·K²KÀ±N´NÑ0CÔ0C�5ˆEØ˜%�<Ðð	 øõ ð 0ð 0ð 0ÝÐ+¨QÑ/Ô/Ð/Ð/Ð/Ð/Ð/Ð/øøøøð0øøøàˆ:s   ‚BB
 Â

B.ÂB)Â)B.c                  óÞ   — g } t          t          j                             ¦   «         ¦  «        D ]>}t          j                             |¦  «        \  }}|                      d|› |› �¦  «         Œ?| S )NÚsm)r   r   r   r   r   Úappend)Ú
cuda_archsr   r    r!   s       r"   Úget_cuda_arch_versionsr<   e   sp   € Ø€JÝ•5”:×*Ò*Ñ,Ô,Ñ-Ô-ð /ð /ˆÝ”z×7Ò7¸Ñ:Ô:‰ˆˆuØ×ÒÐ-˜uÐ- eÐ-Ð-Ñ.Ô.Ð.Ð.ØÐr$   ÚindexÚreturnc           	      ó€   — t           j                             | ¦  «        }t          |dt          |dd¦  «        ¦  «        S )NÚshared_memory_per_block_optinÚshared_memory_per_blockr   )r   r   Úget_device_propertiesÚgetattr)r=   Úpropss     r"   Ú_device_shared_memory_limitrE   m   s8   € ÝŒJ×,Ò,¨UÑ3Ô3€EÝ�5Ð9½7À5ÐJcÐefÑ;gÔ;gÑhÔhÐhr$   r)   é@   i h Údevicec                 óZ   — | j         €t          j                             ¦   «         n| j         S ©N)r=   r   r   Úcurrent_device©rG   s    r"   Ú_get_device_indexrL   |   s$   € Ø*0¬,Ð*>�5Œ:×$Ò$Ñ&Ô&Ð&ÀFÄLÐPr$   c                 ó’   — t          | ¦  «        }|t          t          ¦  «        k     rt          |         S t          ¦   «         |         S rI   )rL   ÚlenÚ_CUDA_ARCHSr<   ©rG   Úidxs     r"   Ú_get_cuda_archrR   €   s>   € Ý
˜FÑ
#Ô
#€CØ
�S•ÑÔÒÐÝ˜3ÔÐÝ!Ñ#Ô# CÔ(Ð(r$   c                 óz   — t          | ¦  «        }|t          vrt          |¦  «        t          |<   t          |         S rI   )rL   Ú_SHARED_MEMORY_LIMIT_BY_DEVICErE   rP   s     r"   Ú_get_shared_memory_limitrU   ‡   s9   € Ý
˜FÑ
#Ô
#€CØ
Õ0Ð0Ð0Ý.IÈ#Ñ.NÔ.NÕ& sÑ+Ý)¨#Ô.Ð.r$   c                 ó¼   — t           rd S t          | ¦  «        }|t          j                             ¦   «         k    r!t          j                             |¦  «         d S d S rI   )Ú_SINGLE_CUDA_DEVICErL   r   r   rJ   Ú
set_devicerP   s     r"   Ú_maybe_set_devicerY   Ž   sY   € Ýð ØˆÝ
˜FÑ
#Ô
#€CØ
�eŒj×'Ò'Ñ)Ô)Ò)Ð)ÝŒ
×Ò˜cÑ"Ô"Ð"Ð"Ð"ð *Ð)r$   c                 ó2   — t          | ¦  «        t          k     S rI   )rU   Ú%_UPSTREAM_MASKED_HEAD128_SHARED_BYTESrK   s    r"   Ú_use_low_shared_masked_tritonr\   –   s   € Ý# FÑ+Ô+Õ.SÒSÐSr$   ÚHNDc	                 ód  — t           s7t          dt          › dt          › dt	          | j        ¦  «        › d�¦  «         da t          j        | j        || j        ¬¦  «        }	|dk    �r| j        \  }
}}}|j        \  }}}}|  	                    d¦  «        |  	                    d	¦  «        |  	                    d
¦  «        }}}| 	                    d¦  «        | 	                    d	¦  «        | 	                    d
¦  «        }}}| 	                    d¦  «        | 	                    d	¦  «        | 	                    d
¦  «        }}}|	 	                    d¦  «        |	 	                    d	¦  «        |	 	                    d
¦  «        }}}�n/|dk    �r| j        \  }
}}}|j        \  }}}}|  	                    d¦  «        |  	                    d
¦  «        |  	                    d	¦  «        }}}| 	                    d¦  «        | 	                    d
¦  «        | 	                    d	¦  «        }}}| 	                    d¦  «        | 	                    d
¦  «        | 	                    d	¦  «        }}}|	 	                    d¦  «        |	 	                    d
¦  «        |	 	                    d	¦  «        }}}nt          d|› d�¦  «        ‚| 	                    d¦  «        | 	                    d	¦  «        | 	                    d
¦  «        | 	                    d¦  «        f\  }}}} |r)t          j        |
||gt          j        | j        ¬¦  «        n!t          j        dgt          j        d¬¦  «        }!|t          z   d	z
  t          z  ||
f}"t          j        |"         | |||||	||!|||||||||||||||| |||||z  ft          t          |d	|dddœŽ |	|!fS )NzE[SageAttention] Using low-shared-memory masked Triton patch (BLOCK_M=z
, BLOCK_N=z, GPU limit=z bytes).T©ÚdtyperG   r]   r   r)   r*   ÚNHDztensor_layout z not supportedé   Úcpué   )ÚBLOCK_MÚBLOCK_NÚHEAD_DIMÚSTAGEÚ
RETURN_LSEÚ	num_warpsÚ
num_stages)Ú'_LOW_SHARED_MASKED_TRITON_PATCH_PRINTEDr3   Ú_LOW_SHARED_MASKED_BLOCK_MÚ_LOW_SHARED_MASKED_BLOCK_NrU   rG   r   ÚemptyÚshapeÚstrideÚ
ValueErrorÚfloat32Úattn_qk_int8_per_blockÚ	_attn_fwd)#ÚqÚkÚvÚq_scaleÚk_scaleÚtensor_layoutÚ	attn_maskÚoutput_dtypeÚ
return_lseÚoÚbÚh_qoÚqo_lenÚhead_dimÚ_Úh_kvÚkv_lenÚstride_bz_qÚ
stride_h_qÚstride_seq_qÚstride_bz_kÚ
stride_h_kÚstride_seq_kÚstride_bz_vÚ
stride_h_vÚstride_seq_vÚstride_bz_oÚ
stride_h_oÚstride_seq_oÚstride_bz_maskÚstride_h_maskÚstride_m_maskÚstride_n_maskÚlseÚgrids#                                      r"   Ú_attn_false_low_shared_maskedr™   š   sè  € å2ð 7Ýð  QÕVpð  Qð  Qõ  }Wð  Qð  Qõ  e}ð  ~ô  ~Fñ  eGô  eGð  Qð  Qð  Qñ  	Rô  	Rð  	RØ26Ð/åŒ�A”G <¸¼ÐAÑAÔA€Aà˜ÒÑØ$%¤GÑ!ˆˆ4�˜ØœWÑˆˆ4�˜Ø01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆØ01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆØ01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆØ01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �Zˆ‰Ø	˜%Ò	Ñ	Ø$%¤GÑ!ˆˆ6�4˜ØœWÑˆˆ6�4˜Ø01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆØ01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆØ01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆØ01·²¸±´¸Q¿XºXÀa¹[¼[È!Ï(Ê(ÐSTÉ+Ì+ �ZˆˆåÐG¨-ÐGÐGÐGÑHÔHÐHàBK×BRÒBRÐSTÑBUÔBUÐW`×WgÒWgÐhiÑWjÔWjÐlu×l|Òl|Ð}~ÑlÔlð  BK÷  BRò  BRð  STñ  BUô  BUð  CUÑ?€N�M =°-ØR\ð  V�%Œ+�q˜$ Ð'­u¬}ÀQÄXÐ
NÑ
NÔ
NÐ
NÕbgÔbmÐopÐnqÕy~ô  zGð  PUð  cVñ  cVô  cV€CØÕ0Ñ0°1Ñ4Õ9SÑSÐUYÐ[\Ð]€DÝÔ$ TÔ*Ø	ˆ1ˆa�˜' 1 i°Ø�Z Ø�Z Ø�Z Ø�Z Ø˜ }°mØ�Øˆd�d‰lðõ +Õ4NÐYaØ˜JØØðð ð ð ð ˆcˆ6€Mr$   ra   r|   r{   c                 óz  — | �| d         j         }t          j                             ¦   «         sdS t          j         |€dn|¦  «        }	 t          j                             t          |¦  «        ¦  «        \  }}|dk     rdt          |¦  «        › d�S t          t          d¦  «        sdS d	t          j
        t          ¦  «        j        vrd
S n# t          t          f$ r Y dS w xY w| €d S | d         }|j        t          j        t          j        fvrd|j        › d�S |j        d         dk    rd|j        d         › d�S d S )Nr   zCUDA is unavailabler   r   zCUDA architecture z! has no masked SageAttention pathru   z*SageAttention Triton kernel is unavailabler|   z1installed SageAttention does not expose attn_maskz6unable to inspect installed SageAttention mask supportzdtype z is unsupportedéÿÿÿÿé€   z	head_dim )rG   r   r   Úis_availabler   rL   rR   Úhasattrrt   ÚinspectÚ	signatureÚ
attn_falseÚ
parametersÚ	TypeErrorrr   r`   Úfloat16Úbfloat16rp   )Úqkv_listr|   rG   r{   r    r„   rv   s          r"   Ú&sageattn_attention_mask_support_reasonr§   Ç   sg  € ØÐØ˜!”Ô#ˆÝŒ:×"Ò"Ñ$Ô$ð %Ø$Ð$ÝŒ\ F N˜&˜&¸Ñ?Ô?€Fð	HÝ”:×3Ò3Õ4EÀfÑ4MÔ4MÑNÔN‰ˆˆqØ�1Š9ˆ9Øa­°vÑ(>Ô(>ÐaÐaÐaÐaÝÕ-¨{Ñ;Ô;ð 	@Ø?Ð?Ø�gÔ/µ
Ñ;Ô;ÔFÐFÐFØFÐFð Gøå•zÐ"ð Hð Hð HØGÐGÐGðHøøøàÐØˆtà�Œ€AØ„w•u”}¥e¤nÐ5Ð5Ð5Ø0˜œÐ0Ð0Ð0Ð0Ø„wˆr„{�SÒÐØ7˜1œ7 2œ;Ð7Ð7Ð7Ð7Øˆ4s   Á	AC ÂC Â( C ÃC ÃC c                 ó*   — t          ||| |¦  «        d u S rI   )r§   )rG   r¦   r|   r{   s       r"   Ú sageattn_supports_attention_maskr©   â   s   € Ý1°(¸IÀvÈ}Ñ]Ô]ÐaeÐeÐer$   Ú	is_causalÚsm_scaler~   Ú	recycle_qÚkwargsc                 óP  — |                      dd¦  «        }t          | d         j        ¦  «        }|�)t          | ||¬¦  «        }	|	�t	          d|› d|	› �¦  «        ‚|�t          | |||||¬¦  «        S |dk    rt          | ||||d	¬
¦  «        S |dk    rt          | ||||¬¦  «        S |dk    rt          | ||||t          rdnd|¬¦  «        S |dk    rt          | ||||d|¬¦  «        S |dk    r't          | ||d||t          rdnd	t           |¬¦	  «	        S t	          d|› �¦  «        ‚)a4  
    Automatically selects the appropriate implementation of the SageAttention kernel based on the GPU compute capability.

    Parameters
    ----------
    q : torch.Tensor
        The query tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    k : torch.Tensor
        The key tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    v : torch.Tensor
        The value tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    tensor_layout : str
        The tensor layout, either "HND" or "NHD".
        Default: "HND".

    is_causal : bool
        Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len.
        Default: False.

    sm_scale : Optional[float]
        The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.

    return_lse : bool
        Whether to return the log sum of the exponentiated attention weights. Used for cases like Ring Attention.
        Default: False.

    Returns
    -------
    torch.Tensor
        The output tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    torch.Tensor
        The logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax normalization factor).
        Shape: ``[batch_size, num_qo_heads, qo_len]``.
        Only returned if `return_lse` is True.

    Note
    ----
    - ``num_qo_heads`` must be divisible by ``num_kv_heads``.
    - The tensors `q`, `k`, and `v` must have the dtype ``torch.float16`` or ``torch.bfloat16``
    - All tensors must be on the same cuda device.
    r|   Nr   ©r{   z9Masked SageAttention is unsupported on CUDA architecture z: )r{   rª   r«   r~   r|   Úsm80Úfp32)r{   rª   r«   r~   Úpv_accum_dtypeÚsm86)r{   rª   r«   r~   Úsm89ú	fp32+fp16ú	fp32+fp32)r{   rª   r«   r~   r²   r¬   Úsm90Úsm120Úper_warp)r{   rª   Úqk_quant_granr«   r~   r²   Úsmooth_vr¬   zUnsupported CUDA architecture: )
ÚpoprR   rG   r§   rr   Úsageattn_qk_int8_pv_fp16_tritonÚsageattn_qk_int8_pv_fp16_cudaÚsageattn_qk_int8_pv_fp8_cudaÚsg2ppÚ!sageattn_qk_int8_pv_fp8_cuda_sm90)
r¦   r{   rª   r«   r~   r¬   r­   r|   ÚarchÚsupport_reasons
             r"   ÚsageattnrÄ   å   sI  € ð~ —
’
˜;¨Ñ-Ô-€IÝ˜( 1œ+Ô,Ñ-Ô-€DØÐÝ?ÀÈ)ÐcpÐqÑqÔqˆØÐ%ÝÐqÐY]ÐqÐqÐaoÐqÐqÑrÔrÐrØÐÝ.¨xÀ}Ð`iÐt|ð  JTð  `ið  jñ  jô  jð  	jØˆv‚~€~Ý,¨XÀ]Ð^gÐrzð  HRð  cið  jñ  jô  jð  	jØ	�ŠˆÝ.¨xÀ}Ð`iÐt|ð  JTð  Uñ  Uô  Uð  	UØ	�ŠˆÝ+¨HÀMÐ]fÐqyð  GQõ  qvð  bGð  bmð  bmð  |Gð  U^ð  _ñ  _ô  _ð  	_Ø	�ŠˆÝ0°ÈÐbkÐv~ð  LVð  grð  @Ið  Jñ  Jô  Jð  	JØ	�ŠˆÝ+¨HÀMÐ]fð  wAð  LTð  akõ  LQð  }]ð  }Hð  }Hð  W]õ  mrð  irð  @Ið  Jñ  Jô  Jð  	JåÐA¸4ÐAÐAÑBÔBÐBr$   ÚtritonÚquantization_backendÚsmooth_kc                 ó  — | \  }	}
}|                       ¦   «          |	j        }|	j        s
J d¦   «         ‚|t          j        t          j        fv s
J d¦   «         ‚|	j        |
j        cxk    r|j        k    sn J d¦   «         ‚|	j        |
j        cxk    r|j        k    sn J d¦   «         ‚|�6|r
J d¦   «         ‚|j        t          j        k    s|j        |k    s
J d¦   «         ‚t          |j        ¦  «         |	 	                    d¦  «        }|duot          |	j        ¦  «        }|d	k     rt          j        j                             |	d
d	|z
  f¦  «        }	t          j        j                             |
d
d	|z
  f¦  «        }
t          j        j                             |d
d	|z
  f¦  «        }n£|d	k    r…|dk     rt          j        j                             |	d
d|z
  f¦  «        }	t          j        j                             |
d
d|z
  f¦  «        }
t          j        j                             |d
d|z
  f¦  «        }n|dk    rt          d|› �¦  «        ‚|	                     d¦  «        dk    r2|
                     d¦  «        dk    r|                     d¦  «        dk    s
J d¦   «         ‚|dk    rdnd}|rû|
                     |d¬¦  «        }|rá|dk    r‚t          j        |	                     dd¦  «        |                     dd¦  «                             dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }n\t          j        |	|                     dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }nd}|t          j        k    s|t          j        k    r|                     t          j        ¦  «        }|€d|dz  z  }|dk    rB|r&t-          |	|
|t.          t0          ||¬¦  «        \  }}}}nLt-          |	|
|||¬¦  «        \  }}}}n2|dk    rt3          |	|
|||¬¦  «        \  }}}}nt          d|› �¦  «        ‚~	~
~|�Š|dk    r2|j        d
         |j        d         |j        d         |j        d         fn1|j        d
         |j        d         |j        d         |j        d         f}|j        |k    r|                     |¦  «        }|rt9          ||||||||¬¦  «        \  }}nV|rt;          |||||||||¬¦	  «	        \  }}n8|�t=          |||||||||¬¦	  «	        \  }}nt=          ||||||||¬¦  «        \  }}|dd|…f         }|r||r|dz  ||z  z   n|dz  fS |S )a5
  
    SageAttention with per-block INT8 quantization for Q and K, FP16 PV with FP16 accumulation, implemented using Triton.
    The FP16 accumulator is added to a FP32 buffer immediately after each iteration.

    Parameters
    ----------
    q : torch.Tensor
        The query tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    k : torch.Tensor
        The key tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    v : torch.Tensor
        The value tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    tensor_layout : str
        The tensor layout, either "HND" or "NHD".
        Default: "HND".

    quantization_backend : str
        The quantization backend, either "triton" or "cuda".
        "cuda" backend offers better performance due to kernel fusion.

    is_causal : bool
        Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len.
        Default: False.

    sm_scale : Optional[float]
        The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.

    smooth_k : bool
        Whether to smooth the key tensor by subtracting the mean along the sequence dimension.
        Default: True.

    return_lse : bool
        Whether to return the log sum of the exponentiated attention weights. Used for cases like Ring Attention.
        Default: False.

    Returns
    -------
    torch.Tensor
        The output tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    torch.Tensor
        The logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax normalization factor).
        Shape: ``[batch_size, num_qo_heads, qo_len]``.
        Only returned if `return_lse` is True.

    Note
    ----
    - ``num_qo_heads`` must be divisible by ``num_kv_heads``. 
    - The tensors `q`, `k`, and `v` must have the dtype ``torch.float16``, ``torch.bfloat16`` or ``torch.float32``.
    - All tensors must be on the same cuda device.
    - `smooth_k` will introduce slight overhead but will improve the accuracy under most circumstances.
    úInput tensors must be on cuda.úAInput tensors must be in dtype of torch.float16 or torch.bfloat16ú'All tensors must be on the same device.ú%All tensors must have the same dtype.Nz?SageAttention does not support attn_mask with causal attention.z(attn_mask must be bool or match q dtype.r›   rF   r   rœ   úUnsupported head_dim: r)   ú#Last dim of qkv must be contiguous.ra   r*   T©ÚdimÚkeepdimrb   ç      ð?ç      à?rÅ   )ÚkmÚBLKQÚBLKKr«   r{   )rÔ   r«   r{   r   z"Unsupported quantization backend: )r{   r}   r~   )r{   r}   r~   r|   .ç/lîdG÷?)Úclearr`   Úis_cudar   r¤   r¥   rG   ÚboolrY   Úsizer\   ÚnnÚ
functionalÚpadrr   rq   ÚmeanÚmatmulÚ	transposeÚsqueezeÚtors   Úper_block_int8_tritonrm   rn   Úper_block_int8_cudarp   ÚexpandÚ	attn_truer™   r¡   )r¦   r{   rÆ   rª   r«   rÇ   r~   r|   r­   rv   rw   rx   r`   Úhead_dim_ogÚmasked_low_sharedÚseq_dimrÔ   Úlse_correctionÚq_int8ry   Úk_int8rz   Útarget_shaper   r—   s                            r"   r½   r½   9  sŠ  € ð\ �G€A€qˆ!Ø‡N‚NÑÔÐØŒG€EØŒ9Ð6Ð6Ð6Ñ6Ô6ˆ9Ø•U”]¥E¤NÐ3Ð3Ð3Ð3Ð5xÑ3Ô3Ð3ØŒ8�q”xÐ+Ð+Ò+Ð+ 1¤8Ò+Ð+Ð+Ð+Ð+Ð-VÑ+Ô+Ð+ØŒ7�a”gÐ(Ð(Ò(Ð( ¤Ò(Ð(Ð(Ð(Ð(Ð*QÑ(Ô(Ð(ØÐØÐ_Ð_Ð_Ñ_Ô_ˆ}ØŒ¥%¤*Ò,Ð,°	´À5Ò0HÐ0HÐ0HÐJtÑ0HÔ0HÐHõ �a”hÑÔÐà—&’&˜‘*”*€KØ!¨Ð-ÐYÕ2OÐPQÔPXÑ2YÔ2YÐà�RÒÐÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆˆØ	�rÒ	Ð	˜k¨CÒ/Ð/ÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆˆØ	�sÒ	Ð	ÝÐ?°+Ð?Ð?Ñ@Ô@Ð@ð �8Š8�B‰<Œ<˜1ÒÐ §¢¨"¡¤°Ò!2Ð!2°q·x²xÀ±|´|ÀqÒ7HÐ7HÐ7HÐJoÑ7HÔ7HÐHà  EÒ)Ð)ˆaˆa¨q€Gàð Ø�VŠV˜¨ˆVÑ.Ô.ˆØð 	cØ Ò%Ð%Ý!&¤¨a¯kªk¸!¸QÑ.?Ô.?ÀÇÂÈaÐQRÑASÔAS×A]ÒA]Ð^_ÐabÑAcÔAcÑ!dÔ!d×!lÒ!lÐmoÑ!pÔ!p×!sÒ!sÕtyô  uBñ  "Cô  "C��å!&¤¨a°·²¸aÀÑ1CÔ1CÑ!DÔ!D×!LÒ!LÈRÑ!PÔ!P×!SÒ!SÕTYÔTaÑ!bÔ!b�øàˆà•”ÒÐ %­5¬=Ò"8Ð"8Ø�DŠD•”ÑÔˆàÐØ˜+¨Ñ,Ñ-ˆà˜xÒ'Ð'Øð 	BÝ/DÀQÈÈbÕWqõ  ySð  ^fð  vCð  0Dñ  0Dô  0DÑ,ˆF�G˜V W Wå/DÀQÈÈbÐ[cð  tAð  0Bñ  0Bô  0BÑ,ˆF�G˜V W WØ	 Ò	'Ð	'Ý+>¸qÀ!ÈÐU]ÐmzÐ+{Ñ+{Ô+{Ñ(ˆ�˜  åÐTÐ>RÐTÐTÑUÔUÐUØ	ˆ!ˆRàÐð  Ò%Ð%ð Œ\˜!Œ_˜fœl¨1œo¨v¬|¸A¬ÀÄÈQÄÐPÐPà”,˜q”/ 6¤<°¤?°F´LÀ´OÀVÄ\ÐRSÄ_ÐUð 	ð
 Œ?˜lÒ*Ð*Ø!×(Ò(¨Ñ6Ô6ˆIàð IÝ˜6 6¨1¨g°wÈmÐjoð  }Gð  Hñ  Hô  H‰ˆˆ3ˆ3Ø	ð IÝ.¨v°v¸qÀ'È7Ðboð  Dð  Q[ð  gpð  qñ  qô  q‰ˆˆ3ˆ3Ø	Ð	Ý˜F F¨A¨w¸È}Ðkpð  ~Hð  T]ð  ^ñ  ^ô  ^‰ˆˆ3ˆ3å˜F F¨A¨w¸È}Ðkpð  ~Hð  Iñ  Iô  I‰ˆˆ3à	ˆ#ˆ|�ˆ|Ð
Ô€Aàð ØÀ(Ð`�#˜
Ñ" ^°hÑ%>Ñ>Ð>ÐPSÐV`ÑP`Ð`Ð`àˆr$   rv   rw   rx   Úcu_seqlens_qÚcu_seqlens_kÚmax_seqlen_qÚmax_seqlen_kc
                 ó\  — | j         }| j        s
J d¦   «         ‚|t          j        t          j        fv s
J d¦   «         ‚| j        |j        cxk    r|j        k    sn J d¦   «         ‚| j         |j         cxk    r|j         k    sn J d¦   «         ‚t          |j        ¦  «         |                      d¦  «        }|dk     rt          j        j	         
                    | dd|z
  f¦  «        } t          j        j	         
                    |dd|z
  f¦  «        }t          j        j	         
                    |dd|z
  f¦  «        }n£|dk    r…|dk     rt          j        j	         
                    | dd|z
  f¦  «        } t          j        j	         
                    |dd|z
  f¦  «        }t          j        j	         
                    |dd|z
  f¦  «        }n|dk    rt          d	|› �¦  «        ‚|                      d¦  «        d
k    r2|                     d¦  «        d
k    r|                     d¦  «        d
k    s
J d¦   «         ‚|                     ¦   «         r|                     ¦   «         s
J d¦   «         ‚|t          j        k    s|t          j        k    r|                     t          j        ¦  «        }|	r|                     dd¬¦  «        }||z
  }|€d|dz  z  }t#          | ||||||¬¦  «        \  }}}}}}|rt%          |||||||||||¬¦  «        }nt'          |||||||||||¬¦  «        }|dd|…f         }|S )a2  

    Parameters
    ----------
    q : torch.Tensor
        The query tensor, shape: ``[cu_seqlens_q[-1], num_qo_heads, head_dim]``.

    k : torch.Tensor
        The key tensor, shape: ``[cu_seqlens_k[-1], num_kv_heads, head_dim]``.

    v : torch.Tensor
        The value tensor, shape: ``[cu_seqlens_k[-1], num_kv_heads, head_dim]``.

    cu_seqlens_q : torch.Tensor
        The cumulative sequence lengths for the query sequences in the batch, used to index into `q`. 
        Shape: ``[batch_size + 1]``, where each entry represents the cumulative length of sequences up to that batch index.

    cu_seqlens_k : torch.Tensor
        The cumulative sequence lengths for the key and value sequences in the batch, used to index into `k` and `v`. 
        Shape: ``[batch_size + 1]``, where each entry represents the cumulative length of sequences up to that batch index.

    max_seqlen_q : int
        The maximum sequence length for the query tensor in the batch.
    
    max_seqlen_k : int
        The maximum sequence length for the key and value tensors in the batch.

    is_causal : bool
        Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len for each sequence.
        Default: False.
    
    sm_scale : Optional[float]
        The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.

    smooth_k : bool
        Whether to smooth the key tensor by subtracting the mean along the sequence dimension.
        Default: True.

    Returns
    -------
    torch.Tensor
        The output tensor, shape: ``[cu_seqlens_q[-1], num_qo_heads, head_dim]``.

    Note
    ----
    - ``num_qo_heads`` must be divisible by ``num_kv_heads``.
    - The tensors `q`, `k`, and `v` must have the dtype ``torch.float16``, ``torch.bfloat16`` or ``torch.float32``.
    - The tensors `cu_seqlens_q` and `cu_seqlens_k` must have the dtype ``torch.int32`` or ``torch.int64``.
    - All tensors must be on the same cuda device.
    - `smooth_k` will introduce slight overhead but will improve the accuracy under most circumstances.
    rÉ   rÊ   rË   rÌ   r›   rF   r   rœ   rÍ   r)   rÎ   z1cu_seqlens_q and cu_seqlens_k must be contiguous.TrÏ   NrÒ   rÓ   )r«   )r}   .)r`   rÙ   r   r¤   r¥   rG   rY   rÛ   rÜ   rÝ   rÞ   rr   rq   Úis_contiguousrs   rã   rß   Úper_block_int8_varlen_tritonÚattn_true_varlenÚattn_false_varlen)rv   rw   rx   rï   rð   rñ   rò   rª   r«   rÇ   r­   r`   rè   rÔ   rì   ry   rí   rz   Úcu_seqlens_q_scaleÚcu_seqlens_k_scaler   s                        r"   Úsageattn_varlenrú   á  s¶  € ðD ŒG€EØŒ9Ð6Ð6Ð6Ñ6Ô6ˆ9Ø•U”]¥E¤NÐ3Ð3Ð3Ð3Ð5xÑ3Ô3Ð3ØŒ8�q”xÐ+Ð+Ò+Ð+ 1¤8Ò+Ð+Ð+Ð+Ð+Ð-VÑ+Ô+Ð+ØŒ7�a”gÐ(Ð(Ò(Ð( ¤Ò(Ð(Ð(Ð(Ð(Ð*QÑ(Ô(Ð(õ �a”hÑÔÐà—&’&˜‘*”*€Kà�RÒÐÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆˆØ	�rÒ	Ð	˜k¨CÒ/Ð/ÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆˆØ	�sÒ	Ð	ÝÐ?°+Ð?Ð?Ñ@Ô@Ð@à�8Š8�B‰<Œ<˜1ÒÐ §¢¨"¡¤°Ò!2Ð!2°q·x²xÀ±|´|ÀqÒ7HÐ7HÐ7HÐJoÑ7HÔ7HÐHØ×%Ò%Ñ'Ô'Ð}¨L×,FÒ,FÑ,HÔ,HÐ}Ð}ÐJ}Ñ}Ô}ÐHà•”ÒÐ %­5¬=Ò"8Ð"8Ø�DŠD•”ÑÔˆàð Ø�VŠV˜ 4ˆVÑ(Ô(ˆØ�‰FˆàÐØ˜+¨Ñ,Ñ-ˆåOkÐlmÐopÐr~ð  AMð  O[ð  ]ið  t|ð  P}ñ  P}ô  P}ÑL€FˆG�V˜WÐ&8Ð:Làð iÝ˜V V¨Q°¸lÈLÐZaÐcjÐl~ð  ASð  bgð  hñ  hô  hˆˆå˜f f¨a°¸|È\Ð[bÐdkÐmð  BTð  chð  iñ  iô  iˆà	ˆ#ˆ|�ˆ|Ð
Ô€Aà€Hr$   Ú
per_threadr±   rº   r²   r»   c	                 ó`  — | \  }
}}|                       ¦   «          |
j        }t          s
J d¦   «         ‚|
j        s
J d¦   «         ‚|t          j        t          j        fv s
J d¦   «         ‚|dv s
J d¦   «         ‚|
j        |j        cxk    r|j        k    sn J d¦   «         ‚|
j        |j        cxk    r|j        k    sn J d¦   «         ‚t          |j        ¦  «         |dk    rd	nd
}|rd
nd	}|dk    rdnd}|rd
nd	}|
 	                    d¦  «        }|dk     rt          j
        j                             |
d	d|z
  f¦  «        }
t          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }n£|dk    r…|dk     rt          j
        j                             |
d	d|z
  f¦  «        }
t          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }n|dk    rt          d|› �¦  «        ‚|
                     d¦  «        d
k    r2|                     d¦  «        d
k    r|                     d¦  «        d
k    s
J d¦   «         ‚|€|dz  }|d	k    rd
nd}|rû|                     |d¬¦  «        }|rá|dk    r‚t	          j        |
                     d
d¦  «        |                     d
d¦  «                             dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }n\t	          j        |
|                     dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }nd}|dk    r=t+          |
|||d|
 	                    d¦  «        dk    r|dk    rdndd¬¦  «        \  }}}}nC|dk    r=t-          |
|||d|
 	                    d¦  «        dk    r|dk    rdnddd¬¦  «        \  }}}}|
 	                    ¦   «         }|
j        }~
~~t	          j        |||¬¦  «        }|dv r|rt1          j        d|› d �¦  «         d!}|d"k    r>|                     t          j        ¦  «        }t5          j        |||||||||||¦  «        }nÑ|d#k    ru|r5t9          ||¬$¦  «        \  }}~t5          j        ||||||||||||¦  «        }n”|                     t          j        ¦  «        }t5          j        |||||||||||¦  «        }nV|dk    r>|                     t          j        ¦  «        }t5          j        |||||||||||¦  «        }nt          d%|› �¦  «        ‚|d&d|…f         }|r||r|d'z  ||z  z   n|d'z  fS |S )(ah  
    SageAttention with INT8 quantization for Q and K, FP16 PV with FP16/FP32 accumulation, implemented using CUDA.

    Parameters
    ----------
    q : torch.Tensor
        The query tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    k : torch.Tensor
        The key tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    v : torch.Tensor
        The value tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    tensor_layout : str
        The tensor layout, either "HND" or "NHD".
        Default: "HND".

    is_causal : bool
        Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len.
        Default: False.

    qk_quant_gran : str
        The granularity of quantization for Q and K, either "per_warp" or "per_thread".
        Default: "per_thread".

    sm_scale : Optional[float]
        The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.

    pv_accum_dtype : str
        The dtype of the accumulation of the product of the value tensor and the attention weights, either "fp16", "fp16+fp32" or "fp32".
        - "fp16": PV accumulation is done in fully in FP16. This is the fastest option but may lead to numerical instability. `smooth_v` option will increase the accuracy in cases when the value tensor has a large bias (like in CogVideoX-2b).
        - "fp32": PV accumulation is done in FP32. This is the most accurate option but may be slower than "fp16" due to CUDA core overhead.
        - "fp16+fp32": PV accumulation is done in FP16, but added to a FP32 buffer every few iterations. This offers a balance between speed and accuracy.
        Default: "fp32".

    smooth_k : bool
        Whether to smooth the key tensor by subtracting the mean along the sequence dimension.
        Default: True.
    
    smooth_v : bool
        Whether to smooth the value tensor by subtracting the mean along the sequence dimension.
        smooth_v will be ignored if pv_accum_dtype is "fp32" or "fp16+fp32".
        Default: False.

    return_lse : bool
        Whether to return the log sum of the exponentiated attention weights. Used for cases like Ring Attention.
        Default: False.

    Returns
    -------
    torch.Tensor
        The output tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    torch.Tensor
        The logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax normalization factor).
        Shape: ``[batch_size, num_qo_heads, qo_len]``.
        Only returned if `return_lse` is True.

    Note
    ----
    - ``num_qo_heads`` must be divisible by ``num_kv_heads``. 
    - The tensors `q`, `k`, and `v` must have the dtype ``torch.float16`` or ``torch.bfloat16``
    - All tensors must be on the same cuda device.
    - `smooth_k` will introduce slight overhead but will improve the accuracy under most circumstances.
    zWSM80 kernel is not available. make sure you GPUs with compute capability 8.0 or higher.rÉ   rÊ   ©r¹   rû   ú8qk_quant_gran must be either 'per_warp' or 'per_thread'.rË   rÌ   ra   r   r)   rû   rb   r*   r›   rF   rœ   rÍ   rÎ   Nç      à¿TrÏ   r¹   ú	fp16+fp32é   é    ©r{   rÕ   ÚWARPQrÖ   ©r{   rÕ   r  rÖ   ÚWARPKr_   )r±   r   zpv_accum_dtype is z, smooth_v will be ignored.Fr±   Úfp16r¯   zUnsupported pv_accum_dtype: .r×   ) rØ   r`   ÚSM80_ENABLEDrÙ   r   r¤   r¥   rG   rY   rÛ   rÜ   rÝ   rÞ   rr   rq   rß   rà   rá   râ   rã   rs   Úper_warp_int8_cudaÚper_thread_int8_tritonro   ÚwarningsÚwarnr
   r   r   Ú)qk_int8_sv_f16_accum_f16_fuse_v_mean_attnÚqk_int8_sv_f16_accum_f16_attnÚ&qk_int8_sv_f16_accum_f16_attn_inst_buf) r¦   r{   rª   rº   r«   r²   rÇ   r»   r~   r­   rv   rw   rx   r`   Ú_tensor_layoutÚ	_is_caualÚ_qk_quant_granÚ_return_lserè   rê   rÔ   rë   rì   ry   rí   rz   Úq_sizeÚq_devicer   r—   Ú
smoothed_vÚvms                                    r"   r¾   r¾   V  sm  € ðt �E€A€aˆØ‡N‚NÑÔÐØŒG€EÝÐrÐrÐrÑrÔrˆ<ØŒ9Ð6Ð6Ð6Ñ6Ô6ˆ9Ø•U”]¥E¤NÐ3Ð3Ð3Ð3Ð5xÑ3Ô3Ð3ØÐ6Ð6Ð6Ð6Ð8rÑ6Ô6Ð6ØŒ8�q”xÐ+Ð+Ò+Ð+ 1¤8Ò+Ð+Ð+Ð+Ð+Ð-VÑ+Ô+Ð+ØŒ7�a”gÐ(Ð(Ò(Ð( ¤Ò(Ð(Ð(Ð(Ð(Ð*QÑ(Ô(Ð(õ �a”hÑÔÐà'¨5Ò0Ð0�Q�Q°a€NØÐ%�� A€IØ'¨<Ò7Ð7�Q�Q¸Q€NØ!Ð(�!�! q€Kà—&’&˜‘*”*€Kà�RÒÐÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆˆØ	�rÒ	Ð	˜k¨CÒ/Ð/ÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆˆØ	�sÒ	Ð	ÝÐ?°+Ð?Ð?Ñ@Ô@Ð@ð �8Š8�B‰<Œ<˜1ÒÐ §¢¨"¡¤°Ò!2Ð!2°q·x²xÀ±|´|ÀqÒ7HÐ7HÐ7HÐJoÑ7HÔ7HÐHàÐØ Ñ$ˆà! QÒ&Ð&ˆaˆa¨A€Gàð Ø�VŠV˜¨ˆVÑ.Ô.ˆØð 	cØ Ò%Ð%Ý!&¤¨a¯kªk¸!¸QÑ.?Ô.?ÀÇÂÈaÐQRÑASÔAS×A]ÒA]Ð^_ÐabÑAcÔAcÑ!dÔ!d×!lÒ!lÐmoÑ!pÔ!p×!sÒ!sÕtyô  uBñ  "Cô  "C��å!&¤¨a°·²¸aÀÑ1CÔ1CÑ!DÔ!D×!LÒ!LÈRÑ!PÔ!P×!SÒ!SÕTYÔTaÑ!bÔ!b�øàˆà˜
Ò"Ð"Ý+=¸aÀÀBÐVcÐjmÐ}~÷  ~Dò  ~Dð  EGñ  ~Hô  ~Hð  LOò  ~Oð  ~Oð  Tbð  fqò  Tqð  TqÐvxÐvxð  xzð  BDð  ,Eñ  ,Eô  ,EÑ(ˆ�˜  Ø	˜,Ò	&Ð	&Ý+AÀ!ÀQÈÐZgÐnqð  BC÷  BHò  BHð  IKñ  BLô  BLð  PSò  BSð  BSð  Xfð  juò  Xuð  XuÐz|Ðz|ð  |~ð  FHð  PRð  ,Sñ  ,Sô  ,SÑ(ˆ�˜ à�VŠV‰XŒX€FØŒx€HØ	ˆ!ˆRÝŒ�F %°Ð9Ñ9Ô9€AàÐ.Ð.Ð.°8Ð.ÝŒÐV¨>ÐVÐVÐVÑWÔWÐWØˆà˜ÒÐØ�DŠD•”ÑÔˆÝÔ7¸ÀÈÈ1ÈgÐW^Ð`nÐpyð  |Jð  LTð  Vañ  bô  bˆˆØ	˜6Ò	!Ð	!Øð 	fÝ% a°}ÐEÑEÔE‰NˆJ˜ØÝÔGÈÐPVÐXbÐdeÐgnÐpwÐy{ð  ~Lð  NWð  Ygð  iqð  s~ñ  ô  ˆCˆCà—’•U”]Ñ#Ô#ˆAÝÔ;¸FÀFÈAÈqÐRYÐ[bÐdrÐt}ð  @Nð  PXð  Zeñ  fô  fˆCˆCØ	˜;Ò	&Ð	&Ø�DŠD•”ÑÔˆÝÔ@ÀÈÐQRÐTUÐW^Ð`gÐiwð  zCð  ESð  U]ð  _jñ  kô  kˆˆåÐH¸ÐHÐHÑIÔIÐIà	ˆ#ˆ|�ˆ|Ð
Ô€Aàð ØÀ(Ð`�#˜
Ñ" ^°hÑ%>Ñ>Ð>ÐPSÐV`ÑP`Ð`Ð`àˆr$   c
                 óÊ
  — |d k    rt           rdnd}	 | \  }}}|                      ¦   «          |j        }t          s
J d¦   «         ‚|j        s
J d¦   «         ‚|t
          j        t
          j        fv s
J d¦   «         ‚|dv s
J d¦   «         ‚|j        |j        cxk    r|j        k    sn J d¦   «         ‚|j        |j        cxk    r|j        k    sn J d	¦   «         ‚t          |j        ¦  «         |d
k    rdnd}|rdnd}|dk    rdnd}|rdnd}| 
                    d¦  «        }|dk     rt
          j        j                             |dd|z
  f¦  «        }t
          j        j                             |dd|z
  f¦  «        }t
          j        j                             |dd|z
  f¦  «        }n£|dk    r…|dk     rt
          j        j                             |dd|z
  f¦  «        }t
          j        j                             |dd|z
  f¦  «        }t
          j        j                             |dd|z
  f¦  «        }n|dk    rt          d|› �¦  «        ‚|                     d¦  «        dk    r2|                     d¦  «        dk    r|                     d¦  «        dk    s
J d¦   «         ‚|€|dz  }|dk    rdnd}|dk    r|rt!          j        d¦  «         d}|g}~t           r@|dk    r|rt!          j        d¦  «         d}d}|dk    rd}t%          ||||¬¦  «        \  }}}nt%          |||¬¦  «        \  }}}|rû|                     |d¬¦  «        }|rá|d
k    r‚t          j        |                     dd¦  «        |                     dd¦  «                             dd¦  «        ¦  «                             d¦  «                             t
          j        ¦  «        }n\t          j        ||                     dd¦  «        ¦  «                             d¦  «                             t
          j        ¦  «        }nd }|dk    rt3          ||||dd d¬!¦  «        \  }}}}n"|dk    rt5          ||||dd dd¬"¦  «        \  }}}}| 
                    ¦   «         } |j        }!|	r~~|}"n~~~t          j        | ||!¬#¦  «        }"|d$k    rC|r!t9          j        ||||"|||||||||¦  «        }#nkt9          j        ||||"||||||||¦  «        }#nK|dk    r t9          j        ||||"||||||||¦  «        }#n%|dk    rt9          j         ||||"||||||||¦  «        }#|"d%d |…f         }"|r|"|r|#d&z  ||z  z   n|#d&z  fS |"S )'Nrµ   r¶   úMSM89 kernel is not available. Make sure you GPUs with compute capability 8.9.rÉ   rÊ   rý   rþ   rË   rÌ   ra   r   r)   rû   rb   r*   r›   rF   rœ   rÍ   rÎ   rÿ   ú8pv_accum_dtype is 'fp32+fp32', smooth_v will be ignored.Fz8pv_accum_dtype is 'fp32+fp16', smooth_v will be ignored.ç      |@g      @)r{   Ú	scale_maxr»   ©r{   r»   TrÏ   r¹   r  r  r  r_   r±   .r×   )!rÀ   rØ   r`   ÚSM89_ENABLEDrÙ   r   r¤   r¥   rG   rY   rÛ   rÜ   rÝ   rÞ   rr   rq   r  r  r   rß   rà   rá   râ   rã   rs   r	  r
  ro   r   Ú5qk_int8_sv_f8_accum_f32_fuse_v_scale_fuse_v_mean_attnÚ)qk_int8_sv_f8_accum_f32_fuse_v_scale_attnr   Ú2qk_int8_sv_f8_accum_f16_fuse_v_scale_attn_inst_buf)$r¦   r{   rª   rº   r«   r²   rÇ   r»   r~   r¬   r­   rv   rw   rx   r`   r  r  r  r  rè   rê   Úv_listÚquant_v_scale_maxÚv_fp8Úv_scaler  rÔ   rë   rì   ry   rí   rz   r  r  r   r—   s$                                       r"   r¿   r¿     s>  € ð ˜ÒÐÝ(-Ð>˜˜°;ˆðHðR �G€A€qˆ!Ø‡N‚NÑÔÐàŒG€EÝÐhÐhÐhÑhÔhˆ<ØŒ9Ð6Ð6Ð6Ñ6Ô6ˆ9Ø•U”]¥E¤NÐ3Ð3Ð3Ð3Ð5xÑ3Ô3Ð3ØÐ6Ð6Ð6Ð6Ð8rÑ6Ô6Ð6ØŒ8�q”xÐ+Ð+Ò+Ð+ 1¤8Ò+Ð+Ð+Ð+Ð+Ð-VÑ+Ô+Ð+ØŒ7�a”gÐ(Ð(Ò(Ð( ¤Ò(Ð(Ð(Ð(Ð(Ð*QÑ(Ô(Ð(õ �a”hÑÔÐà'¨5Ò0Ð0�Q�Q°a€NØÐ%�� A€IØ'¨<Ò7Ð7�Q�Q¸Q€NØ!Ð(�!�! q€Kà—&’&˜‘*”*€Kà�RÒÐÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆˆØ	�rÒ	Ð	˜k¨CÒ/Ð/ÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆˆØ	�sÒ	Ð	ÝÐ?°+Ð?Ð?Ñ@Ô@Ð@ð �8Š8�B‰<Œ<˜1ÒÐ §¢¨"¡¤°Ò!2Ð!2°q·x²xÀ±|´|ÀqÒ7HÐ7HÐ7HÐJoÑ7HÔ7HÐHàÐØ Ñ$ˆØ! QÒ&Ð&ˆaˆa¨A€Gà˜Ò$Ð$¨Ð$ÝŒÐPÑQÔQÐQØˆð ˆS€FØ	Ýð 
eØ˜[Ò(Ð(¨XÐ(ÝŒMÐTÑUÔUÐUØˆHà!ÐØ˜[Ò(Ð(Ø $ÐÝ,¨VÀ=Ð\mð  yAð  Bñ  Bô  BÑˆˆw˜˜å,¨VÀ=Ð[cÐdÑdÔdÑˆˆw˜ð ð Ø�VŠV˜¨ˆVÑ.Ô.ˆØð 	cØ Ò%Ð%Ý!&¤¨a¯kªk¸!¸QÑ.?Ô.?ÀÇÂÈaÐQRÑASÔAS×A]ÒA]Ð^_ÐabÑAcÔAcÑ!dÔ!d×!lÒ!lÐmoÑ!pÔ!p×!sÒ!sÕtyô  uBñ  "Cô  "C��å!&¤¨a°·²¸aÀÑ1CÔ1CÑ!DÔ!D×!LÒ!LÈRÑ!PÔ!P×!SÒ!SÕTYÔTaÑ!bÔ!b�øàˆà˜
Ò"Ð"Ý+=¸aÀÀBÐVcÐjmÐuwð  Að  ,Bñ  ,Bô  ,BÑ(ˆ�˜  Ø	˜,Ò	&Ð	&Ý+AÀ!ÀQÈÐZgÐnqÐy{ð  CEð  MOð  ,Pñ  ,Pô  ,PÑ(ˆ�˜ Ø�VŠV‰XŒX€FØŒx€HØð >ØˆbØˆˆàˆa�ÝŒK˜ e°HÐ=Ñ=Ô=ˆØ˜ÒÐØð 	ÝÔSÐTZÐ\bÐdiÐklÐnuÐw~ð  AHð  JLð  N\ð  ^gð  iwð  yAð  CNñ  Oô  OˆCˆCåÔGÈÐPVÐX]Ð_`ÐbiÐkrÐt{ð  ~Lð  NWð  Ygð  iqð  s~ñ  ô  ˆCˆCØ	˜;Ò	&Ð	&ÝÔLÈVÐU[Ð]bÐdeÐgnÐpwð  zAð  CQð  S\ð  ^lð  nvð  xCñ  Dô  DˆˆØ	˜;Ò	&Ð	&ÝÔLÈVÐU[Ð]bÐdeÐgnÐpwð  zAð  CQð  S\ð  ^lð  nvð  xCñ  Dô  Dˆð 	
ˆ#ˆ|�ˆ|Ð
Ô€Aàð ØÀ(Ð`�#˜
Ñ" ^°hÑ%>Ñ>Ð>ÐPSÐV`ÑP`Ð`Ð`àˆr$   r¶   r›   c                 óÎ	  — | \  }}}|                       ¦   «          |j        }t          s
J d¦   «         ‚|j        s
J d¦   «         ‚|t          j        t          j        fv s
J d¦   «         ‚|dv s
J d¦   «         ‚|j        |j        cxk    r|j        k    sn J d¦   «         ‚|j        |j        cxk    r|j        k    sn J d¦   «         ‚t          |j        ¦  «         |dk    rd	nd
}|rd
nd	}|dk    rdnd}|rd
nd	}| 	                    d¦  «        }|dk     rt          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }n£|dk    r…|dk     rt          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }n|dk    rt          d|› �¦  «        ‚|                     d¦  «        d
k    r2|                     d¦  «        d
k    r|                     d¦  «        d
k    s
J d¦   «         ‚|€|dz  }|d	k    rd
nd}|dk    r|rt          j        d¦  «         d}|g}~t#          |||¬¦  «        \  }}}|rû|                     |d¬¦  «        }|rá|dk    r‚t	          j        |                     d
d¦  «        |                     d
d¦  «                             dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }n\t	          j        ||                     dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }nd}|dk    rt1          ||||ddd¬¦  «        \  }}}}n"|dk    rt3          ||||dddd¬¦  «        \  }}}}| 	                    ¦   «         } |j        }!|
r~|}"n~~t	          j        | ||!¬¦  «        }"|d k    rE|r"t7          j        ||||"||||||||||	¦  «        }#nGt7          j        ||||"|||||||||	¦  «        }#n&|dk    r t7          j        ||||"|||||||||	¦  «        }#|"d!d|…f         }"|r|"|r|#d"z  ||z  z   n|#d"z  fS |"S )#a‹  
    SageAttention with INT8 quantization for Q and K, FP8 PV with FP32 accumulation, implemented using CUDA.

    Parameters
    ----------
    q : torch.Tensor
        The query tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    k : torch.Tensor
        The key tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    v : torch.Tensor
        The value tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    tensor_layout : str
        The tensor layout, either "HND" or "NHD".
        Default: "HND".

    is_causal : bool
        Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len.
        Default: False.

    qk_quant_gran : str
        The granularity of quantization for Q and K, either "per_warp" or "per_thread".
        Default: "per_thread".

    sm_scale : Optional[float]
        The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.

    pv_accum_dtype : str
        The dtype of the accumulation of the product of the value tensor and the attention weights, either "fp32" or "fp32+fp32".
        - "fp32": PV accumulation is done in fully in FP32. However, due to the hardware issue, there are only 22 valid bits in the FP32 accumulator.
        - "fp32+fp32": PV accumulation is done in FP32 (actually FP22), but added to a FP32 buffer every few iterations. This offers a balance between speed and accuracy.
        Default: "fp32+fp32".
        
    smooth_k : bool
        Whether to smooth the key tensor by subtracting the mean along the sequence dimension.
        Default: True.
    
    smooth_v : bool
        Whether to smooth the value tensor by subtracting the mean along the sequence dimension.
        smooth_v will be ignored if pv_accum_dtype is "fp32+fp32".
        Default: False.

    return_lse : bool
        Whether to return the log sum of the exponentiated attention weights. Used for cases like Ring Attention.
        Default: False.

    Returns
    -------
    torch.Tensor
        The output tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

            torch.Tensor
        The logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax normalization factor).
        Shape: ``[batch_size, num_qo_heads, qo_len]``.
        Only returned if `return_lse` is True.

    Note
    ----
    - ``num_qo_heads`` must be divisible by ``num_kv_heads``. 
    - The tensors `q`, `k`, and `v` must have the dtype ``torch.float16`` or ``torch.bfloat16``
    - All tensors must be on the same cuda device.
    - `smooth_k` will introduce slight overhead but will improve the accuracy under most circumstances.
    r  rÉ   rÊ   rý   rþ   rË   rÌ   ra   r   r)   rû   rb   r*   r›   rF   rœ   rÍ   rÎ   Nrÿ   r¶   r  Fr  TrÏ   r¹   r  r  r  r_   r±   .r×   )rØ   r`   r  rÙ   r   r¤   r¥   rG   rY   rÛ   rÜ   rÝ   rÞ   rr   rq   r  r  r   rß   rà   rá   râ   rã   rs   r	  r
  ro   r   r  r   r   )$r¦   r{   rª   rº   r«   r²   rÇ   r»   r~   Úwindowr¬   r­   rv   rw   rx   r`   r  r  r  r  rè   rê   r"  r$  r%  r  rÔ   rë   rì   ry   rí   rz   r  r  r   r—   s$                                       r"   Ú#sageattn_qk_int8_pv_fp8_window_cudar(  Õ  sX  € ðv �E€A€aˆØ‡N‚NÑÔÐØŒG€EÝÐhÐhÐhÑhÔhˆ<ØŒ9Ð6Ð6Ð6Ñ6Ô6ˆ9Ø•U”]¥E¤NÐ3Ð3Ð3Ð3Ð5xÑ3Ô3Ð3ØÐ6Ð6Ð6Ð6Ð8rÑ6Ô6Ð6ØŒ8�q”xÐ+Ð+Ò+Ð+ 1¤8Ò+Ð+Ð+Ð+Ð+Ð-VÑ+Ô+Ð+ØŒ7�a”gÐ(Ð(Ò(Ð( ¤Ò(Ð(Ð(Ð(Ð(Ð*QÑ(Ô(Ð(õ �a”hÑÔÐà'¨5Ò0Ð0�Q�Q°a€NØÐ%�� A€IØ'¨<Ò7Ð7�Q�Q¸Q€NØ!Ð(�!�! q€Kà—&’&˜‘*”*€Kà�RÒÐÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆˆØ	�rÒ	Ð	˜k¨CÒ/Ð/ÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆˆØ	�sÒ	Ð	ÝÐ?°+Ð?Ð?Ñ@Ô@Ð@ð �8Š8�B‰<Œ<˜1ÒÐ §¢¨"¡¤°Ò!2Ð!2°q·x²xÀ±|´|ÀqÒ7HÐ7HÐ7HÐJoÑ7HÔ7HÐHàÐØ Ñ$ˆà! QÒ&Ð&ˆaˆa¨A€Gà˜Ò$Ð$¨Ð$ÝŒÐPÑQÔQÐQØˆàˆS€FØ	Ý(¨¸}ÐW_Ð`Ñ`Ô`Ñ€Eˆ7�Bàð Ø�VŠV˜¨ˆVÑ.Ô.ˆØð 	cØ Ò%Ð%Ý!&¤¨a¯kªk¸!¸QÑ.?Ô.?ÀÇÂÈaÐQRÑASÔAS×A]ÒA]Ð^_ÐabÑAcÔAcÑ!dÔ!d×!lÒ!lÐmoÑ!pÔ!p×!sÒ!sÕtyô  uBñ  "Cô  "C��å!&¤¨a°·²¸aÀÑ1CÔ1CÑ!DÔ!D×!LÒ!LÈRÑ!PÔ!P×!SÒ!SÕTYÔTaÑ!bÔ!b�øàˆà˜
Ò"Ð"Ý+=¸aÀÀBÐVcÐjmÐuwð  Að  ,Bñ  ,Bô  ,BÑ(ˆ�˜  Ø	˜,Ò	&Ð	&Ý+AÀ!ÀQÈÐZgÐnqÐy{ð  CEð  MOð  ,Pñ  ,Pô  ,PÑ(ˆ�˜ à�VŠV‰XŒX€FØŒx€HØð >ØØˆˆàˆaÝŒK˜ e°HÐ=Ñ=Ô=ˆà˜ÒÐØð 	HÝÔSÐTZÐ\bÐdiÐklÐnuÐw~ð  AHð  JLð  N\ð  ^gð  iwð  yAð  CNð  PVñ  Wô  WˆCˆCåÔGÈÐPVÐX]Ð_`ÐbiÐkrÐt{ð  ~Lð  NWð  Ygð  iqð  s~ð  AGñ  Hô  HˆCˆCØ	˜;Ò	&Ð	&ÝÔLÈVÐU[Ð]bÐdeÐgnÐpwð  zAð  CQð  S\ð  ^lð  nvð  xCð  FLñ  Mô  Mˆà	ˆ#ˆ|�ˆ|Ð
Ô€Aàð ØÀ(Ð`�#˜
Ñ" ^°hÑ%>Ñ>Ð>ÐPSÐV`ÑP`Ð`Ð`àˆr$   c	                 óZ  — | \  }
}}|                       ¦   «          |
j        }t          s
J d¦   «         ‚|
j        s
J d¦   «         ‚|t          j        t          j        fv s
J d¦   «         ‚|dv s
J d¦   «         ‚|
j        |j        cxk    r|j        k    sn J d¦   «         ‚|
j        |j        cxk    r|j        k    sn J d¦   «         ‚t          |j        ¦  «         |dk    rd	nd
}|rd
nd	}|dk    rdnd}|rd
nd	}|
 	                    d¦  «        }|dk     rt          j
        j                             |
d	d|z
  f¦  «        }
t          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }n£|dk    r…|dk     rt          j
        j                             |
d	d|z
  f¦  «        }
t          j
        j                             |d	d|z
  f¦  «        }t          j
        j                             |d	d|z
  f¦  «        }n|dk    rt          d|› �¦  «        ‚|
                     d¦  «        d
k    r2|                     d¦  «        d
k    r|                     d¦  «        d
k    s
J d¦   «         ‚|€|dz  }|d	k    rd
nd}| 	                    |¦  «        }|dz  d	k    rd|dz  z
  nd	}|d	k    rí|dk    rtt	          j        |t	          j        | 	                    d	¦  «        | 	                    d
¦  «        || 	                    d¦  «        |j        |j        ¬¦  «        gd¬¦  «        }nst	          j        |t	          j        | 	                    d	¦  «        || 	                    d¦  «        | 	                    d¦  «        |j        |j        ¬¦  «        gd
¬¦  «        }|g}~t#          ||d¬¦  «        \  }}}|rû|                     |d¬¦  «        }|rá|dk    r‚t	          j        |
                     d
d¦  «        |                     d
d¦  «                             dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }n\t	          j        |
|                     dd¦  «        ¦  «                             d¦  «                             t          j        ¦  «        }nd}|dk    rt1          |
|||ddd¬¦  «        \  }}}}n"|dk    rt3          |
|||dddd¬¦  «        \  }}}}|
 	                    ¦   «         } |
j        }!|r~|
}"n~
~t	          j        | ||!¬¦  «        }"|d k    rt7          d!¦  «        ‚|d"k    rt9          j        ||||"||||||||¦  «        }#|"d#d|…f         }"|r|"|r|#d$z  ||z  z   n|#d$z  fS |"S )%a¶  
    SageAttention with INT8 quantization for Q and K, FP8 PV with FP32 accumulation, implemented using CUDA.

    Parameters
    ----------
    q : torch.Tensor
        The query tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

    k : torch.Tensor
        The key tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    v : torch.Tensor
        The value tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_kv_heads, kv_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, kv_len, num_kv_heads, head_dim]``.

    tensor_layout : str
        The tensor layout, either "HND" or "NHD".
        Default: "HND".

    is_causal : bool
        Whether to apply causal mask to the attention matrix. Only applicable when qo_len == kv_len.
        Default: False.

    qk_quant_gran : str
        The granularity of quantization for Q and K, either "per_warp" or "per_thread".
        Default: "per_thread".

    sm_scale : Optional[float]
        The scale used in softmax, if not provided, will be set to ``1.0 / sqrt(head_dim)``.

    pv_accum_dtype : str
        The dtype of the accumulation of the product of the value tensor and the attention weights, either "fp32" or "fp32+fp32".
        - "fp32": PV accumulation is done in fully in FP32. However, due to the hardware issue, there are only 22 valid bits in the FP32 accumulator.
        - "fp32+fp32": PV accumulation is done in FP32 (actually FP22), but added to a FP32 buffer every few iterations. This offers a balance between speed and accuracy.
        Default: "fp32+fp32".
        
    smooth_k : bool
        Whether to smooth the key tensor by subtracting the mean along the sequence dimension.
        Default: True.

    return_lse : bool
        Whether to return the log sum of the exponentiated attention weights. Used for cases like Ring Attention.
        Default: False.

    Returns
    -------
    torch.Tensor
        The output tensor. Shape:
        - If `tensor_layout` is "HND": ``[batch_size, num_qo_heads, qo_len, head_dim]``.
        - If `tensor_layout` is "NHD": ``[batch_size, qo_len, num_qo_heads, head_dim]``.

            torch.Tensor
        The logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax normalization factor).
        Shape: ``[batch_size, num_qo_heads, qo_len]``.
        Only returned if `return_lse` is True.

    Note
    ----
    - ``num_qo_heads`` must be divisible by ``num_kv_heads``. 
    - The tensors `q`, `k`, and `v` must have the dtype ``torch.float16`` or ``torch.bfloat16``
    - All tensors must be on the same cuda device.
    - `smooth_k` will introduce slight overhead but will improve the accuracy under most circumstances.
    zMSM90 kernel is not available. Make sure you GPUs with compute capability 9.0.rÉ   rÊ   rý   rþ   rË   rÌ   ra   r   r)   rû   rb   r*   r›   rF   rœ   rÍ   rÎ   Nrÿ   r]   r_   )rÐ   Fr  TrÏ   r¹   r  r  r  r±   z/Please use pv_accum_dtype='fp32+fp32' for sm90.r¶   .r×   )rØ   r`   ÚSM90_ENABLEDrÙ   r   r¤   r¥   rG   rY   rÛ   rÜ   rÝ   rÞ   rr   rq   ÚcatÚzerosr   rß   rà   rá   râ   rã   rs   r	  r
  ro   ÚNotImplementedErrorr   r   r   )$r¦   r{   rª   rº   r«   r²   rÇ   r~   r¬   r­   rv   rw   rx   r`   r  r  r  r  rè   rê   r†   Ú	v_pad_lenr"  r$  r%  r„   rÔ   rë   rì   ry   rí   rz   r  r  r   r—   s$                                       r"   rÁ   rÁ   ‹  ss  € ðh �E€A€aˆØ‡N‚NÑÔÐØŒG€EÝÐhÐhÐhÑhÔhˆ<ØŒ9Ð6Ð6Ð6Ñ6Ô6ˆ9Ø•U”]¥E¤NÐ3Ð3Ð3Ð3Ð5xÑ3Ô3Ð3ØÐ6Ð6Ð6Ð6Ð8rÑ6Ô6Ð6ØŒ8�q”xÐ+Ð+Ò+Ð+ 1¤8Ò+Ð+Ð+Ð+Ð+Ð-VÑ+Ô+Ð+ØŒ7�a”gÐ(Ð(Ò(Ð( ¤Ò(Ð(Ð(Ð(Ð(Ð*QÑ(Ô(Ð(å�a”hÑÔÐà'¨5Ò0Ð0�Q�Q°a€NØÐ%�� A€IØ'¨<Ò7Ð7�Q�Q¸Q€NØ!Ð(�!�! q€Kà—&’&˜‘*”*€Kà�RÒÐÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆÝŒHÔ×#Ò# A¨¨2°Ñ+;Ð'<Ñ=Ô=ˆˆØ	�rÒ	Ð	˜k¨CÒ/Ð/ÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆÝŒHÔ×#Ò# A¨¨3°Ñ+<Ð'=Ñ>Ô>ˆˆØ	�sÒ	Ð	ÝÐ?°+Ð?Ð?Ñ@Ô@Ð@ð �8Š8�B‰<Œ<˜1ÒÐ §¢¨"¡¤°Ò!2Ð!2°q·x²xÀ±|´|ÀqÒ7HÐ7HÐ7HÐJoÑ7HÔ7HÐHàÐØ Ñ$ˆà! QÒ&Ð&ˆaˆa¨A€Gð
 �VŠV�G‰_Œ_€FØ(.°©¸Ò(9Ð(9��v ‘|Ñ$Ð$¸q€IØ�1‚}€}Ø˜EÒ!Ð!Ý”	˜1�eœk¨!¯&ª&°©)¬)°Q·V²V¸A±Y´YÀ	È1Ï6Ê6ÐRSÉ9Ì9Ð\]Ô\cÐlmÔltÐuÑuÔuÐvÐ|}Ð~Ñ~Ô~ˆAˆAå”	˜1�eœk¨!¯&ª&°©)¬)°YÀÇÂÀqÁ	Ä	È1Ï6Ê6ÐRSÉ9Ì9Ð\]Ô\cÐlmÔltÐuÑuÔuÐvÐ|}Ð~Ñ~Ô~ˆAàˆS€FØ	Ý'¨¸mÐV[Ð\Ñ\Ô\Ñ€Eˆ7�Aàð Ø�VŠV˜¨ˆVÑ.Ô.ˆØð 	cØ Ò%Ð%Ý!&¤¨a¯kªk¸!¸QÑ.?Ô.?ÀÇÂÈaÐQRÑASÔAS×A]ÒA]Ð^_ÐabÑAcÔAcÑ!dÔ!d×!lÒ!lÐmoÑ!pÔ!p×!sÒ!sÕtyô  uBñ  "Cô  "C��å!&¤¨a°·²¸aÀÑ1CÔ1CÑ!DÔ!D×!LÒ!LÈRÑ!PÔ!P×!SÒ!SÕTYÔTaÑ!bÔ!b�øàˆà˜
Ò"Ð"Ý+=¸aÀÀBÐVcÐjlÐtvð  ~Að  ,Bñ  ,Bô  ,BÑ(ˆ�˜  Ø	˜,Ò	&Ð	&Ý+AÀ!ÀQÈÐZgÐnpÐxzð  BEð  MPð  ,Qñ  ,Qô  ,QÑ(ˆ�˜ à�VŠV‰XŒX€FØŒx€HØð >ØØˆˆàˆaÝŒK˜ e°HÐ=Ñ=Ô=ˆà˜ÒÐÝ!Ð"SÑTÔTÐTà	˜;Ò	&Ð	&ÝÔLÈVÐU[Ð]bÐdeÐgnÐpwð  zAð  CQð  S\ð  ^lð  nvð  xCñ  Dô  Dˆà	ˆ#ˆ|�ˆ|Ð
Ô€Aàð ØÀ(Ð`�#˜
Ñ" ^°hÑ%>Ñ>Ð>ÐPSÐV`ÑP`Ð`Ð`àˆr$   r  Ú	v_or_listr  c           	      ó
  — |dk    rdnd}t          | t          ¦  «        r| d         }|                      ¦   «          n| }|j        }|dk    r8|j        \  }}}	}
|	dz   dz  dz  }t          j        |||
|f|j        |¬¦  «        }n=|dk    r7|j        \  }}	}}
|	dz   dz  dz  }t          j        ||
||f|j        |¬¦  «        }t          j	        |||¦  «         ~t          j        |j        t
          j
        |¬¦  «        }t          j        |||
ft
          j        |¬¦  «        }t          j        |||
ft
          j        |¬¦  «        }|rt          j        |||||	||¦  «         |||fS t          j        ||||	||¦  «         ||d fS )Nra   r   r)   r]   é?   rF   r_   )Ú
isinstanceÚlistrØ   rG   rp   r   ro   r`   r   r	   Úfloat8_e4m3fnrs   Úmean_scale_fuse_quant_cudaÚscale_fuse_quant_cuda)r/  r{   r  r»   r  rx   rG   r€   r…   r†   rƒ   Ú
padded_lenÚv_transposed_permuttedr$  r%  r  s                   r"   Úxper_channel_fp8r9  <  sÐ  € ð (¨5Ò0Ð0�Q�Q°a€NÝ�)�TÑ"Ô"ð Ø�aŒLˆØ�ŠÑÔÐÐàˆØŒX€FØ˜ÒÐØ$%¤GÑ!ˆˆ4�˜Ø˜r‘k bÑ(¨2Ñ-ˆ
Ý!&¤¨a°°xÀÐ-LÐTUÔT[ÐdjÐ!kÑ!kÔ!kÐÐà	˜%Ò	Ð	Ø$%¤GÑ!ˆˆ6�4˜Ø˜r‘k bÑ(¨2Ñ-ˆ
Ý!&¤¨a°¸4ÀÐ-LÐTUÔT[ÐdjÐ!kÑ!kÔ!kÐå
Ô% aÐ)?ÀÑPÔPÐPØ	ÝŒKÐ.Ô4½EÔ<OÐX^Ð_Ñ_Ô_€EåŒk˜1˜d HÐ-µU´]È6ÐRÑRÔR€GÝ	Œ�a˜˜xÐ(µ´ÀfÐ	MÑ	MÔ	M€Bàð $ÝÔ)Ð*@À%ÈÈWÐV\Ð^gÐiwÑxÔxÐxØ�g˜rÐ!Ð!åÔ$Ð%;¸UÀGÈVÐU^Ð`nÑoÔoÐoØ�g˜tÐ#Ð#r$   c                  óÌ   — t           at          j                             d¦  «        } | �t           | _        t          j                             d¦  «        }|�t           |_        d S d S )Nzsageattention.quantzsageattention.core)r9  r   ÚsysÚmodulesÚget)Ú
sage_quantÚ	sage_cores     r"   Ú%_install_per_channel_fp8_monkey_patchr@  b  sY   € å&€OÝ”—’Ð!6Ñ7Ô7€JØÐÝ%5ˆ
Ô"Ý”—’Ð 4Ñ5Ô5€IØÐÝ$4ˆ	Ô!Ð!Ð!ð Ðr$   )NNNra   )r]   FNFF)r]   rÅ   FNTFN)FNT)r]   Frû   Nr±   TFF)	r]   Frû   NNTFFF)
r]   Frû   Nr¶   TFFr›   F)r]   Frû   Nr¶   TFF)r]   r  T)nÚ__doc__r;  r   Úplatformrž   Úbackendsr   r�   ÚImportErrorÚtorch.nn.functionalrÜ   rÝ   ÚFÚ$sageattention.triton.quant_per_blockr   rä   Ú+sageattention.triton.quant_per_block_varlenrõ   Ú+sageattention.triton.attn_qk_int8_per_blockrÅ   rt   r   r¡   Ú2sageattention.triton.attn_qk_int8_per_block_causalrç   Ú.sageattention.triton.attn_qk_int8_block_varlenr÷   Ú9sageattention.triton.attn_qk_int8_per_block_causal_varlenrö   Ú%sageattention.triton.quant_per_threadr   r
  r&   r   ÚopsÚsageattention_fusedr
   Úsageattention_qattn_sm80r  r   Úsageattention_qattn_sm89r  r   Úsageattention_qattn_sm90r*  Úsageattention.quantrå   r   r	  r   r   Útypingr   r   r   r   r   r   r  Úosr#   Úimportlib.metadatar%   Úsg2_versionÚ
startswithrÀ   r+   r.   rŸ   r7   r<   r0   rE   ÚtuplerO   r   r   rW   rm   rn   r[   rl   rT   rG   rL   ÚstrrR   rU   rY   rÚ   r\   r¤   r™   ÚTensorr§   r©   ÚfloatrÄ   ÚcompilerÚdisabler½   rú   r¾   r¿   r(  rÁ   Ú_sage_per_channel_fp8r3  r9  r@  © r$   r"   ú<module>ra     s-  ððð ð  €
€
€
Ø €€€à„<�8ÒÐ  ¨¬¸Ñ >Ô >ÐÀ5Ä>ÔCU×CbÒCbÑCdÔCdÐØ
ˆ+ÐWÑ
XÔ
XÐXà Ð Ð Ð Ð Ð Ð Ð Ð à XÐ XÐ XÐ XÐ XÐ XØ fÐ fÐ fÐ fÐ fÐ fØ LÐ LÐ LÐ LÐ LÐ LÐ LÐ LÐ LØ MÐ MÐ MÐ MÐ MÐ MØ SÐ SÐ SÐ SÐ SÐ SØ WÐ WÐ WÐ WÐ WÐ WØ aÐ aÐ aÐ aÐ aÐ aà [Ð [Ð [Ð [Ð [Ð [ð+Ø$Ð$Ð$Ð$Ð$Ð$Øˆ7�6Ð7Ñ8Ô8ð /Ø”Ô.ˆøøð+ØŒYÔ*€F€F€FøøøðØ)Ð)Ð)Ð)Ð)Ð)Øˆ7�;Ð ?Ñ@Ô@ð 9Ø”iÔ8ˆØ€L€LøðØ€L€L€LøøøðØ)Ð)Ð)Ð)Ð)Ð)Øˆ7�;Ð TÑUÔUð 9Ø”iÔ8ˆØ€L€LøðØ€L€L€LøøøðØ)Ð)Ð)Ð)Ð)Ð)Øˆ7�;Ð TÑUÔUð 9Ø”iÔ8ˆØ€L€LøðØ€L€L€Løøøà EÐ EÐ EÐ EÐ EÐ EØ CÐ CÐ CÐ CÐ CÐ CØ (Ð (Ð (Ð (Ð (Ð (Ø /Ð /Ð /Ð /Ð /Ð /à =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ð =Ø €€€Ø 	€	€	€	ðð ð ð 'Ð &Ð &Ð &Ð &Ð &Øˆg�oÑ&Ô&€Ø×Ò˜uÑ%Ô%€à Ð Ð Ð Ø 	€	€	€	Ø €€€ð	ð 	ð 	ðð ð ði sð i¨sð ið ið ið ið
 ˆeÐ*Ð*Ñ,Ô,Ñ-Ô-€Ø”j×-Ò-Ñ/Ô/°1Ò4Ð ØÐ ØÐ à(.Ð %Ø*/Ð 'Ø!#Ð ðQ˜eœlð Q¨sð Qð Qð Qð Qð)˜5œ<ð )¨Cð )ð )ð )ð )ð/ U¤\ð /°cð /ð /ð /ð /ð#˜eœlð #ð #ð #ð #ðT¨%¬,ð T¸4ð Tð Tð Tð Tð LQÐ\`ÐotÔo|ð  JOð *ð *ð *ð *ðZð ÀUÄ\ÐTXÑEXð ÐinÔiuÐx{Ñi{ð  Cñ  jCð ð  [^ð ð  knð  quñ  kuð ð ð ð ð6fð f¨U¬\¸CÑ-?À$Ñ-Fð fÐinÔiuÐx|Ñi|ð fð  UXð fð  eið fð fð fð fð
 ØØ $ØØðRCð RCàðRCð ðRCð �uŒoð	RCð
 ðRCð ðRCð ðRCð RCð RCð RCðh „Ôð Ø (ØØ $ØØØ(,ðeð eð
 ðeð ðeð ðeð �uŒoðeð ðeð ðeð ˜œÔ%ðeð ðeð „\ðeð eð eñ ÔðeðN „Ôð Ø $Øðrð rØ„|ðrà„|ðrð „|ðrð ”,ð	rð
 ”,ðrð ðrð ðrð ðrð �uŒoðrð ðrð ðrð „\ðrð rð rñ Ôðrðh „Ôð ØØ%Ø $Ø ØØØðsð sð
 ðsð ðsð ðsð �uŒoðsð ðsð ðsð ðsð ðsð ðsð „\ðsð sð sñ Ôðsðj „Ôð ØØ%Ø $ØØØØØðEð EàðEð ðEð ð	Eð
 �uŒoðEð ðEð ðEð ðEð ðEð ðEð ðEð „\ðEð Eð Eñ ÔðEðP „Ôð ØØ%Ø $Ø%ØØØØØðsð sð
 ðsð ðsð ðsð �uŒoðsð ðsð ðsð ðsð ðsð ðsð ðsð  „\ð!sð sð sñ Ôðsðj „Ôð ØØ%Ø $Ø%ØØØðkð kð
 ðkð ðkð ðkð �uŒoðkð ðkð ðkð ðkð ðkð ðkð „\ðkð kð kñ ÔðkõZ (Ð ð
 ØØð	#$ð #$Ø�U”\ 4Ð'Ô(ð#$àð#$ð ð#$ð ð	#$ð #$ð #$ð #$ðL5ð 5ð 5ð &Ð %Ñ 'Ô 'Ð 'Ð 'Ð 's0   ÂB, Â,B<Ã  C! Ã!C'Ã+ D ÄDÄ D7 Ä7D=