
    3j                        S SK Jr  S SKJr  S SKrS SKJs  Jr  S SKJr  SSK	J
r  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJrJr  SSKJrJr  SSKJr  SSKJr  SSKJ r J!r!  SSK"J#r#J$r$  SSK%J&r&J'r'  SSK(J)r)  SSK*J+r+J,r,  SSK-J.r.J/r/J0r0  SSK1J2r2J3r3  SSK4J5r5   " S S\Rl                  5      r7\" S5       " S S\Rl                  5      5       r8S r9\" S5      SBS j5       r:S\Rv                  S \<S!\Rv                  4S" jr= SCS#\Rl                  S$\Rv                  S%\Rv                  S&\Rv                  S'\Rv                  S-  S(\>S)\>S*\)\.   4S+ jjr?\" \:5       " S, S-\Rl                  5      5       r@\ " S. S/\Rl                  5      5       rA " S0 S1\Rl                  5      rB " S2 S3\Rl                  5      rC " S4 S5\Rl                  5      rD " S6 S7\5      rE\+ " S8 S9\'5      5       rF\+ " S: S;\F5      5       rG   SDS<\Rv                  \H\Rv                     -  S-  S=\<S-  S'\Rv                  S-  S!\Rv                  \<-  4S> jjrI\+ " S? S@\F\5      5       rJ/ SAQrKg)E    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tuple)TransformersKwargsmaybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )MellumConfigc                      ^  \ rS rSr% \R
                  \S'   S\4U 4S jjr\	    SS\S-  S\
S   S\S-  S	\S-  S
\S\4   4
S jj5       r\R                   " 5       \SS j5       5       rSrU =r$ )MellumRotaryEmbedding3   inv_freqconfigc                 f  > [         TU ]  5         UR                  U l        UR                  U l        Xl        [        [        UR                  5      5      U l        0 U l	        U R                   H  nU R
                  R                  U   nUc  M!  US   U R                  U'   U R                  nU R                  U   S:w  a  [        U R                  U      nU" U R
                  US9u  pVU R                  U S3USS9  U R                  U S3UR                  5       SS9  [        X S3U5        M     g )	N	rope_typedefault
