Ë
    T^(h Ë  ã                   ó  — d dl mZ d dlmZmZmZmZ d dlZd dlmZ ddl	m
Z
 ddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZmZ ddlmZ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+ ddl,m-Z- ddl.m/Z/  e*j`                  e1«      Z2dZ3dZ4 G d„ dejj                  «      Z6 G d„ dejj                  «      Z7d„ Z8dBd„Z9dejt                  de;dejt                  fd„Z<	 dCdejj                  d ejt                  d!ejt                  d"ejt                  d#eejt                     d$e=d%e=fd&„Z> G d'„ d(ejj                  «      Z? G d)„ d*ejj                  «      Z@ G d+„ d,ejj                  «      ZAd-ZB e'd.eB«       G d/„ d0e!«      «       ZCd1ZD e'd.eB«       G d2„ d3eC«      «       ZE G d4„ d5ee%«      ZF G d6„ d7eCe«      ZG e'd8eB«       G d9„ d:eC«      «       ZH e'd;eB«       G d<„ d=eC«      «       ZI e'd>eB«       G d?„ d@eC«      «       ZJg dA¢ZKy)Dé    )Úpartial)ÚCallableÚOptionalÚTupleÚUnionN)Únné   )ÚACT2FN)ÚCacheÚDynamicCacheÚSlidingWindowCacheÚStaticCache)ÚGenerationMixin)ÚAttentionMaskConverter)ÚFlashAttentionKwargs)ÚBaseModelOutputWithPastÚCausalLMOutputWithPastÚQuestionAnsweringModelOutputÚ SequenceClassifierOutputWithPastÚTokenClassifierOutput)ÚROPE_INIT_FUNCTIONSÚdynamic_rope_update)ÚALL_ATTENTION_FUNCTIONSÚPreTrainedModel)ÚUnpack)Ú
LossKwargsÚadd_code_sample_docstringsÚadd_start_docstringsÚ%add_start_docstrings_to_model_forwardÚcan_return_tupleÚloggingÚreplace_return_docstrings)Údeprecate_kwargé   )ÚQwen3ConfigzQwen/Qwen3-8Br%   c                   ó,   ‡ — e Zd Zdˆ fd„	Zd„ Zd„ Zˆ xZS )ÚQwen3RMSNormc                 óŠ   •— t         ‰| �  «        t        j                  t	        j
                  |«      «      | _        || _        y)z;
        Qwen3RMSNorm is equivalent to T5LayerNorm
        N)ÚsuperÚ__init__r   Ú	ParameterÚtorchÚonesÚweightÚvariance_epsilon)ÚselfÚhidden_sizeÚepsÚ	__class__s      €úf/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/qwen3/modeling_qwen3.pyr*   zQwen3RMSNorm.__init__?   s1   ø€ ô 	‰ÑÔÜ—l‘l¤5§:¡:¨kÓ#:Ó;ˆŒØ #ˆÕó    c                 ó"  — |j                   }|j                  t        j                  «      }|j	                  d«      j                  dd¬«      }|t        j                  || j                  z   «      z  }| j                  |j                  |«      z  S )Né   éÿÿÿÿT)Úkeepdim)	ÚdtypeÚtor,   Úfloat32ÚpowÚmeanÚrsqrtr/   r.   )r0   Úhidden_statesÚinput_dtypeÚvariances       r4   ÚforwardzQwen3RMSNorm.forwardG   sy   € Ø#×)Ñ)ˆØ%×(Ñ(¬¯©Ó7ˆØ ×$Ñ$ QÓ'×,Ñ,¨R¸Ð,Ó>ˆØ%¬¯©°H¸t×?TÑ?TÑ4TÓ(UÑUˆØ�{‰{˜]×-Ñ-¨kÓ:Ñ:Ð:r5   c                 ó^   — t        | j                  j                  «      › d| j                  › �S )Nz, eps=)Útupler.   Úshaper/   ©r0   s    r4   Ú
extra_reprzQwen3RMSNorm.extra_reprN   s*   € Ü˜Ÿ™×)Ñ)Ó*Ð+¨6°$×2GÑ2GÐ1HÐIÐIr5   )g�íµ ÷Æ°>)Ú__name__Ú
__module__Ú__qualname__r*   rC   rH   Ú__classcell__©r3   s   @r4   r'   r'   >   s   ø„ õ$ò;öJr5   r'   c                   ó$   ‡ — e Zd Zˆ fd„Zd„ Zˆ xZS )ÚQwen3MLPc                 óÊ  •— t         ‰| �  «        || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d¬«      | _        t        j                  | j                  | j                  d¬«      | _        t        j                  | j                  | j                  d¬«      | _	        t        |j                     | _        y ©NF©Úbias)r)   r*   Úconfigr1   Úintermediate_sizer   ÚLinearÚ	gate_projÚup_projÚ	down_projr
   Ú
hidden_actÚact_fn©r0   rT   r3   s     €r4   r*   zQwen3MLP.__init__S   s¦   ø€ Ü‰ÑÔØˆŒØ!×-Ñ-ˆÔØ!'×!9Ñ!9ˆÔÜŸ™ 4×#3Ñ#3°T×5KÑ5KÐRWÔXˆŒÜ—y‘y ×!1Ñ!1°4×3IÑ3IÐPUÔVˆŒÜŸ™ 4×#9Ñ#9¸4×;KÑ;KÐRWÔXˆŒÜ˜V×.Ñ.Ñ/ˆ�r5   c                 óˆ   — | j                  | j                  | j                  |«      «      | j                  |«      z  «      }|S ©N)rY   r[   rW   rX   )r0   ÚxrY   s      r4   rC   zQwen3MLP.forward]   s6   € Ø—N‘N 4§;¡;¨t¯~©~¸aÓ/@Ó#AÀDÇLÁLÐQRÃOÑ#SÓTˆ	ØÐr5   )rI   rJ   rK   r*   rC   rL   rM   s   @r4   rO   rO   R   s   ø„ ô0ör5   rO   c                 óš   — | dd| j                   d   dz  …f   }| d| j                   d   dz  d…f   }t        j                  | |fd¬«      S )z*Rotates half the hidden dims of the input..Nr8   r7   ©Údim)rF   r,   Úcat)r_   Úx1Úx2s      r4   Úrotate_halfrf   b   sZ   € à	
ˆ3Ð"�!—'‘'˜"‘+ Ñ"Ð"Ð"Ñ	#€BØ	
ˆ3�—‘˜‘˜qÑ Ñ"Ð"Ñ	#€BÜ�9‰9�r�c˜2�Y BÔ'Ð'r5   c                 óž   — |j                  |«      }|j                  |«      }| |z  t        | «      |z  z   }||z  t        |«      |z  z   }||fS )aÛ  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )Ú	unsqueezerf   )ÚqÚkÚcosÚsinÚposition_idsÚunsqueeze_dimÚq_embedÚk_embeds           r4   Úapply_rotary_pos_embrq   i   sY   € ð( �-‰-˜Ó
&€CØ
�-‰-˜Ó
&€CØ�3‰wœ; q›>¨CÑ/Ñ0€GØ�3‰wœ; q›>¨CÑ/Ñ0€GØ�GÐÐr5   r@   Ún_repÚreturnc                 óª   — | j                   \  }}}}|dk(  r| S | dd…dd…ddd…dd…f   j                  |||||«      } | j                  |||z  ||«      S )zÔ
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r$   N)rF   ÚexpandÚreshape)r@   rr   ÚbatchÚnum_key_value_headsÚslenÚhead_dims         r4   Ú	repeat_kvr{   „   so   € ð
 2?×1DÑ1DÑ.€EÐ  hØ�‚zØÐØ!¢!¢Q¨ªa²Ð"2Ñ3×:Ñ:¸5ÐBUÐW\Ð^bÐdlÓm€MØ× Ñ  Ð(;¸eÑ(CÀTÈ8ÓTÐTr5   ÚmoduleÚqueryÚkeyÚvalueÚattention_maskÚscalingÚdropoutc                 óT  — t        || j                  «      }t        || j                  «      }	t        j                  ||j	                  dd«      «      |z  }
|�#|d d …d d …d d …d |j
                  d   …f   }|
|z   }
t        j                  j                  |
dt        j                  ¬«      j                  |j                  «      }
t        j                  j                  |
|| j                  ¬«      }
t        j                  |
|	«      }|j	                  dd«      j                  «       }||
fS )Nr7   r	   éþÿÿÿr8   )rb   r:   )ÚpÚtrainingr$   )r{   Únum_key_value_groupsr,   ÚmatmulÚ	transposerF   r   Ú
functionalÚsoftmaxr<   r;   r:   r‚   r†   Ú
contiguous)r|   r}   r~   r   r€   r�   r‚   ÚkwargsÚ
key_statesÚvalue_statesÚattn_weightsÚcausal_maskÚattn_outputs                r4   Úeager_attention_forwardr“   �   s  € ô ˜3 × ;Ñ ;Ó<€JÜ˜U F×$?Ñ$?Ó@€Lä—<‘<  z×';Ñ';¸A¸qÓ'AÓBÀWÑL€LØÐ!Ø$¢Qªª1Ð.D°
×0@Ñ0@ÀÑ0DÐ.DÐ%DÑEˆØ# kÑ1ˆä—=‘=×(Ñ(¨¸2ÄUÇ]Á]Ð(ÓS×VÑVÐW\×WbÑWbÓc€LÜ—=‘=×(Ñ(¨¸È6Ï?É?Ð(Ó[€LÜ—,‘,˜|¨\Ó:€KØ×'Ñ'¨¨1Ó-×8Ñ8Ó:€Kà˜Ð$Ð$r5   c                   ó6  ‡ — e Zd 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 )ÚQwen3Attentionz=Multi-headed attention from 'Attention Is All You Need' paperrT   Ú	layer_idxc                 óÎ  •— t         ‰| �  «        || _        || _        t	        |d|j
                  |j                  z  «      | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                  ¬«      | _        t        j                  |j
                  |j                  | j                  z  |j                  ¬«      | _        t        j                  |j
                  |j                  | j                  z  |j                  ¬«      | _        t        j                  |j                  | j                  z  |j
                  |j                  ¬«      | _        t)        | j                  |j*                  ¬«      | _        t)        | j                  |j*                  ¬«      | _        |j0                  | _        | j                  j2                  r:t	        | j                  dd «      �#| j                  | j                  j4                  k\  sd | _        y y )Nrz   g      à¿TrR   ©r2   Úsliding_window)r)   r*   rT   r–   Úgetattrr1   Únum_attention_headsrz   rx   r‡   r�   Úattention_dropoutÚ	is_causalr   rV   Úattention_biasÚq_projÚk_projÚv_projÚo_projr'   Úrms_norm_epsÚq_normÚk_normr™   Úuse_sliding_windowÚmax_window_layers©r0   rT   r–   r3   s      €r4   r*   zQwen3Attention.__init__­   sÒ  ø€ Ü‰ÑÔØˆŒØ"ˆŒÜ ¨
°F×4FÑ4FÈ&×JdÑJdÑ4dÓeˆŒØ$*×$>Ñ$>À&×B\ÑB\Ñ$\ˆÔ!Ø—}‘} dÑ*ˆŒØ!'×!9Ñ!9ˆÔØˆŒä—i‘iØ×Ñ × :Ñ :¸T¿]¹]Ñ JÐQW×QfÑQfô
ˆŒô —i‘iØ×Ñ × :Ñ :¸T¿]¹]Ñ JÐQW×QfÑQfô
ˆŒô —i‘iØ×Ñ × :Ñ :¸T¿]¹]Ñ JÐQW×QfÑQfô
ˆŒô —i‘iØ×&Ñ&¨¯©Ñ6¸×8JÑ8JÐQW×QfÑQfô
ˆŒô # 4§=¡=°f×6IÑ6IÔJˆŒÜ" 4§=¡=°f×6IÑ6IÔJˆŒØ$×3Ñ3ˆÔà�K‰K×*Ò*Ü˜Ÿ™Ð%5°tÓ<ÐHØ—‘ $§+¡+×"?Ñ"?Ò?à"&ˆDÕð @r5   r@   Úposition_embeddingsr€   Úpast_key_valueÚcache_positionr�   rs   c                 ó  — |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 )Nr8   r$   r7   )rl   rk   r«   Ú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.ç        )r‚   r�   r™   )rF   rz   r¤   rŸ   Úviewr‰   r¥   r    r¡   rq   Úupdater–   r“   rT   Ú_attn_implementationÚgetÚloggerÚwarning_oncer   r†   rœ   r�   r™   rv   rŒ   r¢   )r0   r@   r©   r€   rª   r«   r�   Úinput_shapeÚhidden_shapeÚquery_statesrŽ   r�   rk   rl   Úcache_kwargsÚattention_interfacer’   r�   s                     r4   rC   zQwen3Attention.forwardÍ   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Ð(Ð(r5   )NN)rI   rJ   rK   Ú__doc__r%   Úintr*   r,   ÚTensorr   r   r   Ú
LongTensorr   r   rC   rL   rM   s   @r4   r•   r•   ª   sÆ   ø„ ÙGð'˜{ð '°sõ 'ðJ +/Ø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)r5   r•   c                   óp  ‡ — e Zd Zdedefˆ fd„Z	 	 	 	 	 	 	 ddej                  deej                     deej                     dee
   dee   d	ee   d
eej                     deeej                  ej                  f      dee   deej                  eeej                  ej                  f      f   fd„Zˆ xZS )ÚQwen3DecoderLayerrT   r–   c                 ó   •— t         ‰| �  «        |j                  | _        t        ||¬«      | _        t        |«      | _        t        |j                  |j                  ¬«      | _	        t        |j                  |j                  ¬«      | _
        |j                  r4|j                  dk7  r$t        j                  d|j                  › d�«       y y y )N)rT   r–   r˜   Úflash_attention_2z=Sliding Window Attention is enabled but not implemented for `z)`; unexpected results may be encountered.)r)   r*   r1   r•   Ú	self_attnrO   Úmlpr'   r£   Úinput_layernormÚpost_attention_layernormr™   r³   rµ   r¶   r¨   s      €r4   r*   zQwen3DecoderLayer.__init__  s´   ø€ Ü‰ÑÔØ!×-Ñ-ˆÔÜ'¨vÀÔKˆŒÜ˜FÓ#ˆŒÜ+¨F×,>Ñ,>ÀF×DWÑDWÔXˆÔÜ(4°V×5GÑ5GÈV×M`ÑM`Ô(aˆÔ%à×!Ò! f×&AÑ&AÐEXÒ&Xä×ÑØOÐPV×PkÑPkÐOlð m9ð 9õð 'YÐ!r5   r@   r€   rm   rª   r¯   Ú	use_cacher«   r©   r�   rs   c	                 óÚ   — |}
| j                  |«      } | j                  d||||||||dœ|	¤Ž\  }}|
|z   }|}
| j                  |«      }| j                  |«      }|
|z   }|f}|r||fz  }|S )N)r@   r€   rm   rª   r¯   rÈ   r«   r©   © )rÆ   rÄ   rÇ   rÅ   )r0   r@   r€   rm   rª   r¯   rÈ   r«   r©   r�   ÚresidualÚself_attn_weightsÚoutputss                r4   rC   zQwen3DecoderLayer.forward  s±   € ð !ˆà×,Ñ,¨]Ó;ˆð ,:¨4¯>©>ð 
,
Ø'Ø)Ø%Ø)Ø/ØØ)Ø 3ñ
,
ð ñ
,
Ñ(ˆÐ(ð ! =Ñ0ˆð !ˆØ×5Ñ5°mÓDˆØŸ™ Ó/ˆØ  =Ñ0ˆà Ð"ˆÙØÐ)Ð+Ñ+ˆGàˆr5   )NNNFFNN)rI   rJ   rK   r%   r½   r*   r,   r¾   r   r¿   r   Úboolr   r   r   ÚFloatTensorrC   rL   rM   s   @r4   rÁ   rÁ      s  ø„ ð˜{ð °sõ ð$ 26Ø37Ø*.Ø,1Ø$)Ø59ØKOñ(à—|‘|ð(ð ! §¡Ñ.ð(ð ˜u×/Ñ/Ñ0ð	(ð
 ! ™ð(ð $ D™>ð(ð ˜D‘>ð(ð ! ×!1Ñ!1Ñ2ð(ð & e¨E¯L©L¸%¿,¹,Ð,FÑ&GÑHð(ð Ð-Ñ.ð(ð 
ˆu× Ñ  (¨5°×1BÑ1BÀE×DUÑDUÐ1UÑ+VÑ"WÐWÑ	X÷(r5   rÁ   c                   ó^   ‡ — e Zd Zddefˆ fd„Z ej                  «       ed„ «       «       Zˆ xZ	S )ÚQwen3RotaryEmbeddingrT   c                 óê  •— t         ‰| �  «        t        |d«      rG|j                  �;|j                  j	                  d|j                  j	                  d«      «      | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |«      \  }| _        | j                  d|d¬«       | j                  | _        y )NÚrope_scalingÚ	rope_typeÚtypeÚdefaultÚinv_freqF)Ú
persistent)r)   r*   ÚhasattrrÓ   r´   rÔ   Úmax_position_embeddingsÚmax_seq_len_cachedÚoriginal_max_seq_lenrT   r   Úrope_init_fnÚattention_scalingÚregister_bufferr×   Úoriginal_inv_freq)r0   rT   Údevicer×   r3   s       €r4   r*   zQwen3RotaryEmbedding.__init__<  sÉ   ø€ Ü‰ÑÔä�6˜>Ô*¨v×/BÑ/BÐ/NØ#×0Ñ0×4Ñ4°[À&×BUÑBU×BYÑBYÐZ`ÓBaÓbˆD�Nà&ˆDŒNØ"(×"@Ñ"@ˆÔØ$*×$BÑ$BˆÔ!àˆŒÜ/°·±Ñ?ˆÔà+/×+<Ñ+<¸T¿[¹[È&Ó+QÑ(ˆ�$Ô(Ø×Ñ˜Z¨¸eÐÔDØ!%§¡ˆÕr5   c                 ób  — | j                   d d d …d f   j                  «       j                  |j                  d   dd«      j	                  |j
                  «      }|d d …d d d …f   j                  «       }t        |j
                  j                  t        «      r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d¬«      5  |j                  «       |j                  «       z  j                  dd«      }t        j                  ||fd¬	«      }|j                  «       | j                  z  }|j                  «       | j                  z  }	d d d «       j	                  |j                   ¬
