
    ^j                        d dl mZ d dlmZ d dlZd dlmc mZ d dlmZ ddl	m
Z ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZ ddlmZmZ ddlmZ ddlmZ ddl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, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5  G d dejl                        Z7 ed       G d dejl                               Z8d Z9 ed      dBd       Z:dejv                  d e<d!ejv                  fd"Z=	 dCd#ejl                  d$ejv                  d%ejv                  d&ejv                  d'ejv                  dz  d(e>d)e>d*e)e.   fd+Z? ee:       G d, d-ejl                               Z@e G d. d/ejl                               ZA G d0 d1ejl                        ZB G d2 d3ejl                        ZC G d4 d5ejl                        ZD G d6 d7e      ZEe+ G d8 d9e'             ZFe+ G d: d;eF             ZG	 	 	 dDd<ejv                  eHejv                     z  dz  d=e<dz  d'ejv                  dz  d!ejv                  e<z  fd>ZIe+ G d? d@eFe             ZJg dAZKy)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                        e Zd ZU ej                  ed<   def fdZe	 	 	 	 ddedz  de	d   de
dz  dedz  d	ed
ef   f
d       Z ej                         edd              Z xZS )MellumRotaryEmbeddinginv_freqconfigc                 t   t         |           |j                  | _        |j                  | _        || _        t        t        |j                              | _        i | _	        | j                  D ]  }| j
                  j                  |   }||d   | j                  |<   | j                  }| j                  |   dk7  rt        | j                  |      } || j
                  |      \  }}| j                  | d|d       | j                  | d|j                         d       t        | | d|        y )	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          u/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/mellum/modeling_mellum.pyr2   zMellumRotaryEmbedding.__init__6   s6   "("@"@$*$B$B!F$6$6 78** 	UJ++55jAK")4[)ADNN:&%)%I%IL~~j)Y624>>*3MN4@Yc4d1M1  J<y!9=UZ [  J</A!BMDWDWDYfk lDZL(:;=ST	U    Ndeviceztorch.deviceseq_lenr,   returnztorch.Tensorc                 z   | j                   |   d   }| j                   |   j                  dd      }t        | dd      xs | j                  | j                  z  }t        ||z        }d}d|t        j                  d|dt        j                        j                  |t        j                  	      |z  z  z  }	|	|fS )
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)rF   rO   )r9   getgetattrhidden_sizenum_attention_headsinttorcharangeint64tofloat)
r'   rF   rG   r,   baserK   rL   dimattention_factorr&   s
             rD   r:   z5MellumRotaryEmbedding.compute_default_rope_parametersK   s    . %%j1,? & 6 6z B F FG^`c d6:t4h8J8JfNhNh8h(223 U\\!S!5;;?BB&X]XcXcBdgjjk
 )))rE   c                 N   t        | | d      }t        | | d      }|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        |d	      5  |j                         |j                         z  j                  dd
      }	t        j                  |	|	fd      }
|
j                         |z  }|
j                         |z  }d d d        j	                  |j                        j	                  |j                        fS # 1 sw Y   AxY w)Nr-   r0   r   r"   mpscpuF)device_typeenabledrM   r[   rN   )rQ   rY   expandshaperX   rF   
isinstancetypestrr   	transposerU   catcossinrO   )r>   xposition_idsr,   r&   attention_scalinginv_freq_expandedposition_ids_expandedra   freqsembrk   rl   s                rD   forwardzMellumRotaryEmbedding.forwardp   sl    4J<y!9:#DZL8J*KL$T1d]399;BB<CUCUVWCXZ\^_`ccdedldlm ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	0&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')//C'')//C		0 vvAGGv$cff177f&;;;	0 	0s   *A1FF$)NNNNN)__name__
__module____qualname__rU   Tensor__annotations__r#   r2   staticmethodr   rT   rh   tuplerY   r:   no_gradr   rt   __classcell__rC   s   @rD   r%   r%   3   s    llU| U* &*+/"!%	"*t#"*("* t"* $J	"*
 
~u$	%"* "*H U]]_<  <rE   r%   RMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	MellumRMSNormepsrH   Nc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z<
        MellumRMSNorm is equivalent to T5LayerNorm
        N)r1   r2   r   	ParameterrU   onesweightvariance_epsilon)r>   rR   r   rC   s      rD   r2   zMellumRMSNorm.__init__   s1     	ll5::k#:; #rE   hidden_statesc                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )NrM   r^   T)keepdim)	rO   rX   rU   float32powmeanrsqrtr   r   )r>   r   input_dtypevariances       rD   rt   zMellumRMSNorm.forward   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::rE   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r|   r   re   r   )r>   s    rD   