layer_type	_inv_freqF)
persistent_original_inv_freq_attention_scaling)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr(   listsetlayer_typesr*   rope_parameterscompute_default_rope_parametersr   register_bufferclonesetattr)selfr(   r-   rope_paramsrope_init_fncurr_inv_freqcurr_attention_scaling	__class__s          d/home/wildlama/miniconda3/lib/python3.13/site-packages/transformers/models/mellum/modeling_mellum.pyr3   MellumRotaryEmbedding.__init__6   s(   "("@"@$*$B$B!F$6$6 78**J++55jAK")4[)ADNN:&%)%I%IL~~j)Y624>>*3MN4@Yc4d1M  J<y!9=UZ [  J</A!BMDWDWDYfk lDL(:;=ST +    Ndeviceztorch.deviceseq_lenr-   returnztorch.Tensorc           	      v   U R                   U   S   nU R                   U   R                  SS5      n[        U SS5      =(       d    U R                  U R                  -  n[        Xe-  5      nSnSU[        R                  " SUS[        R                  S9R                  U[        R                  S	9U-  -  -  n	X4$ )
a  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
    layer_type (`str`, *optional*):
        The current layer type if the model has different RoPE parameters per type.
        Should not be used unless `config.layer_types is not None`
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetapartial_rotary_factorg      ?head_dimNr      dtype)rH   rQ   )r:   getgetattrhidden_sizenum_attention_headsinttorcharangeint64tofloat)
r(   rH   rI   r-   baserM   rN   dimattention_factorr'   s
             rE   r;   5MellumRotaryEmbedding.compute_default_rope_parametersK   s    . %%j1,? & 6 6z B F FG^`c d6:t4h8J8JfNhNh8h(23 U\\!S!5;;?BB&X]XcXcBdgjjk
 ))rG   c                 H   [        X S35      n[        X S35      nUS S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        USS	9   UR                  5       UR                  5       -  R                  SS
5      n	[        R                  " X4SS9n
U
R                  5       U-  nU
R                  5       U-  nS S S 5        WR	                  UR                  S9WR	                  UR                  S94$ ! , (       d  f       N@= f)Nr.   r1   r   r"   mpscpuF)device_typeenabledrO   r]   rP   )rS   r[   expandshaperZ   rH   
isinstancetypestrr   	transposerW   catcossinrQ   )r?   xposition_idsr-   r'   attention_scalinginv_freq_expandedposition_ids_expandedrd   freqsembrn   ro   s                rE   forwardMellumRotaryEmbedding.forwardp   sd    4<y!9:#DL8J*KL$T1d]399;BB<CUCUVWCXZ\^_`ccdedldlm ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')//C'')//C	 D vvAGGv$cff177f&;;; DCs   +A.F
F!)r(   r9   r5   r6   r*   )NNNNN)__name__
__module____qualname____firstlineno__rW   Tensor__annotations__r#   r3   staticmethodr   rV   rk   tupler[   r;   no_gradr   rw   __static_attributes____classcell__rD   s   @rE   r%   r%   3   s    llU| U* &*+/"!%	"*t#"*("* t"* $J	"*
 
~u$	%"* "*H ]]_<  <rG   r%   RMSNormc                   x   ^  \ rS rSrS
S\SS4U 4S jjjrS\R                  S\R                  4S jrS r	S	r
U =r$ )MellumRMSNorm   epsrJ   Nc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z,
MellumRMSNorm is equivalent to T5LayerNorm
N)r2   r3   r   	ParameterrW   onesweightvariance_epsilon)r?   rT   r   rD   s      rE   r3   MellumRMSNorm.__init__   s/     	ll5::k#:; #rG   hidden_statesc                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ )NrO   ra   T)keepdim)	rQ   rZ   rW   float32powmeanrsqrtr   r   )r?   r   input_dtypevariances       rE   rw   MellumRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::rG   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r   r   rh   r   )r?   s    rE   
extra_reprMellumRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrG   )r   r   )gư>)rz   r{   r|   r}   r[   r3   rW   r~   rw   r   r   r   r   s   @rE   r   r      sB    $ $$ $ $;U\\ ;ell ;J JrG   r   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nra   rO   rf   )rh   rW   rm   )rp   x1x2s      rE   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rG   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  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.
    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.
)	unsqueezer   )qkrn   ro   unsqueeze_dimq_embedk_embeds          rE   apply_rotary_pos_embr      sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0GrG   r   n_reprJ   c                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )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)rh   rg   reshape)r   r   batchnum_key_value_headsslenrN   s         rE   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTrG   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub  X-   n
[
        R                  R                  U
S[        R                  S9R                  UR                  5      n
[
        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )NrO   r   ra   )r]   rQ   )ptrainingr"   )r   num_key_value_groupsrW   matmulrl   r   