«      	j	                  |j                   ¬
«      fS # 1 sw Y   ŒAxY w)Nr   r8   r$   ÚmpsÚcpuF)Údevice_typeÚenabledr7   ra   )r:   )r×   Úfloatru   rF   r;   rá   Ú
isinstancerÕ   Ústrr,   Úautocastr‰   rc   rk   rÞ   rl   r:   )
r0   r_   rm   Úinv_freq_expandedÚposition_ids_expandedrå   ÚfreqsÚembrk   rl   s
             r4   rC   zQwen3RotaryEmbedding.forwardM  sV  € ð !ŸM™M¨$²°4¨-Ñ8×>Ñ>Ó@×GÑGÈ×HZÑHZÐ[\ÑH]Ð_aÐcdÓe×hÑhÐij×iqÑiqÓrÐØ ,ªQ°²a¨ZÑ 8× >Ñ >Ó @Ðä'1°!·(±(·-±-ÄÔ'EÈ!Ï(É(Ï-É-Ð[`ÒJ`�a—h‘h—m’mÐfkˆÜ�^‰^¨¸UÔCñ 	5Ø&×,Ñ,Ó.Ð1F×1LÑ1LÓ1NÑN×YÑYÐZ[Ð]^Ó_ˆEÜ—)‘)˜U E˜N°Ô3ˆCØ—'‘'“)˜d×4Ñ4Ñ4ˆCØ—'‘'“)˜d×4Ñ4Ñ4ˆC÷		5ð �v‰v˜AŸG™GˆvÓ$ c§f¡f°1·7±7 fÓ&;Ð;Ð;÷	5ð 	5ús   Ã BF%Æ%F.r^   )
