Ë
    S^(h+I  ã            &       óN  — d dl Z d dlZd dlmZmZ d dlZd dlmc mZ	 ddl
mZmZmZmZmZ  ej                   e«      ZdZ e«       rd dlmZmZmZ d dlmZmZ d dlmZ  e«       rd dlmZ ddlmZmZmZ dd	lmZ dd
lm Z er$d e! e jD                  e«      jF                  «      v Z$d„ Z%d„ Z&dejN                  de(ejN                  ejN                  e)f   fd„Z*dejN                  dejN                  dejN                  dejN                  de)f
d„Z+d„ Z,	 d4dejN                  dejN                  dejN                  deejZ                     fd„Z. ed«      Z/ej`                  jc                  dd«      dk(  Z2	 	 	 	 	 	 	 	 	 	 	 	 d5d!ejN                  d"ejN                  d#ejN                  deejN                     de)d$e3d%e4d&eejN                     d'ee4   d(ee)   d)e3d*ee4   d+ee3   d,eejj                     d-eejj                     d.ee)   d/ee)   deejZ                     f$d0„Z6 G d1„ d2ed ¬3«      Z7y)6é    N)ÚOptionalÚ	TypedDicté   )Úis_flash_attn_2_availableÚis_flash_attn_greater_or_equalÚ#is_flash_attn_greater_or_equal_2_10Úis_torch_npu_availableÚlogging)Úindex_first_axisÚ	pad_inputÚunpad_input)Úflash_attn_funcÚflash_attn_varlen_func)Úapply_rotary_emb)Únpu_rotary_mul)Únpu_flash_attn_func)Únpu_flash_attn_varlen_funcÚwindow_sizec                  ó0   — t        «       ryt        «       ryy)z5Determine whether flash-attention can be used or not.TF)r   r	   © ó    úi/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/modeling_flash_attention_utils.pyÚis_flash_attn_availabler   6   s   € ô !Ô"Øô ÔØàr   c                  ó\   — t        «       rt        «        S t        «       rddlm}   | «       S y)zBDetermine whether flash-attention uses top-left or down-right maskr   ©Ú'is_npu_fa2_top_left_aligned_causal_maskF)r   r   r	   Ú integrations.npu_flash_attentionr   r   s    r   Ú!flash_attn_supports_top_left_maskr   D   s+   € ô !Ô"ä6Ó8Ð8Ð8äÔå]á6Ó8Ð8àr   Úattention_maskÚreturnc                 ód  — | j                  dt        j                  ¬«      }t        j                  | j	                  «       d¬«      j	                  «       }|j                  «       j                  «       }t        j                  t        j                  |dt        j                  ¬«      d«      }|||fS )aq  
    Retrieves indexing data required to repad unpadded (ragged) tensors.

    Arguments:
        attention_mask (`torch.Tensor`):
            Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.

    Return:
        indices (`torch.Tensor`):
            The indices of non-masked tokens from the flattened input sequence.
        cu_seqlens (`torch.Tensor`):
            The cumulative sequence lengths, used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
        max_seqlen_in_batch (`int`):
            Maximum sequence length in batch.
    éÿÿÿÿ)ÚdimÚdtypeF)Úas_tupler   )r   r   )
ÚsumÚtorchÚint32ÚnonzeroÚflattenÚmaxÚitemÚFÚpadÚcumsum)r   Úseqlens_in_batchÚindicesÚmax_seqlen_in_batchÚ
cu_seqlenss        r   Ú_get_unpad_datar4   T   sŽ   € ð  &×)Ñ)¨b¼¿¹Ð)ÓDÐÜ�m‰m˜N×2Ñ2Ó4¸uÔE×MÑMÓO€GØ*×.Ñ.Ó0×5Ñ5Ó7ÐÜ—‘”u—|‘|Ð$4¸!Ä5Ç;Á;ÔOÐQWÓX€JàØØðð r   Úquery_layerÚ	key_layerÚvalue_layerÚquery_lengthc                 ó  — t        |«      \  }}}|j                  \  }}	}
}t        |j                  ||	z  |
|«      |«      }t        |j                  ||	z  |
|«      |«      }||	k(  r't        | j                  ||	z  d|«      |«      } |}|}|}nn|dk(  rLd}t	        j
                  |dz   t        j                  | j                  ¬«      }|dd }| j                  d«      } n|dd…| d…f   }t        | |«      ^} }}}}| |||||f||ffS )a¥  
    Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to different batches.

    This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation of the same intermediary
    tensors for query, key, value tensors.

    Arguments:
        query_layer (`torch.Tensor`):
            Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim).
        key_layer (`torch.Tensor`):
            Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
        value_layer (`torch.Tensor`):
            Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
        attention_mask (`torch.Tensor`):
            Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
        query_length (`int`):
            Target length.

    Return:
        query_layer (`torch.Tensor`):
            Query state without padding. Shape: (total_target_length, num_heads, head_dim).
        key_layer (`torch.Tensor`):
            Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
        value_layer (`torch.Tensor`):
            Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
        indices_q (`torch.Tensor`):
            The indices of non-masked tokens from the flattened input target sequence.
        (cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
            The cumulative sequence lengths for the target (query) and source (key, value), used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
        (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
            Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value).
    r"   r   )r$   ÚdeviceN)
r4   Úshaper   Úreshaper'   Úaranger(   r:   Úsqueezer   )r5   r6   r7   r   r8   Ú	indices_kÚcu_seqlens_kÚmax_seqlen_in_batch_kÚ
batch_sizeÚ
kv_seq_lenÚnum_key_value_headsÚhead_dimÚcu_seqlens_qÚmax_seqlen_in_batch_qÚ	indices_qÚ_s                   r   Ú_upad_inputrJ   o   sW  € ôN 6EÀ^Ó5TÑ2€Iˆ|Ð2Ø<E¿O¹OÑ9€J�
Ð/°ä  ×!2Ñ!2°:À
Ñ3JÐL_ÐaiÓ!jÐluÓv€IÜ"Ø×Ñ˜J¨Ñ3Ð5HÈ(ÓSÐU^ó€Kð �zÒ!Ü& {×':Ñ':¸:È
Ñ;RÐTVÐX`Ó'aÐclÓmˆØ#ˆØ 5ÐØ‰	Ø	˜Ò	Ø !ÐÜ—|‘|Ø˜‰N¤%§+¡+°k×6HÑ6Hô
ˆð !  "Ð%ˆ	Ø!×)Ñ)¨!Ó,‰ð (ª¨L¨=©>Ð(9Ñ:ˆÜJUÐVaÐcqÓJrÐGˆ�Y Ð.CÀað 	ØØØØ	�|Ð$Ø	Ð 5Ð6ðð r   c                 óî  — | j                  d| j                  d«      | j                  d«      «      } |j                  «       j                  d|j                  d«      |j                  d«      «      }|j                  «       j                  d|j                  d«      |j                  d«      «      }|j                  «       }t	        j
                  |j                  d«      |j                  t        j                  ¬«      }t	        j                  ||dk(     t	        j                  |j                  «       |j                  t        j                  ¬«      f«      }|j                  «       dz   }| |||||f||ffS )aI  
    This function returns necessary arguments to call `flash_attn_varlen_func`.
    All three query, key, value states will be flattened.
    Cumulative lengths of each examples in the batch will be extracted from position_ids.

    NOTE: ideally cumulative lengths should be prepared at the data collator stage

    Arguments:
        query (`torch.Tensor`):
            Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim).
        key (`torch.Tensor`):
            Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
        value (`torch.Tensor`):
            Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
        position_ids (`torch.Tensor`):
            Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.

    Return:
        query (`torch.Tensor`):
            Query state without padding. Shape: (total_target_length, num_heads, head_dim).
        key (`torch.Tensor`):
            Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
        value (`torch.Tensor`):
            Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
        indices_q (`torch.Tensor`):
            The indices of non-masked tokens from the flattened input target sequence.
        (cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
            The cumulative sequence lengths for the target (query) and source (key, value), used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
        (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
            Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value).
    r"   éþÿÿÿr   )r:   r$   r   )ÚviewÚsizeÚ
contiguousr*   r'   r=   r:   r(   ÚcatÚtensorr+   )ÚqueryÚkeyÚvalueÚposition_idsrH   Úcu_seq_lensÚ
max_lengths          r   Úprepare_fa2_from_position_idsrX   ¸   s0  € ð@ �J‰J�r˜5Ÿ:™: b›>¨5¯:©:°b«>Ó:€EØ
�.‰.Ó
×
Ñ
  C§H¡H¨R£L°#·(±(¸2³,Ó
?€CØ×ÑÓ×#Ñ# B¨¯
©
°2«¸¿
¹
À2»ÓG€EØ×'Ñ'Ó)€LÜ—‘˜\×.Ñ.¨qÓ1¸,×:MÑ:MÔUZ×U`ÑU`Ôa€Iä—)‘)à�l aÑ'Ñ(Ü�L‰L˜×*Ñ*Ó,°\×5HÑ5HÔPU×P[ÑP[Ô\ð	
ó€Kð ×!Ñ!Ó# aÑ'€Jà�3˜˜y¨;¸Ð*DÀzÐS]ÐF^Ð_Ð_r   rR   rS   rT   Útarget_dtypec                 óð   — |€| ||fS | j                   }|t        j                  k(  rLt        j	                  d|› d�«       | j                  |«      } |j                  |«      }|j                  |«      }| ||fS )aG  
    PEFT usually casts the layer norms in float32 for training stability reasons
    therefore the input hidden states gets silently casted in float32. Hence, we need
    cast them back in float16 / bfloat16 just to be sure everything works as expected.
    This might slowdown training & inference so it is recommended to not cast the LayerNorms!

    Args:
        query (`torch.Tensor`):
            Input query states to be passed to Flash Attention API
        key (`torch.Tensor`):
            Input key states to be passed to Flash Attention API
        value (`torch.Tensor`):
            Input value states to be passed to Flash Attention API
        target_dtype (`torch.dtype`, *optional*):
            The dtype to convert the attention tensors to. Conversion can be ignored by
            not providing the target dtype.
    z¾The input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in ú.)r$   r'   Úfloat32ÚloggerÚwarning_onceÚto)rR   rS   rT   rY   Úinput_dtypes        r   Úfa_peft_integration_checkra   ê   s„   € ð. ÐØ�c˜5Ð Ð à—+‘+€KØ”e—m‘mÒ#Ü×Ñðàˆ~˜Qð ô	