extra_reprzMellumRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrE   )gư>)
rv   rw   rx   rY   r2   rU   ry   rt   r   r~   r   s   @rD   r   r      s7    $ $$ $;U\\ ;ell ;JrE   r   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..Nr^   rM   rc   )re   rU   rj   )rm   x1x2s      rD   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rE   rotary_pos_embc                     |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.
        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krk   rl   unsqueeze_dimq_embedk_embeds          rD   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGrE   r   n_reprH   c                     | 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)re   rd   reshape)r   r   batchnum_key_value_headsslenrL   s         rD   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTrE   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )NrM   r   r^   )r[   rO   )ptrainingr"   )r   num_key_value_groupsrU   matmulri   r   
functionalsoftmaxr   rX   rO   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               rD   eager_attention_forwardr      s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$rE   c                        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j                  dz  d	e
dz  d
ee   de	ej                  ej                  dz  f   fdZ xZS )MellumAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr'   	layer_idxc                 R   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                  |   dk(  r|j2                  | _        y d | _        y )NrL   g      Tbiasr   sliding_attention)r1   r2   r'   r   rQ   rR   rS   rL   r   r   r   attention_dropout	is_causalr   Linearattention_biasq_projk_projv_projo_projr   rms_norm_epsq_normk_normr8   sliding_windowr>   r'   r   rC   s      rD   r2   z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rE   Nr   position_embeddingsr   past_key_valuesr   rH   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        ||	||      \  }}	| |j                  |	|
| j                        \  }	}
t        j                  | j                  j                  t               } || ||	|
|f| j"                  sdn| j$                  | j&                  | j(                  d|\  }} |j*                  g |d j-                         }| j/                  |      }||fS )Nr^   r"   rM           )r   r   r   )re   rL   r   r   viewri   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   rk   rl   attention_interfacer   r   s                   rD   rt   z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&S#7jRUWZ#[ j&'6'='=j,X\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL..
%
 
%
!\ *k));;;;FFHkk+.L((rE   ru   )rv   rw   rx   __doc__r#   rT   r2   rU   ry   r|   r	   r   r   rt   r~   r   s   @rD   r   r      s    Gv| v v> )-')||') #5<<#=>') t+	')
 ') -.') 
u||U\\D00	1')rE   r   c                        e Zd ZdZ fdZdej                  dej                  dej                  dej                  fdZ xZS )MellumExpertsz2Collection of expert weights stored as 3D tensors.c                    t         |           |j                  | _        |j                  | _        |j
                  | _        t        j                  t        j                  | j                  d| j                  z  | j                              | _        t        j                  t        j                  | j                  | j                  | j                              | _        t        |j                     | _        y )NrM   )r1   r2   num_expertsrR   
hidden_dimmoe_intermediate_sizeintermediate_dimr   r   rU   emptygate_up_proj	down_projr   
hidden_actact_fnr>   r'   rC   s     rD   r2   zMellumExperts.__init__*  s    !-- ,, & < <LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../rE   r   top_k_indextop_k_weightsrH   c                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesrM   r"   r   )r^   rc   r^   )rU   
zeros_liker}   r   r   one_hotr   permutegreatersumnonzerowherelinearr   chunkr   r   
index_add_rX   rO   )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                 rD   rt   zMellumExperts.forward3  s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0)	rv   rw   rx   r   r2   rU   ry   rt   r~   r   s   @rD   r   r   &  sF    <0#||# \\# ||	#
 
#rE   r   c                   $     e Zd Z fdZd Z xZS )MellumTopKRouterc                 .   t         |           |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        j                  t        j                  | j                  | j                              | _        y ru   )r1   r2   num_experts_per_toktop_kr   norm_topk_probrR   r   r   r   rU   zerosr   r   s     rD   r2   zMellumTopKRouter.__init__O  si    //
!--$33 ,,ll5;;t/?/?#QRrE   c                    |j                  d| j                        }t        j                  || j                        }t
        j                  j                  j                  |t
        j                  d      }t        j                  || j                  d      \  }}| j                  r||j                  dd      z  }|j                  |j                        }|}|||fS )Nr^   )rO   r[   rc   T)r[   r   )r   r   Fr   r   rU   r   r   r   rY   topkr	  r
  r   rX   rO   )r>   r   router_logitsrouter_probsrouter_top_valuerouter_indicesrouter_scoress          rD   rt   zMellumTopKRouter.forwardW  s    %--b$//B<xx**22=Y[2\+0::lDJJTV+W(. 0 4 4T 4 JJ+..}/B/BC(m^;;rE   rv   rw   rx   r2   rt   r~   r   s   @rD   r  r  N  s    S	<rE   r  c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )MellumSparseMoeBlockr'   c                 b    t         |           t        |      | _        t	        |      | _        y ru   )r1   r2   r   expertsr  r  r   s     rD   r2   zMellumSparseMoeBlock.__init__d  s&    $V,$V,	rE   r   rH   c                     |j                   \  }}}|j                  d|      }| j                  |      \  }}}| j                  |||      }	|	j	                  |||      S )Nr^   )re   r   r  r  r   )
