Ë
    T^(hr  ã                   óÖ  — d Z ddlmZmZmZ ddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZ ddl m!Z! ddl"m#Z#  ejH                  e%«      Z&dZ' G d„ de«      Z( G d„ de«      Z) G d„ de«      Z* G d„ de«      Z+ G d„ de!«      Z, G d„ de
e«      Z- G d„ de«      Z. G d „ d!e«      Z/ G d"„ d#e«      Z0 G d$„ d%e«      Z1g d&¢Z2y)'zPyTorch Qwen3 model.é    )ÚCallableÚOptionalÚTupleNé   )ÚCache)ÚFlashAttentionKwargs)ÚCausalLMOutputWithPast)ÚALL_ATTENTION_FUNCTIONS)ÚUnpack)Ú
LossKwargsÚloggingé   )ÚGemmaMLP)	ÚLlamaAttentionÚLlamaDecoderLayerÚLlamaForCausalLMÚLlamaForQuestionAnsweringÚLlamaForSequenceClassificationÚLlamaForTokenClassificationÚLlamaRMSNormÚapply_rotary_pos_embÚeager_attention_forward)ÚMistralModelé   )ÚQwen3ConfigzQwen/Qwen3-8Bc                   ó   — e Zd Zy)ÚQwen3RMSNormN©Ú__name__Ú
__module__Ú__qualname__© ó    úe/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/qwen3/modular_qwen3.pyr   r   4   ó   „ Ør#   r   c                   ó   — e Zd Zy)ÚQwen3MLPNr   r"   r#   r$   r'   r'   8   r%   r#   r'   c                   ó2  ‡ — e Zd Zdedefˆ fd„Z	 	 ddej                  deej                  ej                  f   de	ej                     de	e
   de	ej                     d	ee   d
eej                  e	ej                     e	eej                        f   fd„Zˆ xZS )ÚQwen3AttentionÚconfigÚ	layer_idxc                 ó�  •— t         ‰| �  ||«       t        | j                  |j                  ¬«      | _        t        | j                  |j                  ¬«      | _        |j                  | _        | j                  j                  r:t        | j                  dd «      �#| j                  | j                  j                  k\  sd | _        y y )N)ÚepsÚsliding_window)ÚsuperÚ__init__r   Úhead_dimÚrms_norm_epsÚq_normÚk_normr.   r*   Úuse_sliding_windowÚgetattrr+   Úmax_window_layers©Úselfr*   r+   Ú	__class__s      €r$   r0   zQwen3Attention.__init__=   s•   ø€ Ü‰Ñ˜ Ô+Ü" 4§=¡=°f×6IÑ6IÔJˆŒÜ" 4§=¡=°f×6IÑ6IÔJˆŒØ$×3Ñ3ˆÔà�K‰K×*Ò*Ü˜Ÿ™Ð%5°tÓ<ÐHØ—‘ $§+¡+×"?Ñ"?Ò?à"&ˆDÕð @r#   Úhidden_statesÚposition_embeddingsÚattention_maskÚpast_key_valueÚcache_positionÚkwargsÚreturnc                 ó  — |j                   d d }g |¢d‘| j                  ‘­}| j                  | j                  |«      j	                  |«      «      j                  dd«      }	| j                  | j                  |«      j	                  |«      «      j                  dd«      }
| j                  |«      j	                  |«      j                  dd«      }|\  }}t        |	|
||«      \  }	}
|�'|||dœ}|j                  |
|| j                  |«      \  }
}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd«      rt         j#                  d	«       nt$        | j                  j                     } || |	|
||f| j&                  sd
n| j(                  | j*                  | j,                  dœ|¤Ž\  }} |j.                  g |¢d‘­Ž j1                  «       }| j3                  |«      }||fS )Néÿÿÿÿr   r   )ÚsinÚcosr?   ÚeagerÚsdpaÚoutput_attentionsFzã`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.g        )ÚdropoutÚscalingr.   )Úshaper1   r3   Úq_projÚviewÚ	transposer4   Úk_projÚv_projr   Úupdater+   r   r*   Ú_attn_implementationÚgetÚloggerÚwarning_oncer
   ÚtrainingÚattention_dropoutrJ   r.   ÚreshapeÚ
contiguousÚo_proj)r9   r;   r<   r=   r>   r?   r@   Úinput_shapeÚhidden_shapeÚquery_statesÚ
key_statesÚvalue_statesrE   rD   Úcache_kwargsÚattention_interfaceÚattn_outputÚattn_weightss                     r$   ÚforwardzQwen3Attention.forwardI   sþ  € ð $×)Ñ)¨#¨2Ð.ˆØ8˜Ð8 bÐ8¨$¯-©-Ñ8ˆà—{‘{ 4§;¡;¨}Ó#=×#BÑ#BÀ<Ó#PÓQ×[Ñ[Ð\]Ð_`ÓaˆØ—[‘[ §¡¨]Ó!;×!@Ñ!@ÀÓ!NÓO×YÑYÐZ[Ð]^Ó_ˆ
Ø—{‘{ =Ó1×6Ñ6°|ÓD×NÑNÈqÐRSÓTˆà&‰ˆˆSÜ#7¸ÀjÐRUÐWZÓ#[Ñ ˆ�jàÐ%à#&¨sÀnÑUˆLØ'5×'<Ñ'<¸ZÈÐW[×WeÑWeÐgsÓ'tÑ$ˆJ˜ä(?ÐØ�;‰;×+Ñ+¨wÒ6Ø�{‰{×/Ñ/°6Ò9¸f¿j¹jÐI\Ð^cÔ>dÜ×#Ñ#ðLõô
 '>¸d¿k¹k×>^Ñ>^Ñ&_Ð#á$7ØØØØØð
%
ð  $Ÿ}š}‘C°$×2HÑ2HØ—L‘LØ×.Ñ.ñ
%
ð ñ
%
Ñ!ˆ�\ð *�k×)Ñ)Ð;¨;Ð;¸Ò;×FÑFÓHˆØ—k‘k +Ó.ˆØ˜LÐ(Ð(r#   )NN)r   r    r!   r   Úintr0   ÚtorchÚTensorr   r   r   Ú
LongTensorr   r   rd   Ú__classcell__©r:   s   @r$   r)   r)   <   sÂ   ø„ ð
'˜{ð 
'°sõ 
'ð" +/Ø59ñ0)à—|‘|ð0)ð # 5§<¡<°·±Ð#=Ñ>ð0)ð ! §¡Ñ.ð	0)ð
 ! ™ð0)ð ! ×!1Ñ!1Ñ2ð0)ð Ð-Ñ.ð0)ð 