ð —‘˜Ó&ˆØ�f‰f�\Ó"ˆØ—‘˜Ó&ˆà�#�uÐÐr   z2.4.1ÚFLASH_ATTENTION_DETERMINISTICÚ0Ú1FÚquery_statesÚ
key_statesÚvalue_statesÚ	is_causalÚdropoutrU   Úsoftmax_scaleÚsliding_windowÚuse_top_left_maskÚsoftcapÚdeterministicÚcu_seq_lens_qÚcu_seq_lens_kÚmax_length_qÚmax_length_kc                 ó,  — |
s|}n	|xr |dk7  }t         xr |	duxr |j                  d   |	kD  }|rd|	|	fini }t        r|€t        }||d<   |�||d<   t	        | |||«      \  } }}|�U| j                  d   }t        | ||||«      \  } }}}}}|\  }}|\  }}t        | ||f|||||||dœ|¤Ž}t        ||||«      }|S |��C|€/|dk7  �r;t        j                  |d¬	«      dk\  j                  «       �s| j                  d«      }|�|€ t        | |||«      \  } }}}}}|\  }}|\  }}n“| j                  d| j                  d
«      | j                  d«      «      } |j                  d|j                  d
«      |j                  d«      «      }|j                  d|j                  d
«      |j                  d«      «      }t        | ||f|||||||dœ|¤Ž}|j                  |d|j                  d
«      |j                  d«      «      }|S t        | |||f||dœ|¤Ž}|S )aÔ  
    Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
    first unpad the input, then computes the attention scores and pad the final attention scores.

    Args:
        query_states (`torch.Tensor`):
            Input query states to be passed to Flash Attention API
        key_states (`torch.Tensor`):
            Input key states to be passed to Flash Attention API
        value_states (`torch.Tensor`):
            Input value states to be passed to Flash Attention API
        attention_mask (`torch.Tensor`, *optional*):
            The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
            position of padding tokens and 1 for the position of non-padding tokens.
        dropout (`float`):
            Attention dropout
        softmax_scale (`float`, *optional*):
            The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
        use_top_left_mask (`bool`, defaults to `False`):
            flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference.
        softcap (`float`, *optional*):
            Softcap for the attention logits, used e.g. in gemma2.
        deterministic (`bool`, *optional*):
            Determines if the deterministic option introduced in flash_attn>=2.4.1 is enabled.
    r   Nr   rn   rm   r   )rF   r@   Úmax_seqlen_qÚmax_seqlen_kÚ	dropout_prj   Úcausalr"   )r#   rL   )rj   rw   )Ú_flash_supports_window_sizer;   Ú	flash_241Údeterministic_gra   rJ   r   r   r'   ÚdiffÚallrN   rX   r<   rM   r   ) re   rf   rg   r   r8   rh   ri   rU   rj   rk   rl   rm   rn   ro   rp   rq   rr   rY   Úkwargsrw   Úuse_sliding_windowsÚflash_kwargsrB   rH   rV   Úmax_seq_lensrF   r@   rG   rA   Úattn_output_unpadÚattn_outputs                                    r   Ú_flash_attention_forwardrƒ     só  € ñ\ Ø‰ð Ò0˜|¨qÑ0ˆô 	$Òk¨¸dÐ(BÒkÀz×GWÑGWÐXYÑGZÐ]kÑGkð ñ I\�M N°NÐ#CÑDÐac€LåØÐ Ü+ˆMØ(5ˆ�_Ñ%àÐØ")ˆ�YÑô .GØ�j ,°ó.Ñ*€L�*˜lð
 Ð!Ø!×'Ñ'¨Ñ*ˆ