rI   rJ   rK   r%   r*   r,   Úno_gradr   rC   rL   rM   s   @r4   rÑ   rÑ   ;  s3   ø„ ñ/˜{õ /ð" €U‡]�]ƒ_Øñ<ó ó ô<r5   rÑ   aJ  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`Qwen3Config`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zSThe bare Qwen3 Model outputting raw hidden-states without any specific head on top.c                   óF   — e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZdZd„ Zy)ÚQwen3PreTrainedModelÚmodelTrÁ   Úpast_key_valuesc                 ó  — | j                   j                  }t        |t        j                  «      rY|j
                  j                  j                  d|¬«       |j                  �%|j                  j                  j                  «        y y t        |t        j                  «      rf|j
                  j                  j                  d|¬«       |j                  �2|j
                  j                  |j                     j                  «        y y y )Nr°   )r>   Ústd)rT   Úinitializer_rangerè   r   rV   r.   ÚdataÚnormal_rS   Úzero_Ú	EmbeddingÚpadding_idx)r0   r|   rõ   s      r4   Ú_init_weightsz"Qwen3PreTrainedModel._init_weights€  sÃ   € Ø�k‰k×+Ñ+ˆÜ�fœbŸi™iÔ(Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø�{‰{Ð&Ø—‘× Ñ ×&Ñ&Õ(ð 'ä˜¤§¡Ô-Ø�M‰M×Ñ×&Ñ&¨C°SÐ&Ô9Ø×!Ñ!Ð-Ø—‘×"Ñ" 6×#5Ñ#5Ñ6×<Ñ<Õ>ð .ð .r5   N)rI   rJ   rK   r%   Úconfig_classÚbase_model_prefixÚsupports_gradient_checkpointingÚ_no_split_modulesÚ_skip_keys_device_placementÚ_supports_flash_attn_2Ú_supports_sdpaÚ_supports_flex_attnÚ_supports_cache_classÚ_supports_quantized_cacheÚ_supports_static_cacheÚ_supports_attention_backendrü   rÊ   r5   r4   rñ   rñ   n  sU   „ ð
 €LØÐØ&*Ð#Ø,Ð-ÐØ#4Ð"5ÐØ!ÐØ€NØÐØ ÐØ $ÐØ!ÐØ"&Ðó	?r5   rñ   a$  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                   ó  ‡ — e Zd ZdZdefˆ fd„Zd„ Zd„ Ze e	e