r>   r   
batch_sizesequence_lengthr   hidden_states_reshaped_routing_weightsselected_expertsr   s
             rD   rt   zMellumSparseMoeBlock.forwardi  si    2?2E2E/
OZ!.!3!3B
!C/3yy9O/P,?,"ll+ACSUde"**:
SSrE   )	rv   rw   rx   r#   r2   rU   ry   rt   r~   r   s   @rD   r  r  c  s-    -| -
TU\\ Tell TrE   r  c                   &     e Zd Zd fd	Zd Z xZS )	MellumMLPc                    t         |           || _        |j                  | _        ||j                  n|| _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFr   )r1   r2   r'   rR   intermediate_sizer   r   	gate_projup_projr   r   r   r   )r>   r'   r$  rC   s      rD   r2   zMellumMLP.__init__r  s    !--=N=V!9!9\m4#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../rE   c                     | j                  | j                  | j                  |            | j                  |      z        }|S ru   )r   r   r%  r&  )r>   rm   r   s      rD   rt   zMellumMLP.forward|  s6    NN4;;t~~a/@#ADLLQRO#ST	rE   ru   r  r   s   @rD   r!  r!  q  s    0rE   r!  c                       e Zd Zdedef fdZ	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
eej                  ej                  f   dz  dee   dej                  fdZ xZS )MellumDecoderLayerr'   r   c                 |   t         |           |j                  | _        t        ||      | _        |j
                  |   dk(  rt        |      | _        nt        ||j                        | _        t        |j                  |j                        | _        t        |j                  |j                        | _        y )Nsparse)r$  r   )r1   r2   rR   r   	self_attnmlp_layer_typesr  mlpr!  r$  r   r   input_layernormpost_attention_layernormr   s      rD   r2   zMellumDecoderLayer.__init__  s    !--(;!!),8+F3DH 6;S;STDH,V-?-?VEXEXY(5f6H6HfNaNa(b%rE   Nr   r   rn   r   	use_cacher   r   rH   c           
          |}| j                  |      } | j                  d||||||d|\  }}	||z   }|}| j                  |      }| j                  |      }||z   }|S )N)r   r   rn   r   r1  r    )r/  r,  r0  r.  )
r>   r   r   rn   r   r1  r   r   residualr  s
             rD   rt   zMellumDecoderLayer.forward  s     !,,];)4>> 
')%+ 3
 
q !=0 !55mD/ =0rE   )NNNFN)rv   rw   rx   r#   rT   r2   rU   ry   
LongTensorr	   boolr|   r   r   rt   r~   r   s   @rD   r)  r)    s    	c| 	c 	c /304(,!&HL|| t+ &&-	
  $; #5<<#=>E +, 
rE   r)  c                        e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZ eed      eedZ ej(                          fd	       Z xZS )
MellumPreTrainedModelr'   modelTr)  r   r   )index)r  r   
attentionsc                    t         |   |       | j                  j                  }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       n2t	        |t              r"t        j                  |j                  d|       t	        |t              r|j                  D ]  }|j                  }|j                  |   dk7  rt         |j                  |      } ||j                  |      \  }}t        j"                  t%        || d      |       t        j"                  t%        || d      |        y y )Nr   )r   stdr*   r+   r-   r/   )r1   _init_weightsr'   initializer_rangerf   r   initnormal_r   r   r  r   r%   r8   r:   r)   r   copy_rQ   )r>   r   r=  r,   r@   rA   r  rC   s          rD   r>  z#MellumPreTrainedModel._init_weights  s   f%kk++fm,LL,,3C@LL))= 01LLSc:f34$00 ^
%EE##J/9<#6v7G7G
7S#TL#/*#U q

76j\+CDmT

76j\9K+LM}]^ 5rE   )rv   rw   rx   r#   rz   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_outputsrU   r}   r>  r~   r   s   @rD   r8  r8    s{    &*#-.#4"5N!"&'(8B+% U]]_^ ^rE   r8  c                        e Zd Zdef fdZeee	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  d	edz  d
ee   defd                     Z xZS )MellumModelr'   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   r'   F)r1   r2   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrR   embed_tokens
ModuleListrangenum_hidden_layersr)  layersr   r   normr%   
rotary_embgradient_checkpointing	post_initr   s      rD   r2   zMellumModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdy	2d
 "&"4"4&:M:MN	/v>&+# 	 es   DN	input_idsr   rn   r   inputs_embedsr1  r   rH   c           	         |d u |d uz  rt        d      || j                  |      }|r|t        | j                        }|V||j	                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        |x}	t              sP| j                  ||||dfdfdd	}