ÜWbØ˜* l°NÀLóX
ÑTˆ�j ,°	¸;Èð &1Ñ"ˆ�lØ7CÑ4ÐÐ4ä2ØØØð
ð &Ø%Ø.Ø.ØØ'Øñ
ð ñ
Ðô  Ð 1°9¸jÈ,ÓWˆðX ÐðO 
Ñ	!ØÐ  \°QÓ%6ÄÇ
Á
È<Ð]_Ô@`ÐdeÑ@e×?jÑ?jÕ?là!×&Ñ& qÓ)ˆ
àÐ  MÐ$9ä-¨l¸JÈÐVbÓcñ YˆL˜* l°I¸{ÈLð ,7Ñ(ˆM˜=Ø)5Ñ&ˆL™,ð (×/Ñ/°°L×4EÑ4EÀbÓ4IÈ<×K\ÑK\Ð]_ÓK`ÓaˆLØ#×+Ñ+¨B°
·±ÀÓ0CÀZÇ_Á_ÐUWÓEXÓYˆJØ'×/Ñ/°°L×4EÑ4EÀbÓ4IÈ<×K\ÑK\Ð]_ÓK`ÓaˆLä,ØØØð
ð 'Ø&Ø%Ø%ØØ'Øñ
ð ñ
ˆð "×&Ñ& z°2°{×7GÑ7GÈÓ7KÈ[×M]ÑM]Ð^`ÓMaÓbˆð Ðô	 &Ø˜* l°Gð
ØKXÐagñ
Økwñ
ˆð Ðr   c                   óz   — e Zd ZU dZeej                     ed<   eej                     ed<   ee   ed<   ee   ed<   y)ÚFlashAttentionKwargsað  
    Keyword arguments for Flash Attention with Compile.

    Attributes:
        cu_seq_lens_q (`torch.LongTensor`, *optional*)
            Gets cumulative sequence length for query state.
        cu_seq_lens_k (`torch.LongTensor`, *optional*)
            Gets cumulative sequence length for key state.
        max_length_q (`int`, *optional*):
            Maximum sequence length for query state.
        max_length_k (`int`, *optional*):
            Maximum sequence length for key state.
    ro   rp   rq   rr   N)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r'   Ú