«      	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     d	ee   d
eej                      dee   dee   dee   deej                     dee   defd„«       «       Z	 ddej                  dej                  dej                  d	edef
d„Zedej                  dededej2                  dej4                  dej                  deded	efd„«       Zˆ xZS )Ú
Qwen3Modelz›
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`Qwen3DecoderLayer`]

    Args:
        config: Qwen3Config
    rT   c           	      ó  •— t         ‰| �  |«       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                  «      | _        t        j                  t        |j                  «      D �cg c]  }t        ||«      ‘Œ c}«      | _        t        |j                  |j                  ¬«      | _        t#        |¬«      | _        d| _        | j)                  «        y c c}w )Nr˜   )rT   F)r)   r*   Úpad_token_idrû   Ú
vocab_sizer   rú   r1   Úembed_tokensÚ
ModuleListÚrangeÚnum_hidden_layersrÁ   Úlayersr'   r£   ÚnormrÑ   Ú
rotary_embÚgradient_checkpointingÚ	post_initr¨   s      €r4   r*   zQwen3Model.__init__Û  sÆ   ø€ Ü‰Ñ˜Ô Ø!×.Ñ.ˆÔØ ×+Ñ+ˆŒäŸL™L¨×):Ñ):¸F×<NÑ<NÐPT×P`ÑP`ÓaˆÔÜ—m‘mÜCHÈ×IaÑIaÓCbÖc°iÔ˜v yÕ1Òcó
ˆŒô ! ×!3Ñ!3¸×9LÑ9LÔMˆŒ	Ü.°fÔ=ˆŒØ&+ˆÔ#ð 	�‰Õùò ds   ÂDc                 ó   — | j                   S r^   ©r  rG   s    r4   Úget_input_embeddingszQwen3Model.get_input_embeddingsë  s   € Ø× Ñ Ð r5   c                 ó   — || _         y r^   r  ©r0   r   s     r4   Úset_input_embeddingszQwen3Model.set_input_embeddingsî  s
   € Ø!ˆÕr5   Ú	input_idsr€   rm   ró   Úinputs_embedsrÈ   r¯   Úoutput_hidden_statesr«   Úflash_attn_kwargsrs   c
                 ó^  — |�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|d u |d uz  rt	        d«      ‚| j
                  r%| j                  r|rt        j                  d«       d}t        |t        d «      t        f«      st	        d«      ‚|€| j                  |«      }|r|€
t        «       }|	€F|�|j                  «       nd}t        j                   |||j"                  d   z   |j$                  ¬«      }	|€|	j'                  d«      }| j)                  |||	||«      }|}| j+                  ||«      }|rdnd }|rdnd }| j,                  d | j                   j.                   D ]r  }|r||fz  }| j
                  r:| j                  r.| j1                  t3        |j4                  fi |