functionalsoftmaxr   rZ   rQ   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               rE   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$rG   c                     ^  \ rS rSrSrS\S\4U 4S jjr SS\R                  S\
\R                  \R                  4   S	\R                  S-  S
\S-  S\\   S\
\R                  \R                  S-  4   4S jjrSrU =r$ )MellumAttention   z=Multi-headed attention from 'Attention Is All You Need' paperr(   	layer_idxc                 4  > [         TU ]  5         Xl        X l        [	        USUR
                  UR                  -  5      U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        SU l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR                  U R                  -  UR
                  UR                  S9U l        [)        U R                  UR*                  S9U l        [)        U R                  UR*                  S9U l        UR0                  U   S:X  a  UR2                  U l        g S U l        g )NrN   g      Tbiasr   sliding_attention)r2   r3   r(   r   rS   rT   rU   rN   r   r   r   attention_dropout	is_causalr   Linearattention_biasq_projk_projv_projo_projr   rms_norm_epsq_normk_normr9   sliding_windowr?   r(   r   rD   s      rE   r3   MellumAttention.__init__   s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 $DMMv7J7JK#DMMv7J7JK7=7I7I)7TXk7kf33qurG   Nr   position_embeddingsr   past_key_valuesr   rJ   c                 Z   UR                   S S n/ UQSPU R                  P7nU R                  U R                  U5      R	                  U5      5      R                  SS5      nU R                  U R                  U5      R	                  U5      5      R                  SS5      n	U R                  U5      R	                  U5      R                  SS5      n
Uu  p[        XX5      u  pUb  UR                  XU R                  5      u  p[        R                  " U R                  R                  [         5      nU" U UU	U
U4U R"                  (       d  SOU R$                  U R&                  U R(                  S.UD6u  pUR*                  " / UQSP76 R-                  5       nU R/                  U5      nX4$ )Nra   r"   rO           )r   r   r   )rh   rN   r   r   viewrl   r   r   r   r   updater   r   get_interfacer(   _attn_implementationr   r   r   r   r   r   r   r   )r?   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   rn   ro   attention_interfacer   r   s                   rE   rw   MellumAttention.forward   s    $))#2.88b8$--8{{4;;}#=#B#B<#PQ[[\]_`a[[]!;!@!@!NOYYZ[]^_
{{=166|DNNqRST&#7RU#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL..
%
 
%
! "));;;;FFHkk+.((rG   )r   r(   rN   r   r   r   r   r   r   r   r   r   r   r   ry   )rz   r{   r|   r}   __doc__r#   rV   r3   rW   r~   r   r	   r   r   rw   r   r   r   s   @rE   r   r      s    Gv| v v> )-')||') #5<<#=>') t+	')
 ') -.') 
u||U\\D00	1') ')rG   r   c                      ^  \ rS rSrSrU 4S jrS\R                  S\R                  S\R                  S\R                  4S jrS	r	U =r
$ )
MellumExpertsi&  z2Collection of expert weights stored as 3D tensors.c                   > [         TU ]  5         UR                  U l        UR                  U l        UR
                  U l        [        R                  " [        R                  " U R                  SU R                  -  U R                  5      5      U l        [        R                  " [        R                  " U R                  U R                  U R                  5      5      U l        [        UR                     U l        g )NrO   )r2   r3   num_expertsrT   
hidden_dimmoe_intermediate_sizeintermediate_dimr   r   rW   emptygate_up_proj	down_projr   
hidden_actact_fnr?   r(   rD   s     rE   r3   MellumExperts.__init__*  s    !-- ,, & < <LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../rG   r   top_k_indextop_k_weightsrJ   c                 X   [         R                  " U5      n[         R                  " 5          [         R                  R                  R                  X R                  S9nUR                  SSS5      n[         R                  " UR                  SS9S5      R                  5       nS S S 5        W H  nUS   nXpR                  :X  a  M  [         R                  " WU   5      u  pX   n
[        R                  R                  XR                  U   5      R                  SSS9u  pU R                  U5      U-  n[        R                  R                  XR                   U   5      nXXS 4   -  nUR#                  SXR%                  UR&                  5      5        M     U$ ! , (       d  f       N= f)N)num_classesrO   r"   r   )ra   rf   ra   )rW   
zeros_liker   r   r   one_hotr   permutegreatersumnonzerowherelinearr   chunkr   r   
index_add_rZ   rQ   )r?   r   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 rE   rw   MellumExperts.forward3  so    $..}=]]_((--55kO_O_5`K%--aA6K{8'DaHPPRJ 
 %J#AJ---#(;;{:/F#G I)4M}}++M;L;LZ;XY__`agi_jHD$(KK$5$:!$&MM$8$89NP^P^_iPj$k!$9)`dJd<e$e!**1i9Q9QReRkRk9lm % #"# _s   A7F
F))r   r   r   r   r   r   )rz   r{   r|   r}   r   r3   rW   r~   rw   r   r   r   s   @rE   r   r   &  sK    <0#||# \\# ||	#
 
# #rG   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )MellumTopKRouteriN  c                 2  > [         TU ]  5         UR                  U l        UR                  U l        UR
                  U l        UR                  U l        [        R                  " [        R                  " U R                  U R                  5      5      U l        g ry   )r2   r3   num_experts_per_toktop_kr   norm_topk_probrT   r   r   r   rW   zerosr   r   s     rE   r3   MellumTopKRouter.__init__O  si    //
!--$33 ,,ll5;;t/?/?#QRrG   c                    UR                  SU R                  5      n[        R                  " XR                  5      n[
        R                  R                  R                  U[
        R                  SS9n[
        R                  " X0R                  SS9u  pEU R                  (       a  XDR                  SSS9-  nUR                  UR                  5      nUnX&U4$ )Nra   )rQ   r]   rf   T)r]   r   )r   r   Fr  r   rW   r   r   r   r[   topkr  r  r  rZ   rQ   )r?   r   router_logitsrouter_probsrouter_top_valuerouter_indicesrouter_scoress          rE   rw   MellumTopKRouter.forwardW  s    %--b$//B<xx**22=Y[2\+0::lJJTV+W( 4 4T 4 JJ+..}/B/BC(^;;rG   )r   r  r   r  r   rz   r{   r|   r}   r3   rw   r   r   r   s   @rE   r  r  N  s    S	< 	<rG   r  c                   j   ^  \ rS rSrS\4U 4S jjrS\R                  S\R                  4S jrSr	U =r
$ )MellumSparseMoeBlockic  r(   c                 b   > [         TU ]  5         [        U5      U l        [	        U5      U l        g ry   )r2   r3   r   expertsr  r  r   s     rE   r3   MellumSparseMoeBlock.__init__d  s&    $V,$V,	rG   r   rJ   c                     UR                   u  p#nUR                  SU5      nU R                  U5      u  pgnU R                  XXU5      n	U	R	                  X#U5      $ )Nra   )rh   r   r  r)  r   )
r?   r   
batch_sizesequence_lengthr   hidden_states_reshaped_routing_weightsselected_expertsr	  s
             rE   rw   MellumSparseMoeBlock.forwardi  s`    2?2E2E/
Z!.!3!3B
!C/3yy9O/P,,"ll+AUde"**:
SSrG   )r)  r  )rz   r{   r|   r}   r#   r3   rW   r~   rw   r   r   r   s   @rE   r'  r'  c  s3    -| -
TU\\ Tell T TrG   r'  c                   2   ^  \ rS rSrSU 4S jjrS rSrU =r$ )	MellumMLPiq  c                   > [         TU ]  5         Xl        UR                  U l        Uc  UR                  OUU l        [
        R                  " U R                  U R                  SS9U l        [
        R                  " U R                  U R                  SS9U l        [
        R                  " U R                  U R                  SS9U l	        [        UR                     U l        g NFr   )r2   r3   r(   rT   intermediate_sizer   r   	gate_projup_projr   r   r   r   )r?   r(   r7  rD   s      rE   r3   MellumMLP.__init__r  s    !--=N=V!9!9\m4#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../rG   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ ry   )r   r   r8  r9  )r?   rp   r   s      rE   rw   MellumMLP.forward|  s6    NN4;;t~~a/@#ADLLQRO#ST	rG   )r   r(   r   r8  rT   r7  r9  ry   r%  r   s   @rE   r4  r4  q  s    0 rG   r4  c                     ^  \ rS rSrS\S\4U 4S jjr     SS\R                  S\R                  S-  S\R                  S-  S	\
S-  S
\S-  S\\R                  \R                  4   S-  S\\   S\R                  4S jjrSrU =r$ )MellumDecoderLayeri  r(   r   c                 h  > [         TU ]  5         UR                  U l        [        X5      U l        UR
                  U   S:X  a  [        U5      U l        O[        XR                  S9U l        [        UR                  UR                  S9U l        [        UR                  UR                  S9U l        g )Nsparse)r7  r   )r2   r3   rT   r   	self_attnmlp_layer_typesr'  mlpr4  r7  r   r   input_layernormpost_attention_layernormr   s      rE   r3   MellumDecoderLayer.__init__  s    !--(;!!),8+F3DH ;S;STDH,V-?-?VEXEXY(5f6H6HfNaNa(b%rG   Nr   r   rq   r   	use_cacher   r   rJ   c           
          UnU R                  U5      nU R                  " SUUUUUUS.UD6u  pX-   nUnU R                  U5      nU R                  U5      nX-   nU$ )N)r   r   rq   r   rG  r    )rD  rA  rE  rC  )
r?   r   r   rq   r   rG  r   r   residualr/  s
             rE   rw   MellumDecoderLayer.forward  s     !,,];>> 
')%+ 3
 
 !0 !55mD/ 0rG   )rT   rD  rC  rE  rA  )NNNFN)rz   r{   r|   r}   r#   rV   r3   rW   r~   
LongTensorr	   boolr   r   r   rw   r   r   r   s   @rE   r>  r>    s    	c| 	c 	c /304(,!&HL|| t+ &&-	
  $; #5<<#=>E +, 
 rG   r>  c                      ^  \ rS rSr% \\S'   SrSrS/rS/r	Sr
SrSrSrSr\" \SS9\\S	.r\R*                  " 5       U 4S
 j5       rSrU =r$ )MellumPreTrainedModeli  r(   modelTr>  r   r   )index)r  r   
attentionsc                   > [         TU ]  U5        U R                  R                  n[	        U[
        5      (       aA  [        R                  " UR                  SUS9  [        R                  " UR                  SUS9  O5[	        U[        5      (       a   [        R                  " UR                  SUS9  [	        U[        5      (       a  UR                   H  nUR                  nUR                  U   S:w  a  [         UR                  U      nU" UR                  US9u  pV[        R"                  " [%        X S35      U5        [        R"                  " [%        X S35      U5        M     g g )Nr   )r   stdr+   r,   r.   r0   )r2   _init_weightsr(   initializer_rangeri   r   initnormal_r   r   r  r   r%   r9   r;   r*   r   copy_rS   )r?   r   rT  r-   rA   rB   r/  rD   s          rE   rU  #MellumPreTrainedModel._init_weights  s   f%kk++fm,,LL,,3C@LL))= 011LLSc:f344$00
%EE##J/9<#6v7G7G
7S#TL#/*#U 

76\+CDmT

76\9K+LM}] 1 5rG   rI  )rz   r{   r|   r}   r#   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr    r  r>  r   _can_record_outputsrW   r   rU  r   r   r   s   @rE   rO  rO    sy    &*#-.#4"5N!"&'(8B+% ]]_^ ^rG   rO  c                     ^  \ rS rSrS\4U 4S jjr\\\      SS\	R                  S-  S\	R                  S-  S\	R                  S-  S\S-  S	\	R                  S-  S
\S-  S\\   S\4S jj5       5       5       rSrU =r$ )MellumModeli  r(   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [
        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        [#        US9U l        SU l        U R)                  5         g s  snf )Nr   r(   F)r2   r3   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrT   embed_tokens
ModuleListrangenum_hidden_layersr>  layersr   r   normr%   
rotary_embgradient_checkpointing	post_initr   s      rE   r3   MellumModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdDcy2Dcd
 "&"4"4&:M:MN	/v>&+# 	 es   C?N	input_idsr   rq   r   inputs_embedsrG  r   rJ   c           	        ^ US L US L-  (       a  [        S5      eUc  U R                  U5      nU(       a  Uc  [        U R                  S9nUcU  Ub  UR	                  5       OSn[
        R                  " UR                  S   UR                  S9U-   nUR                  S5      n[        U=n	[        5      (       dR  U R                  UUUUS.mU4S jU4S jS	.n
0 n	[        U R                  R                  5       H  nX   " 5       X'   M     Un0 n[        U R                  R                  5       H  nU R                  XU5      X'   M     [        U R                   S U R                  R"                   5       HE  u  pU" U4XR                  R                  U      XR                  R                  U      UUS
.UD6nMG     U R%                  U5      n['        UU(       a  US9$ S S9$ )Nz:You must specify exactly one of input_ids or inputs_embedsrh  r   r"   )rH   )r(   rx  r   r   rq   c                     > [        S0 T D6$ NrI  )r   mask_kwargss   rE   <lambda>%MellumModel.forward.<locals>.<lambda>	  s    *<*K{*KrG   c                     > [        S0 T D6$ r{  )r   r|  s   rE   r~  r  
  s    -N-]Q\-]rG   )full_attentionr   )r   r   rq   r   )last_hidden_stater   )
ValueErrorrm  r
   r(   get_seq_lengthrW   rX   rh   rH   r   ri   dictr8   r9   rs  	enumeraterq  rp  rr  r   )r?   rw  r   rq   r   rx  rG  r   past_seen_tokenscausal_mask_mappingmask_creation_functionsr-   r   r   idecoder_layerr}  s                   @rE   rw   MellumModel.forward  s    -t";<YZZ  --i8M0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L?-FF++!."0#2 ,K #L%]'# #%!$++"9"9:
2I2U2W#/ ; & dkk556J.2oom[e.f+ 7 !*$++6U8U8U*V WA)2;;3J3J13MN$78O8OPQ8R$S) / M !X 		-0%+/8O
 	
>B
 	
rG   )rm  rt  rq  rr  rj  rs  rk  )NNNNNN)rz   r{   r|   r}   r#   r3   r   r!   r   rW   rL  r~   r	   FloatTensorrM  r   r   r   rw   r   r   r   s   @rE   rf  rf    s    |     .2.204(,26!%<
##d*<
 t+<
 &&-	<

 <
 ((4/<
 $;<
 +,<
 
 <
    <
rG   rf  gate_logitsr   c                    U b  [        U [        5      (       d  g[        U [        5      (       aC  U S   R                  n[        R                  " U  Vs/ s H  oUR                  U5      PM     snSS9n[        R                  R                  R                  WSS9n[        R                  " XrSS9u  p[        R                  R                  R                  X5      n
Uc:  [        R                  " U
R                  5       SS9n[        R                  " USS9nGOUR                  u  pUR                  S   X-  -  nUSSS2SS2SS4   R                  XXU45      R                  SX!5      R                  W5      n[        R                   " U
R                  5       U-  SS9[        R                   " USS9-  nUSSS2SS2S4   R                  XX45      R                  SU5      R                  U5      n[        R                   " UU-  SS9[        R                   " USS9-  n[        R                   " XR#                  S5      -  5      nUU-  $ s  snf )ax  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.

Args:
    gate_logits:
        Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
        shape [batch_size X sequence_length, num_experts].
    num_experts:
        Number of experts
    top_k:
        The number of experts to route per-token, can be also interpreted as the `top-k` routing
        parameter.
    attention_mask (`torch.Tensor`, *optional*):
        The attention_mask used in forward function
        shape [batch_size X sequence_length] if not None.

Returns:
    The auxiliary loss.
Nr   rf   ra   )ri   r   rH   rW   rm   rZ   r   r   r   r  r   r   r[   rh   rg   r   r  r   )r  r   r  r   compute_device
layer_gateconcatenated_gate_logitsr0  r/  r1  r
  tokens_per_expertrouter_prob_per_expertr,  r-  rp  expert_attention_mask router_per_expert_attention_maskoverall_losss                      rE   load_balancing_loss_funcr  '  s+   : *[%"@"@+u%%$Q..#(99^i-j^iPZmmN.K^i-jpq#r hh))112JPR1SO**_DA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
4::1=*B^_ 4AtT12V&OKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&OQRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1Q1QRS1TTUL+%%[ .ks   Ic                   \  ^  \ rS rSrSS0rSS0rSS/S/40rU 4S jr\\	         SS
\
R                  S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\S	-  S\\
R                  -  S\\   S\4S jj5       5       rSrU =r$ )MellumForCausalLMiy  zlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr   logitsc                 J  > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  U l	        UR                  U l
        UR                  U l        U R                  5         g r6  )r2   r3   rf  rP  rk  r   r   rT   r  router_aux_loss_coefr   r  ru  r   s     rE   r3   MellumForCausalLM.__init__  s      (
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	rG   Nrw  r   rq   r   rx  labelsrG  output_router_logitslogits_to_keepr   rJ   c
                 z   Ub  UOU R                   R                  nU R                  " SUUUUUUUS.U
D6nUR                  n[	        U	[
        5      (       a  [        U	* S5      OU	nU R                  USS2USS24   5      nSnUb  U R                  " XU R                  40 U
D6nSnU(       aY  [        UR                  U R                  U R                  U5      nUb*  XR                  UR                  UR                   5      -  -  n[#        UUUUR$                  UR&                  UR(                  UR                  S9$ )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]`.

Example:

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

>>> model = MellumForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")

>>> 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)rw  r   rq   r   rx  rG  r  )lossaux_lossr  r   r   rR  r  rI  )r(   r  rP  r  ri   rV   slicer  loss_functionrk  r  r  r   r  r  rZ   rH   r   r   r   rR  )r?   rw  r   rq   r   rx  r  rG  r  r  r   outputsr   slice_indicesr  r  r  s                    rE   rw   MellumForCausalLM.forward  sP   N %9$D $++JjJj 	
 +/** 	+
)%+'!5	+
 	+
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
rG   )r  rP  r   r  r  rk  )	NNNNNNNNr   )rz   r{   r|   r}   _tied_weights_keys_tp_plan_pp_planr3   r   r   rW   rL  r~   r	   r  rM  rV   r   r   r   rw   r   r   r   s   @rE   r  r  y  s5   *,GH23H_-z:;H
  .2.204(,26*.!%,0-.P
##d*P
 t+P
 &&-	P

 P
 ((4/P
   4'P
 $;P
 #TkP
 ell*P
 +,P
 
#P
  P
rG   r  )r  rf  rO  )r"   )r   )NrO   N)Lcollections.abcr   typingr   rW   torch.nn.functionalr   r   r   r   rW  activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   r   r   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.genericr   r   r   utils.output_capturingr    r!   configuration_mellumr#   Moduler%   r   r   r   r~   rV   r   r[   r   r   r   r  r'  r4  r>  rO  rf  r   r  r  __all__rI  rG   rE   <module>r     s  * %      & ! . )  S B 9 Q K F & 5 [ [ E .M<BII M<` Y'JBII J (J(( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*D)bii D) +D)N $#BII $# $#N<ryy <*T299 T		  )3 )X "^O "^ "^J P
' P
 P
j #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d c
- c
 c
L HrG   