LongTensorÚ__annotations__Úintr   r   r   r…   r…   £  s?   … ñð ˜E×,Ñ,Ñ-Ó-Ø˜E×,Ñ,Ñ-Ó-Ø˜3‘-ÓØ˜3‘-Ôr   r…   )Útotal)N)g        NNNFNNNNNNN)8ÚinspectÚosÚtypingr   r   r'   Útorch.nn.functionalÚnnÚ
functionalr-   Úutilsr   r   r   r	   r
   Ú
get_loggerr†   r]   r   Úflash_attn.bert_paddingr   r   r   Ú
flash_attnr   Úflash_attn.layers.rotaryr   Ú	torch_npur   r   r   r   ÚlistÚ	signatureÚ
parametersrx   r   r   ÚTensorÚtuplerŒ   r4   rJ   rX   r$   ra   ry   ÚenvironÚgetrz   ÚboolÚfloatrŠ   rƒ   r…   r   r   r   ú<module>r£      sÓ  ðó Û 	ß &ã ß Ð ÷õ ð 
ˆ×	Ñ	˜HÓ	%€Ø€ñ ÔßPÑPßBÝ9ñ ÔÝ<çZÑZÝXÝfñ Ø"/±4Ð8I¸×8IÑ8IÈ/Ó8Z×8eÑ8eÓ3fÐ"fÐòòð  E§L¡Lð °U¸5¿<¹<ÈÏÉÐWZÐ;ZÑ5[ó ð6FØ—‘ðFà�|‰|ðFð —‘ðFð —L‘Lð	Fð
 óFòR/`ðl +/ñ	&Ø�<‰<ð&à	�‰ð&ð �<‰<ð&ð ˜5Ÿ;™;Ñ'ó	&ñR +¨7Ó3€	Ø—*‘*—.‘.Ð!@À#ÓFÈ#ÑM€ð Ø+/Ø%)Ø$(Ø#Ø#Ø$(Ø04Ø04Ø"&Ø"&Ø*.ñ%IØ—,‘,ðIà—‘ðIð —,‘,ðIð ˜UŸ\™\Ñ*ð	Ið
 ðIð ðIð ðIð ˜5Ÿ<™<Ñ(ðIð ˜E‘?ðIð ˜S‘MðIð ðIð �e‰_ðIð ˜D‘>ðIð ˜E×,Ñ,Ñ-ðIð ˜E×,Ñ,Ñ-ðIð  ˜3‘-ð!Ið" ˜3‘-ð#Ið$ ˜5Ÿ;™;Ñ'ó%IôX ˜9¨Eö  r   