¤Ž|||||||	|«	      }n ||f||||||	|d	œ|
¤Ž}|d   }|sŒj||d   fz  }Œt | j7                  |«      }|r||fz  }t9        ||r|nd ||¬
«      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r$   ©rá   rÊ   )r€   rm   rª   r¯   rÈ   r«   r©   )Úlast_hidden_stateró   r@   Ú
attentions)rT   r¯   r  rÈ   Ú
ValueErrorr  r†   rµ   r¶   rè   rÕ   r   r  r   Úget_seq_lengthr,   ÚarangerF   rá   rh   Ú_update_causal_maskr  r  r  Ú_gradient_checkpointing_funcr   Ú__call__r  r   )r0   r  r€   rm   ró   r  rÈ   r¯   r  r«   r   Úpast_seen_tokensr‘   r@   r©   Úall_hidden_statesÚall_self_attnsÚdecoder_layerÚlayer_outputss                      r4   rC   zQwen3Model.forwardñ  s£  € ð 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð "+Ð!6‘I¸D¿K¹K×<QÑ<Qˆ	à˜Ð -°tÐ";Ò<ÜÐYÓZÐZà×&Ò&¨4¯=ª=¹YÜ×ÑØjôð ˆIô ˜/¬D°«J¼Ð+>Ô?ÜÐaÓbÐbàÐ Ø ×-Ñ-¨iÓ8ˆMá˜Ð0Ü*›nˆOàÐ!ØCRÐC^˜×=Ñ=Ô?ÐdeÐÜ"Ÿ\™\Ø Ð"2°]×5HÑ5HÈÑ5KÑ"KÐTa×ThÑThôˆNð ÐØ)×3Ñ3°AÓ6ˆLà×.Ñ.Ø˜M¨>¸?ÐL]ó
ˆð &ˆð #Ÿo™o¨m¸\ÓJÐñ #7™B¸DÐÙ0™°dˆà!Ÿ[™[Ð)H¨4¯;©;×+HÑ+HÐIò  	6ˆMÙ#Ø! mÐ%5Ñ5Ð!à×*Ò*¨t¯}ª}Ø $× AÑ AÜ˜M×2Ñ2ÑHÐ6GÑHØ!ØØ Ø#Ø%ØØ"Ø'ó
!‘ñ !.Ø!ð
!à#.Ø!-Ø#2Ø&7Ø'Ø#1Ø(;ñ
!ð (ñ
!�ð *¨!Ñ,ˆMâ Ø =°Ñ#3Ð"5Ñ5‘ðA 	6ðD Ÿ	™	 -Ó0ˆñ  Ø -Ð!1Ñ1Ðä&Ø+Ù/8™O¸dØ+Ø%ô	
ð 	
r5   Úinput_tensorc                 ó  — | j                   j                  dk(  rS|�H|�F|d d …df   j                  «       j                  «       |j	                  «       d   k7  }|rt        d«      ‚|�d|v r|S y |�|j                  «       nd}t        |t        «      }t        |t        «      }	| j                   j                  dk(  r?|s=|	s;|s9t        j                  |||| j                   j                  | j                  ¬«      ry |j                  |j                  }}
t!        j"                  |
«      j$                  }|j&                  d   }|	s|r|j)                  «       }n1t        |t         j*                  «      r|j&                  d   n||z   dz   }| j-                  ||||
|||j&                  d   | j                   |¬	«	      }| j                   j                  dk(  r2|�0|j                  j.                  d
v r|st        j0                  ||«      }|S )NrÃ   r8   r   zêYou are attempting to perform batched generation with padding_side='right' this may lead to unexpected behaviour for Flash Attention version of Qwen3. Make sure to  call `tokenizer.padding_side  = 'left'` before tokenizing the input. r°   r®   )r  Úpast_key_values_lengthr™   Úis_trainingr$   )Úsequence_lengthÚtarget_lengthr:   rá   r«   Ú
batch_sizerT   ró   )ÚcudaÚxpu)rT   r³   ÚsumÚitemÚsizer%  r&  rè   r   r   r   Ú_ignore_causal_mask_sdpar™   r†   r:   rá   r,   ÚfinfoÚminrF   Úget_max_cache_shaper¾   Ú5_prepare_4d_causal_attention_mask_with_cache_positionrÕ   Ú_unmask_unattended)r0   r€   r0  r«   ró   r¯   Úis_padding_rightr+  Úusing_static_cacheÚusing_sliding_window_cacher:   rá   Ú	min_dtyper4  r5  r‘   s                   r4   r(  zQwen3Model._update_causal_mask^  s  € ð �;‰;×+Ñ+Ð/BÒBØÐ)¨oÐ.IØ#1²!°R°%Ñ#8×#<Ñ#<Ó#>×#CÑ#CÓ#EÈ×IZÑIZÓI\Ð]^ÑI_Ñ#_Ð Ù#Ü$ðaóð ð
 Ð)¨c°^Ñ.CØ%Ð%Øð
 @OÐ?Z˜?×9Ñ9Ô;Ð`aÐÜ'¨¼ÓEÐÜ%/°ÔASÓ%TÐ"ð �K‰K×,Ñ,°Ò6Ù'Ñ+EÙ%ä%×>Ñ>ØØ*Ø'7Ø#Ÿ{™{×9Ñ9Ø ŸM™Mõð à$×*Ñ*¨L×,?Ñ,?ˆvˆÜ—K‘K Ó&×*Ñ*ˆ	Ø&×,Ñ,¨QÑ/ˆá%Ñ);Ø+×?Ñ?ÓA‰Mô
 ˜n¬e¯l©lÔ;ð ×$Ñ$ RÒ(à%¨Ñ7¸!Ñ;ð ð ×PÑPØØ+Ø'ØØØ)Ø#×)Ñ)¨!Ñ,Ø—;‘;Ø+ð Qó 

ˆð �K‰K×,Ñ,°Ò6ØÐ*Ø×%Ñ%×*Ñ*¨oÑ=Ù%ô
 1×CÑCÀKÐQZÓ[ˆKàÐr5   r4  r5  r:   rá   r6  c	                 óp  — | �| j                  «       dk(  r| }	|	S t        j                  |«      j                  }
t        j                  ||f|
||¬«      }	t        j
                  ||¬«      |j                  dd«      kD  }|j                  �]t        |t        «      r||kD  rHt        j
                  ||¬«      |j                  dd«      |j                  z
  k  }|j                  |«       |	|z  }	|	dddd…dd…f   j                  |ddd«      }	| �©|	j                  «       }	| j                  d   |kD  r| dd…d|…f   } | j                  d   }|	dd…dd…dd…d|…f   | dd…dddd…f   j                  |	j                  «      z   }|dk(  }|	dd…dd…dd…d|…f   j!                  ||
«      |	dd…dd…dd…d|…f<   |	S )aT  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
            config (`Qwen3Config`):
                The model's configuration class
            past_key_values (`Cache`):
                The cache class that is being used currently to generate
        Né   )Ú
fill_valuer:   rá   r"  r8   r$   r   )rb   r,   r=  r>  Úfullr'  rv   r™   rè   r   Úbitwise_or_ru   ÚclonerF   r;   rá   Úmasked_fill)r€   r4  r5  r:   rá   r«   r6  rT   ró   r‘   rE  Údiagonal_attend_maskÚsliding_attend_maskÚmask_lengthÚpadding_masks                  r4   r@  z@Qwen3Model._prepare_4d_causal_attention_mask_with_cache_position±  sò  € ðH Ð%¨.×*<Ñ*<Ó*>À!Ò*Cà(ˆKð: Ðô7 Ÿ™ EÓ*×.Ñ.ˆIÜŸ*™*Ø  -Ð0¸YÈeÐ\bôˆKô $)§<¡<°ÀfÔ#MÐP^×PfÑPfÐgiÐklÓPmÑ#mÐ Ø×$Ñ$Ð0ô " /Ô3EÔFÈ/Ð\iÒJiÜ*/¯,©,°}ÈVÔ*TØ&×.Ñ.¨r°1Ó5¸×8MÑ8MÑMñ+Ð'ð )×4Ñ4Ð5HÔIØÐ/Ñ/ˆKØ% d¨D²!²QÐ&6Ñ7×>Ñ>¸zÈ1ÈbÐRTÓUˆKØÐ)Ø)×/Ñ/Ó1�Ø!×'Ñ'¨Ñ+¨mÒ;Ø%3²A°~¸°~Ð4EÑ%F�NØ,×2Ñ2°2Ñ6�Ø*ª1ªa²°L°[°LÐ+@ÑAÀNÒSTÐVZÐ\`ÒbcÐScÑDd×DgÑDgØ×&Ñ&óEñ  �ð  ,¨qÑ0�Ø5@ÂÂAÂqÈ,È;È,ÐAVÑ5W×5cÑ5cØ  )ó6�šAšq¢! \ k \Ð1Ñ2ð Ðr5   ©	NNNNNNNNN)F)rI   rJ   rK   r¼   r%   r*   r  r  r    r   ÚQWEN3_INPUTS_DOCSTRINGr   r,   r¿   r¾   r   rÏ   rÎ   r   r   r   rC   r(  Ústaticmethodr½   r:   rá   r@  rL   rM   s   @r4   r
  r
  Ï  sõ  ø„ ñ
ð˜{õ ò !ò"ð Ù*Ð+AÓBð 15Ø15Ø37Ø+/Ø59Ø$(Ø,0Ø/3Ø59ñi
à˜E×,Ñ,Ñ-ði
ð ! §¡Ñ.ði
ð ˜u×/Ñ/Ñ0ð	i
ð
 " %™ði
ð   × 1Ñ 1Ñ2ði
ð ˜D‘>ði
ð $ D™>ði
ð ' t™nði
ð ! ×!1Ñ!1Ñ2ði
ð $Ð$8Ñ9ði
ð 
!òi
ó Có ði
ðb #(ñQàŸ™ðQð —l‘lðQð Ÿ™ð	Qð
 ðQð  óQðf ðBØŸ™ðBàðBð ðBð �{‰{ð	Bð
 —‘ðBð Ÿ™ðBð ðBð ðBð òBó ôBr5   r
  c                   ó   — e Zd Zy)ÚKwargsForCausalLMN)rI   rJ   rK   rÊ   r5   r4   rU  rU  ÷  s   … r5   rU  c                   óâ  ‡ — e Zd ZdgZddiZddgdgfiZˆ fd„Zd„ Zd„ Zd	„ Z	d
„ Z
d„ Zd„ Ze eddd¬«       ee«       eee¬«      	 	 	 	 	 	 	 	 	 	 	 ddeej,                     deej.                     deej,                     dee   deej2                     deej,                     dee   dee   dee   deej,                     deeej.                  f   dee   defd„«       «       «       «       Zˆ xZ S ) ÚQwen3ForCausalLMzlm_head.weightÚlm_headÚcolwise_repr@   Úlogitsc                 óè   •— t         ‰| �  |«       t        |«      | _        |j                  | _        t        j                  |j                  |j                  d¬«      | _        | j                  «        y rQ   )
r)   r*   r
  rò   r  r   rV   r1   rX  r  r\   s     €r4   r*   zQwen3ForCausalLM.__init__ÿ  sU   ø€ Ü‰Ñ˜Ô Ü Ó'ˆŒ
Ø ×+Ñ+ˆŒÜ—y‘y ×!3Ñ!3°V×5FÑ5FÈUÔSˆŒð 	�‰Õr5   c                 ó.   — | j                   j                  S r^   ©rò   r  rG   s    r4   r  z%Qwen3ForCausalLM.get_input_embeddings  ó   € Ø�z‰z×&Ñ&Ð&r5   c                 ó&   — || j                   _        y r^   r]  r  s     r4   r  z%Qwen3ForCausalLM.set_input_embeddings  ó   € Ø"'ˆ�
‰
Õr5   c                 ó   — | j                   S r^   ©rX  rG   s    r4   Úget_output_embeddingsz&Qwen3ForCausalLM.get_output_embeddings  s   € Ø�|‰|Ðr5   c                 ó   — || _         y r^   rb  )r0   Únew_embeddingss     r4   Úset_output_embeddingsz&Qwen3ForCausalLM.set_output_embeddings  s	   € Ø%ˆ�r5   c                 ó   — || _         y r^   ©rò   )r0   Údecoders     r4   Úset_decoderzQwen3ForCausalLM.set_decoder  s	   € Øˆ�
r5   c                 ó   — | j                   S r^   rh  rG   s    r4   Úget_decoderzQwen3ForCausalLM.get_decoder  s   € Ø�z‰zÐr5   Únum_logits_to_keepz4.50Úlogits_to_keep)ÚversionÚnew_name)Úoutput_typerý   r  r€   rm   ró   r  ÚlabelsrÈ   r¯   r  r«   r�   rs   c                 óæ  — |�|n| j                   j                  }|	�|	n| j                   j                  }	 | j                  d||||||||	|
dœ	|¤Ž}|j                  }t        |t        «      rt        | d«      n|}| j                  |dd…|dd…f   «      }d}|�* | j                  d||| j                   j                  dœ|¤Ž}t        |||j                  |j                  |j                  ¬«      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."
        ```N)	r  r€   rm   ró   r  rÈ   r¯   r  r«   )rZ  rr  r  ©ÚlossrZ  ró   r@   r$  rÊ   )rT   r¯   r  rò   r#  rè   r½   ÚslicerX  Úloss_functionr  r   ró   r@   r$  )r0   r  r€   rm   ró   r  rr  rÈ   r¯   r  r«   rn  r�   rÍ   r@   Úslice_indicesrZ  ru  s                     r4   rC   zQwen3ForCausalLM.forward  s  € ðd 2CÐ1NÑ-ÐTX×T_ÑT_×TqÑTqÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	ð
 ,6¨4¯:©:ð ,