ˆu�|‰|˜X e§l¡lÑ3°X¸eÀEÇLÁLÑ>QÑ5RÐRÑ	S÷0)r#   r)   c                   ó(   ‡ — e Zd Zdedefˆ fd„Zˆ xZS )ÚQwen3DecoderLayerr*   r+   c                 óæ   •— t         ‰| �  «        t        ||¬«      | _        t	        |«      | _        |j                  r4|j                  dk7  r$t        j                  d|j                  › d�«       y y y )N)r*   r+   Úflash_attention_2z=Sliding Window Attention is enabled but not implemented for `z)`; unexpected results may be encountered.)
r/   r0   r)   Ú	self_attnr'   Úmlpr.   rR   rT   rU   r8   s      €r$   r0   zQwen3DecoderLayer.__init__}   sp   ø€ Ü‰ÑÔÜ'¨vÀÔKˆŒÜ˜FÓ#ˆŒà×!Ò! f×&AÑ&AÐEXÒ&Xä×ÑØOÐPV×PkÑPkÐOlð m9ð 9õð 'YÐ!r#   )r   r    r!   r   re   r0   ri   rj   s   @r$   rl   rl   |   s   ø„ ð
˜{ð 
°s÷ 
ñ 
r#   rl   c                   ó   — e Zd Zy)Ú
Qwen3ModelNr   r"   r#   r$   rr   rr   Š   r%   r#   rr   c                   ó   — e Zd Zy)ÚKwargsForCausalLMNr   r"   r#   r$   rt   rt   Ž   s   … r#   rt   c                   ó.   ‡ — e Zd Zdee   defˆ fd„Zˆ xZS )ÚQwen3ForCausalLMÚsuper_kwargsrA   c                 ó"   •— t        ‰| �  di |¤ŽS )a  
            labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, Qwen3ForCausalLM

        >>> model = Qwen3ForCausalLM.from_pretrained("Qwen/Qwen3-8B")
        >>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-8B")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```r"   )r/   rd   )r9   rw   r:   s     €r$   rd   zQwen3ForCausalLM.forward’   s   ø€ ôF ‰w‰Ñ. Ñ.Ð.r#   )r   r    r!   r   rt   r	   rd   ri   rj   s   @r$   rv   rv   ‘   s%   ø„ ð#/àÐ0Ñ1ð#/ð 
 ÷#/ñ #/r#   rv   c                   ó   — e Zd Zy)ÚQwen3ForSequenceClassificationNr   r"   r#   r$   rz   rz   ¸   r%   r#   rz   c                   ó   — e Zd Zy)ÚQwen3ForTokenClassificationNr   r"   r#   r$   r|   r|   ¼   r%   r#   r|   c                   ó   — e Zd Zy)ÚQwen3ForQuestionAnsweringNr   r"   r#   r$   r~   r~   À   r%   r#   r~   )rv   r~   rr   ÚQwen3PreTrainedModelrz   r|   )3Ú__doc__Útypingr   r   r   rf   Útorch.utils.checkpointÚcache_utilsr   Úmodeling_flash_attention_utilsr   Úmodeling_outputsr	   Úmodeling_utilsr
   Úprocessing_utilsr   Úutilsr   r   Úgemma.modeling_gemmar   Úllama.modeling_llamar   r   r   r   r   r   r   r   r   Úmistral.modeling_mistralr   Úconfiguration_qwen3r   Ú
get_loggerr   rT   Ú_CHECKPOINT_FOR_DOCr   r'   r)   rl   rr   rt   rv   rz   r|   r~   Ú__all__r"   r#   r$   ú<module>r�      sç   ðñ ç ,Ñ ,ã Û å  Ý BÝ 6Ý 5Ý &÷õ ,÷
÷ 
õ 
õ 4Ý ,ð 
ˆ×	Ñ	˜HÓ	%€à%Ð ô	�<ô 	ô	ˆxô 	ô=)�^ô =)ô@Ð)ô ô	�ô 	ô ?Ð,¨jÔ >ô$/Ð'ô $/ôN	Ð%Cô 	ô	Ð"=ô 	ô	Ð 9ô 	ò�r#   