i }	t        | j                  j                        D ]  } |
|          |	|<    |}i }t        | j                  j                        D ]  }| j                  |||      ||<    t        | j                   d | j                  j"                         D ]G  \  }} ||f|	| j                  j                  |      || j                  j                  |      ||d
|}I | j%                  |      }t'        ||r|      S d       S )Nz:You must specify exactly one of input_ids or inputs_embedsrP  r   r"   )rF   )r'   r_  r   r   rn   c                      t        di  S Nr3  )r   mask_kwargss   rD   <lambda>z%MellumModel.forward.<locals>.<lambda>	  s    *<*K{*K rE   c                      t        di  S rb  )r   rc  s   rD   re  z%MellumModel.forward.<locals>.<lambda>
  s    -N-]Q\-] rE   )full_attentionr   )r   r   rn   r   )last_hidden_stater   )
ValueErrorrU  r
   r'   get_seq_lengthrU   rV   re   rF   r   rf   dictr7   r8   r[  	enumeraterY  rX  rZ  r   )r>   r^  r   rn   r   r_  r1  r   past_seen_tokenscausal_mask_mappingmask_creation_functionsr,   r   r   idecoder_layerrd  s                   @rD   rt   zMellumModel.forward  s    -t";<YZZ  --i8M0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L?-F++!."0#2 ,K #L%]'# #%!$++"9"9: X
2U2I*2U2W#J/X & dkk556 	gJ.2oom\[e.f
+	g !*$++6U8U8U*V W 	A})24;;3J3J13MN$78O8OPQ8R$S) / M	 		-0%+/8O
 	
>B
 	
rE   )NNNNNN)rv   rw   rx   r#   r2   r   r!   r   rU   r5  ry   r	   FloatTensorr6  r   r   r   rt   r~   r   s   @rD   rN  rN    s    |     .2.204(,26!%<
##d*<
 t+<
 &&-	<

 <
 ((4/<
 $;<
 +,<
 
 <
    <
rE   rN  gate_logitsr   c                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    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   rc   r^   )rf   r|   rF   rU   rj   rX   r   r   r   r  r   r   rY   re   rd   r   r   r   )rs  r   r	  r   compute_device
layer_gateconcatenated_gate_logitsr  r  r  r   tokens_per_expertrouter_prob_per_expertr  r  rX  expert_attention_mask router_per_expert_attention_maskoverall_losss                      rD   load_balancing_loss_funcr}  '  s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUK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.1G1Q1QRS1TTUL+%%[ .ks   Ic                   N    e Zd ZddiZddiZddgdgfiZ fdZee	 	 	 	 	 	 	 	 	 dd	e	j                  dz  d
e	j                  dz  de	j                  dz  dedz  de	j                  dz  de	j                  dz  dedz  dedz  dee	j                  z  dee   defd              Z xZS )MellumForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _
        |j                  | _        | j                          y r#  )r1   r2   rN  r9  rS  r   r   rR   r  router_aux_loss_coefr   r  r]  r   s     rD   r2   zMellumForCausalLM.__init__  s      (
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	rE   Nr^  r   rn   r   r_  labelsr1  output_router_logitslogits_to_keepr   rH   c
                 j   ||n| j                   j                  } | j                  d|||||||d|
}|j                  }t	        |	t
              rt        |	 d      n|	}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |
}d}|rYt        |j                  | j                  | j                  |      }|+|| j                  |j                  |j                         z  z  }t#        ||||j$                  |j&                  |j(                  |j                        S )ar  
        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)r^  r   rn   r   r_  r1  r  )lossaux_lossr  r   r   r;  r  r3  )r'   r  r9  rh  rf   rT   slicer  loss_functionrS  r}  r  r   r  r  rX   rF   r   r   r   r;  )r>   r^  r   rn   r   r_  r  r1  r  r  r   outputsr   slice_indicesr  r  r  s                    rD   rt   zMellumForCausalLM.forward  sU   N %9$D $++JjJj 	
 +5$** 	+
)%+'!5	+
 	+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
rE   )	NNNNNNNNr   )rv   rw   rx   _tied_weights_keys_tp_plan_pp_planr2   r   r   rU   r5  ry   r	   rr  r6  rT   r   r   r   rt   r~   r   s   @rD   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
rE   r  )r  rN  r8  )r"   )r   )NrM   N)Lcollections.abcr   typingr   rU   torch.nn.functionalr   r   r   r   r@  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   ry   rT   r   rY   r   r   r   r  r  r!  r)  r8  rN  r|   r}  r  __all__r3  rE   rD   <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rE   