ØØ)Ø%Ø+Ø'ØØ/Ø!5Ø)ñ,
ð ñ,
ˆð  ×1Ñ1ˆä8BÀ>ÔSVÔ8Wœ˜~˜o¨tÔ4Ð]kˆØ—‘˜mªA¨}ºaÐ,?Ñ@ÓAˆàˆØÐØ%�4×%Ñ%Ðp¨V¸FÈtÏ{É{×OeÑOeÑpÐioÑpˆDä%ØØØ#×3Ñ3Ø!×/Ñ/Ø×)Ñ)ô
ð 	
r5   )NNNNNNNNNNr   )!rI   rJ   rK   Ú_tied_weights_keysÚ_tp_planÚ_pp_planr*   r  r  rc  rf  rj  rl  r    r#   r   rR  r"   r   Ú_CONFIG_FOR_DOCr   r,   r¿   r¾   r   rÏ   rÎ   r   r½   r   rU  rC   rL   rM   s   @r4   rW  rW  ú  s¬  ø„ Ø*Ð+ÐØ˜=Ð)€HØ˜_Ð-°¨zÐ:Ð;€Hôò'ò(òò&òòð ÙÐ)°6ÐDTÔUÙ*Ð+AÓBÙÐ+AÐP_Ô`ð 15Ø15Ø37Ø+/Ø59Ø-1Ø$(Ø,0Ø/3Ø59Ø34ñP
à˜E×,Ñ,Ñ-ðP
ð ! §¡Ñ.ðP
ð ˜u×/Ñ/Ñ0ð	P
ð
 " %™ðP
ð   × 1Ñ 1Ñ2ðP
ð ˜×)Ñ)Ñ*ðP
ð ˜D‘>ðP
ð $ D™>ðP
ð ' t™nðP
ð ! ×!1Ñ!1Ñ2ðP
ð ˜c 5§<¡<Ð/Ñ0ðP
ð Ð*Ñ+ðP
ð 
 òP
ó aó Có Vó ôP
r5   rW  aÖ  
    The Qwen3 Model transformer with a sequence classification head on top (linear layer).

    [`Qwen3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                   ó(  ‡ — e Zd Zˆ fd„Zd„ Zd„ Ze ee«      	 	 	 	 	 	 	 	 	 dde	e
j                     de	e
j                     de	e
j                     de	e   de	e
j                     d	e	e
j                     d
e	e   de	e   de	e   defd„«       «       Zˆ xZS )ÚQwen3ForSequenceClassificationc                 óè   •— t         ‰| �  |«       |j                  | _        t        |«      | _        t        j                  |j                  | j                  d¬«      | _        | j                  «        y rQ   )
r)   r*   Ú
num_labelsr
  rò   r   rV   r1   Úscorer  r\   s     €r4   r*   z'Qwen3ForSequenceClassification.__init__�  sS   ø€ Ü‰Ñ˜Ô Ø ×+Ñ+ˆŒÜ Ó'ˆŒ
Ü—Y‘Y˜v×1Ñ1°4·?±?ÈÔOˆŒ
ð 	�‰Õr5   c                 ó.   — | j                   j                  S r^   r]  rG   s    r4   r  z3Qwen3ForSequenceClassification.get_input_embeddingsŠ  r^  r5   c                 ó&   — || j                   _        y r^   r]  r  s     r4   r  z3Qwen3ForSequenceClassification.set_input_embeddings�  r`  r5   r  r€   rm   ró   r  rr  rÈ   r¯   r  rs   c
           
      ó¢  — | j                  ||||||||	¬«      }
|
j                  }| j                  |«      }|�|j                  d   }n|j                  d   }| j                  j
                  €|dk7  rt        d«      ‚| j                  j
                  €d}nÃ|�“|| j                  j
                  k7  j                  |j                  t        j                  «      }t        j                  |j                  d   |j                  t        j                  ¬«      }||z  j                  d«      }n.d}t        j                  | j                  j                   › d�«       |t        j                  ||j                  ¬	«      |f   }d}|�| j#                  |||| j                  ¬
«      }t%        |||
j&                  |
j(                  |
j*                  ¬«      S )á�  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        ©r€   rm   ró   r  rÈ   r¯   r  Nr   r$   z=Cannot handle batch sizes > 1 if no padding token is defined.r8   )rá   r:   zŠ will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r"  )rZ  rr  Úpooled_logitsrT   rt  )rò   r#  r�  rF   rT   r  r%  r;   rá   r,   Úint32r'  Úargmaxrµ   r¶   r3   rI   rw  r   ró   r@   r$  )r0   r  r€   rm   ró   r  rr  rÈ   r¯   r  Útransformer_outputsr@   rZ  r6  Úlast_non_pad_tokenÚnon_pad_maskÚtoken_indicesr‡  ru  s                      r4   rC   z&Qwen3ForSequenceClassification.forward�  sÁ  € ð* 8<·z±zØØ)Ø%Ø+Ø'ØØ/Ø!5ð 8Bó 	8
Ðð ,×=Ñ=ˆØ—‘˜MÓ*ˆàÐ Ø"Ÿ™¨Ñ+‰Jà&×,Ñ,¨QÑ/ˆJà�;‰;×#Ñ#Ð+°
¸a²ÜÐ\Ó]Ð]Ø�;‰;×#Ñ#Ð+Ø!#ÑØÐ"à%¨¯©×)AÑ)AÑA×EÑEÀfÇmÁmÔUZ×U`ÑU`ÓaˆLÜ!ŸL™L¨¯©¸Ñ)<ÀVÇ]Á]ÔZ_×ZeÑZeÔfˆMØ"/°,Ñ">×!FÑ!FÀrÓ!JÑà!#ÐÜ×ÑØ—>‘>×*Ñ*Ð+ð ,Zð Zôð
 œuŸ|™|¨J¸v¿}¹}ÔMÐOaÐaÑbˆàˆØÐØ×%Ñ%¨V¸FÐR_Ðhl×hsÑhsÐ%ÓtˆDä/ØØ Ø/×?Ñ?Ø-×;Ñ;Ø*×5Ñ5ô
ð 	
r5   rQ  )rI   rJ   rK   r*   r  r  r    r   rR  r   r,   r¿   r¾   r   rÏ   rÎ   r   rC   rL   rM   s   @r4   r~  r~  q  s  ø„ ô ò'ò(ð Ù*Ð+AÓBð 15Ø15Ø37Ø+/Ø59Ø-1Ø$(Ø,0Ø/3ñA
à˜E×,Ñ,Ñ-ðA
ð ! §¡Ñ.ðA
ð ˜u×/Ñ/Ñ0ð	A
ð
 " %™ðA
ð   × 1Ñ 1Ñ2ðA
ð ˜×)Ñ)Ñ*ðA
ð ˜D‘>ðA
ð $ D™>ðA
ð ' t™nðA
ð 
*òA
ó Có ôA
r5   r~  z´
    The Qwen3 Model transformer with a token classification head on top (a linear layer on top of the hidden-states
    output) e.g. for Named-Entity-Recognition (NER) tasks.
    c                   óD  ‡ — e Zd Zˆ fd„Zd„ Zd„ Ze ee«       e	e
ee¬«      	 	 	 	 	 	 	 	 	 ddeej                     deej                      deej                     dee   d	eej$                     d
eej                     dee   dee   dee   defd„«       «       «       Zˆ xZS )ÚQwen3ForTokenClassificationc                 ó„  •— t         ‰| �  |«       |j                  | _        t        |«      | _        t        |dd «      �|j                  }nt        |dd «      �|j                  }nd}t        j                  |«      | _
        t        j                  |j                  |j                  «      | _        | j                  «        y )NÚclassifier_dropoutÚhidden_dropoutgš™™™™™¹?)r)   r*   r€  r
  rò   rš   r‘  r’  r   ÚDropoutr‚   rV   r1   r�  r  )r0   rT   r‘  r3   s      €r4   r*   z$Qwen3ForTokenClassification.__init__Þ  s¢   ø€ Ü‰Ñ˜Ô Ø ×+Ñ+ˆŒÜ Ó'ˆŒ
Ü�6Ð/°Ó6ÐBØ!'×!:Ñ!:ÑÜ�VÐ-¨tÓ4Ð@Ø!'×!6Ñ!6Ñà!$ÐÜ—z‘zÐ"4Ó5ˆŒÜ—Y‘Y˜v×1Ñ1°6×3DÑ3DÓEˆŒ
ð 	�‰Õr5   c                 ó.   — | j                   j                  S r^   r]  rG   s    r4   r  z0Qwen3ForTokenClassification.get_input_embeddingsî  r^  r5   c                 ó&   — || j                   _        y r^   r]  r  s     r4   r  z0Qwen3ForTokenClassification.set_input_embeddingsñ  r`  r5   )Ú
checkpointrq  rý   r  r€   rm   ró   r  rr  rÈ   r¯   r  rs   c
           
      ó  — | j                  ||||||||	¬«      }
|
j                  }| j                  |«      }| j                  |«      }d}|�| j	                  ||| j
                  «      }t        |||
j                  |
j                  ¬«      S )r…  r†  N)ru  rZ  r@   r$  )	rò   r#  r‚   r�  rw  rT   r   r@   r$  )r0   r  r€   rm   ró   r  rr  rÈ   r¯   r  rÍ   Úsequence_outputrZ  ru  s                 r4   rC   z#Qwen3ForTokenClassification.forwardô  s    € ð4 ,0¯:©:ØØ)Ø%Ø+Ø'ØØ/Ø!5ð ,6ó 	,
ˆð "×3Ñ3ˆØŸ,™, Ó7ˆØ—‘˜OÓ,ˆàˆØÐØ×%Ñ% f¨f°d·k±kÓBˆDä$ØØØ!×/Ñ/Ø×)Ñ)ô	
ð 	
r5   rQ  )rI   rJ   rK   r*   r  r  r    r   rR  r   Ú_CHECKPOINT_FOR_DOCr   r|  r   r,   r¿   r¾   r   rÏ   rÎ   rC   rL   rM   s   @r4   r�  r�  Ö  s  ø„ ôò 'ò(ð Ù*Ð+AÓBÙØ&Ø)Ø$ôð 15Ø15Ø37Ø+/Ø59Ø-1Ø$(Ø,0Ø/3ñ*
à˜E×,Ñ,Ñ-ð*
ð ! §¡Ñ.ð*
ð ˜u×/Ñ/Ñ0ð	*
ð
 " %™ð*
ð   × 1Ñ 1Ñ2ð*
ð ˜×)Ñ)Ñ*ð*
ð ˜D‘>ð*
ð $ D™>ð*
ð ' t™nð*
ð 
ò*
óó Có ô*
r5   r�  zå
The Qwen3 Model transformer with a span classification head on top for extractive question-answering tasks like
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                   ó@  ‡ — e Zd ZdZˆ fd„Zd„ Zd„ Ze ee	«      	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
e   d	e
ej                     d
e
ej                     de
ej                     de
e   de
e   defd„«       «       Zˆ xZS )ÚQwen3ForQuestionAnsweringÚtransformerc                 ó®   •— t         ‰| �  |«       t        |«      | _        t	        j
                  |j                  d«      | _        | j                  «        y )Nr7   )	r)   r*   r
  rœ  r   rV   r1   Ú
qa_outputsr  r\   s     €r4   r*   z"Qwen3ForQuestionAnswering.__init__2  sA   ø€ Ü‰Ñ˜Ô Ü% fÓ-ˆÔÜŸ)™) F×$6Ñ$6¸Ó:ˆŒð 	�‰Õr5   c                 ó.   — | j                   j                  S r^   ©rœ  r  rG   s    r4   r  z.Qwen3ForQuestionAnswering.get_input_embeddings:  s   € Ø×Ñ×,Ñ,Ð,r5   c                 ó&   — || j                   _        y r^   r   r  s     r4   r  z.Qwen3ForQuestionAnswering.set_input_embeddings=  s   € Ø(-ˆ×ÑÕ%r5   r  r€   rm   ró   r  Ústart_positionsÚend_positionsr¯   r  rs   c
           	      ó”  — | j                  |||||||	¬«      }|j                  }| j                  |«      }|j                  dd¬«      \  }}|j	                  d«      j                  «       }|j	                  d«      j                  «       }d}|�|� | j                  ||||fi |
¤Ž}t        ||||j                  |j                  ¬«      S )a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        )r€   rm   ró   r  r¯   r  r$   r8   ra   N)ru  Ústart_logitsÚ
end_logitsr@   r$  )
rœ  r#  rž  ÚsplitÚsqueezerŒ   rw  r   r@   r$  )r0   r  r€   rm   ró   r  r¢  r£  r¯   r  r�   rÍ   r˜  rZ  r¥  r¦  ru  s                    r4   rC   z!Qwen3ForQuestionAnswering.forward@  sé   € ð4 ,0×+;Ñ+;ØØ)Ø%Ø+Ø'Ø/Ø!5ð ,<ó ,
ˆð "×3Ñ3ˆà—‘ Ó1ˆØ#)§<¡<°°r <Ó#:Ñ ˆ�jØ#×+Ñ+¨BÓ/×:Ñ:Ó<ˆØ×'Ñ'¨Ó+×6Ñ6Ó8ˆ
àˆØÐ&¨=Ð+DØ%�4×%Ñ% l°JÀÐQ^ÑiÐbhÑiˆDä+ØØ%Ø!Ø!×/Ñ/Ø×)Ñ)ô
ð 	
r5   rQ  )rI   rJ   rK   rþ   r*   r  r  r    r   rR  r   r,   r¿   rÏ   r   rÎ   r   rC   rL   rM   s   @r4   r›  r›  (  s
  ø„ ð &Ðôò-ò.ð Ù*Ð+AÓBð 15Ø6:Ø37Ø+/Ø59Ø6:Ø48Ø,0Ø/3ñ3
à˜E×,Ñ,Ñ-ð3
ð ! ×!2Ñ!2Ñ3ð3
ð ˜u×/Ñ/Ñ0ð	3
ð
 " %™ð3
ð   × 1Ñ 1Ñ2ð3
ð " %×"2Ñ"2Ñ3ð3
ð   × 0Ñ 0Ñ1ð3
ð $ D™>ð3
ð ' t™nð3
ð 
&ò3
ó Có ô3
r5   r›  )rW  r›  r
  rñ   r~  r�  )Nr$   )r°   )LÚ	functoolsr   Útypingr   r   r   r   r,   r   Úactivationsr
   Úcache_utilsr   r   r   r   Ú
generationr   Úmodeling_attn_mask_utilsr   Úmodeling_flash_attention_utilsr   Úmodeling_outputsr   r   r   r   r   Úmodeling_rope_utilsr   r   Úmodeling_utilsr   r   Úprocessing_utilsr   Úutilsr   r   r   r   r    r!   r"   Úutils.deprecationr#   Úconfiguration_qwen3r%   Ú
get_loggerrI   rµ   r™  r|  ÚModuler'   rO   rf   rq   r¾   r½   r{   rç   r“   r•   rÁ   rÑ   ÚQWEN3_START_DOCSTRINGrñ   rR  r
  rU  rW  r~  r�  r›  Ú__all__rÊ   r5   r4   ú<module>r»     sv  ðõ, ß 3Ó 3ã Ý å !ß OÓ OÝ )Ý >Ý B÷õ ÷ Lß FÝ &÷÷ ñ õ 1Ý ,ð 
ˆ×	Ñ	˜HÓ	%€à%Ð Ø€ôJ�2—9‘9ô Jô(ˆr�y‰yô ò (óð6	U˜UŸ\™\ð 	U°#ð 	U¸%¿,¹,ó 	Uð& ñ%Ø�I‰Ið%à�<‰<ð%ð 
�‰ð%ð �<‰<ð	%ð
 ˜UŸ\™\Ñ*ð%ð ð%ð ó%ô4S)�R—Y‘Yô S)ôl8˜Ÿ	™	ô 8ôv<˜2Ÿ9™9ô <ðDÐ ñ" ØYØóô?˜?ó ?ó	ð?ð4@Ð ñF ØYØóôaÐ%ó aó	ðaôH	 ?Ð,¨jÔ >ôt
Ð+¨_ô t
ñn ðð óôS
Ð%9ó S
óðS
ñl ðð óôH
Ð"6ó H
óðH
ñV ðð óôF
Ð 4ó F
óðF
òR�r5   