
    Z j                        S SK Jr  S SKJr  S SKrS SK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  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"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/J0r0  SSK1J2r2  \*Rf                  " \45      r5\" S5       " S S\Rl                  5      5       r7 " S S\Rl                  5      r8 " S S\Rl                  5      r9 " S S\Rl                  5      r: " S  S!\Rl                  5      r; " S" S#\Rl                  5      r<S$ r=\" S%5      SDS& j5       r>S'\R~                  S(\@S)\R~                  4S* jrA SES+\Rl                  S,\R~                  S-\R~                  S.\R~                  S/\R~                  S-  S0\BS1\BS2\%\'   4S3 jjrC " S4 S5\Rl                  5      rD " S6 S7\5      rE\( " S8 S9\#5      5       rF\( " S: S;\F5      5       rG   SFS<\R~                  \H\R~                     -  S-  S=\@S-  S/\R~                  S-  S)\R~                  \@-  4S> jjrI " S? S@\F\5      rJ " SA SB\\F5      rK/ SCQrLg)G    )Callable)OptionalN)nn)
functional   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hubuse_kernel_func_from_hub)create_causal_mask) GenericForSequenceClassificationGradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )JetMoeConfig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$ )JetMoeRMSNorm0   epsreturnNc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z,
JetMoeRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer'   	__class__s      {/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/jetmoe/modeling_jetmoe.pyr+   JetMoeRMSNorm.__init__2   s/     	ll5::k#:; #    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      -  $ )N   T)keepdim)	dtypetor-   float32powmeanrsqrtr0   r/   )r1   r7   input_dtypevariances       r4   forwardJetMoeRMSNorm.forward:   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r6   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler/   shaper0   )r1   s    r4   
extra_reprJetMoeRMSNorm.extra_reprA   s*    ))*+6$2G2G1HIIr6   )r0   r/   )gư>)__name__
__module____qualname____firstlineno__floatr+   r-   TensorrD   rI   __static_attributes____classcell__r3   s   @r4   r%   r%   0   sB    $ $$ $ $;U\\ ;ell ;J Jr6   r%   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )JetMoeRotaryEmbeddingE   inv_freqNconfigc                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultrW   F)
persistentoriginal_inv_freq)r*   r+   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrX   rope_parametersrZ   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r1   rX   devicerope_init_fnrW   r3   s        r4   r+   JetMoeRotaryEmbedding.__init__H   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuUr6   rf   ztorch.deviceseq_lenr(   ztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
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.
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head_dimNg      ?r   r9   r<   )rf   r<   )	ra   getattrr2   num_attention_headsr-   arangeint64r=   rO   )rX   rf   ri   basedimattention_factorrW   s          r4   rb   5JetMoeRotaryEmbedding.compute_default_rope_parametersX   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r6   c                 L   U R                   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                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r:   r!   mpscpuF)device_typeenabledr9   rs   rm   )rW   rO   expandrH   r=   rf   
isinstancetypestrr   	transposer-   catcosrc   sinr<   )
r1   xposition_idsinv_freq_expandedposition_ids_expandedry   freqsembr   r   s
             r4   rD   JetMoeRotaryEmbedding.forwardv   sN    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F#)rc   rX   r_   r`   rZ   NNNN)rK   rL   rM   rN   r-   rP   __annotations__r"   r+   staticmethodr   intrG   rO   rb   no_gradr   rD   rQ   rR   rS   s   @r4   rU   rU   E   s    llV| V V  &*+/"*t#*(* t* 
~u$	%	* *: ]]_<  <r6   rU   c                   B   ^  \ rS rSrS\S\S\SS4U 4S jjrS rS	rU =r$ )
JetMoeParallelExperts   num_experts
input_sizeoutput_sizer(   Nc                    > [         TU ]  5         [        R                  " [        R
                  " XU5      5      U l        Xl        X l        X0l	        g)aS  
Initialize the JetMoeParallelExperts module.
The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
[ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
[MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
used in vllm.

Args:
    num_experts (int):
        Number of experts.
    input_size (int):
        Size of the input.
    output_size (int):
        Size of the output.
N)
r*   r+   r   r,   r-   emptyr/   r   r   r   )r1   r   r   r   r3   s       r4   r+   JetMoeParallelExperts.__init__   s<    " 	ll5;;{#TU&$&r6   c                     UR                  USS9n/ n[        U R                  5       H8  nUR                  [        R
                  " X5   U R                  U   5      5        M:     [        R                  " USS9nU$ )z
Forward pass of the JetMoeParallelExperts module.

Args:
    inputs (Tensor):
        Input tensor.
    expert_size:
        Expert size information.

Returns:
    Tensor: Output tensor.
r   r{   )	splitranger   appendFlinearr/   r-   r   )r1   inputsexpert_size
input_listoutput_listiresultss          r4   rD   JetMoeParallelExperts.forward   sh     \\+1\5
t''(Aqxx
t{{1~FG )))KQ/r6   )r   r   r   r/   	rK   rL   rM   rN   r   r+   rD   rQ   rR   rS   s   @r4   r   r      s.    'C 'S 's 't '. r6   r   c                   >   ^  \ rS rSrS\S\S\4U 4S jjrS rSrU =r$ )JetMoeTopKGating   r   r   top_kc                 z   > [         TU ]  5         X l        Xl        X0l        [
        R                  " XSS9U l        g)z
Initialize the top-k gating mechanism.

Args:
    input_size (`int`):
        Size of the input.
    num_experts (`int`):
        Number of experts.
    top_k (`int`):
        Number of top experts to select.
FbiasN)r*   r+   r   r   r   r   Linearlayer)r1   r   r   r   r3   s       r4   r+   JetMoeTopKGating.__init__   s2     	&$
YYzUC
r6   c                 z   U R                  U5      R                  5       nUR                  U R                  SS9u  p4[        R
                  " USS9R                  U5      n[        R                  " UR                  S5      U R                  /UR                  UR                  S9nUR                  SUS5      nUR                  5       R                  S5      nUR                  5       nUR!                  5       n	U	R#                  S5      u  pUR%                  U R                  SS9nUR!                  5       nX[   nXXU4$ )Nr!   r{   r   r<   rf   trunc)rounding_mode)r   rO   topkr   r-   softmaxtype_aszerossizer   r<   rf   scatterlongsumtolistflattensortdiv)r1   r7   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr   top_k_experts_index_sorted_expertsbatch_indexbatch_gatess                 r4   rD   JetMoeTopKGating.forward   s"   M*002&,kk$**!k&D#mmLa8@@O a $"2"23;;L;LU`UgUg
 a2jjl&&q) "((* &--/"/"4"4Q"7*..tzz.Q "))+!7#+FRRr6   )r   r   r   r   r   rS   s   @r4   r   r      s-    D3 DS D D(S Sr6   r   c                   :   ^  \ rS rSrSrS\4U 4S jjrS rSrU =r	$ )	JetMoeMoE   z
A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

Args:
    config:
        Configuration object with model hyperparameters.
rX   c                 <  > [         TU ]  5         UR                  U l        UR                  U l        [
        UR                     U l        [        R                  R                  [        R                  " U R                  5      5      U l        [        UR                  U R                  U R                  S-  5      U l        [        UR                  U R                  U R                  5      U l        [#        U R                  UR                  UR$                  S9U l        g )Nr9   r   r   r   )r*   r+   r2   r   intermediate_sizer	   activation_function
activationr-   r   r,   r   r   r   num_local_expertsinput_linearoutput_linearr   num_experts_per_tokrouterr1   rX   r3   s     r4   r+   JetMoeMoE.__init__   s     ,,!33 !;!;<HH&&u{{4??'CD	1&2J2JDOO]a]m]mpq]qr263K3KTM]M]_c_n_no&00,,
r6   c                    UR                  5       u  p#nUR                  SU5      nU R                  U5      u  pVpxn	X   n
U R                  X5      nUR	                  SSS9nU R                  US   5      US   -  nU R                  X5      nXSS2S4   -  n[        R                  " X#-  U R                  4UR                  UR                  S9nUR                  SXm5      nUR                  X#U R                  5      nXR                  -   nU$ )z
Forward pass of the mixture of experts layer.

Args:
    layer_input (Tensor):
        Input tensor.

Returns:
    Tensor:
        Output tensor.
    Tensor:
        Router logits.
r:   r9   r{   r   r!   Nr   )r   reshaper   r   chunkr   r   r-   r   r   r<   rf   	index_addviewr   )r1   layer_inputbszlengthemb_sizer   r   r   r   router_logitsexpert_inputsr7   chunked_hidden_statesexpert_outputsr   layer_outputs                   r4   rD   JetMoeMoE.forward   s    !, 0 0 2X!))"h7BF++kBZ?-#0))-E - 3 3A2 3 >(=a(@ADYZ[D\\++MG'ag*>>S\4??;>CWCW`n`u`uvq+F#((dooF#ii/r6   )r   r   r2   r   r   r   r   )
rK   rL   rM   rN   __doc__r"   r+   rD   rQ   rR   rS   s   @r4   r   r      s    
| 
  r6   r   c                   F   ^  \ rS rSrSrS\4U 4S jjrS rS rS r	Sr
U =r$ )		JetMoeMoAi  z
A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.

Args:
    config:
        Configuration object with model hyperparameters.
rX   c                 d  > [         TU ]  5         UR                  U l        UR                  U l        UR                  UR                  -  U l        UR                  U l	        [        R                  R                  [        R                  " U R
                  5      5      U l        [        U R                  U R
                  U R                  5      U l        [        U R                  U R                  U R
                  5      U l        [%        U R
                  U R                  U R                  S9U l        g )Nr   )r*   r+   r   r   r2   r   kv_channelsnum_key_value_headsr   r   r-   r   r,   r   r   r   r   r   r   r   r   s     r4   r+   JetMoeMoA.__init__'  s    !33 ,,!--0J0JJ//
HH&&u{{4??'CD	1$2B2BDOOUYUeUef243C3CTEUEUW[WfWfg&((**
r6   c                    UR                  5       u  p#nUR                  SU5      nU R                  U5      u  pVpxn	XVXx4n
X   nU R                  X5      n[        R
                  " X#-  U R                  -  U R                  4UR                  UR                  S9nUR                  SX\5      nUR                  X#U R                  S5      nXU
4$ )zq
Map inputs to attention experts according to routing decision and compute query projection inside each experts.
r:   r   r   )r   r   r   r   r-   r   r   r2   r<   rf   r   r   )r1   r   r   r   r   r   r   r   r   r   	topo_infor   r   r   r   s                  r4   mapJetMoeMoA.map9  s     !, 0 0 2X!))"h7UYU`U`alUmR;])Q	 $0**=F \DJJ&(8(89AUAU^l^s^s
 q*>O#((djj"EI55r6   c                    UR                  5       u  p4pVUR                  SU5      nUu  pxpX   nU R                  X5      nXSS2S4   -  n[        R                  " X4-  U R
                  4UR                  UR                  S9nUR                  SX5      nUR                  X4U R
                  5      nXR                  -   nU$ )ze
Compute output projection inside each attention experts and merge the outputs of different experts.
r:   Nr   r   )r   r   r   r-   r   r   r<   rf   r   r   r   )r1   r   r   r   r   kr2   r   r   r   r   r   r   r   r   s                  r4   reduceJetMoeMoA.reduceP  s     '2&6&6&8#Q!))"k:FOC; $9++MG (ag*>> S\4??;>CWCW`n`u`uvq+F#((dooF#ii/r6   c                     [        S5      e)Nz-This module doesn't support call and forward.)NotImplementedError)r1   r   s     r4   rD   JetMoeMoA.forwardf  s    !"QRRr6   )r   r2   r   r   r   r   r   r   )rK   rL   rM   rN   r   r"   r+   r   r   rD   rQ   rR   rS   s   @r4   r   r     s*    
| 
$6.,S Sr6   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..Nr:   r9   r{   )rH   r-   r   )r   x1x2s      r4   rotate_halfr   j  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r6   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   )qr   r   r   unsqueeze_dimq_embedk_embeds          r4   apply_rotary_pos_embr  q  sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0Gr6   r7   n_repr(   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   r|   r   )r7   r	  batchr   slenrl   s         r4   	repeat_kvr    s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr6   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$ )Nr9   r   r:   )rs   r<   )ptrainingr!   )r  num_key_value_groupsr-   matmulr   r   r   r   r>   r=   r<   r  r  
contiguous)r  r  r  r  r  r  r  r  
key_statesvalue_statesattn_weightsattn_outputs               r4   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$$r6   c                     ^  \ rS rSrSrSS\S\S-  4U 4S jjjr   SS\R                  S\R                  S-  S	\R                  S-  S
\S-  S\\R                  \R                  S-  \\R                     S-  4   4
S jjrSrU =r$ )JetMoeAttentioni  z@
Multi-headed attention from 'Attention Is All You Need' paper.
NrX   	layer_idxc                 Z  > [         TU ]  5         Xl        X l        SU l        Uc-  [
        R                  SU R                  R                   S35        SU l	        UR                  U l        UR                  U l        UR                  UR                  -  U l        UR                  U l        UR                   U l        UR                  U l        U R$                  S-  U l        [)        U5      U l        [,        R.                  R1                  UR2                  U R                  S-  SS	9U l        g)
z
Initialize the JetMoeAttention module.

Args:
    config:
        Configuration object with model hyperparameters.
    layer_idx:
        Index of the layer in the model.
TNzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.r!   g      r9   Fr   )r*   r+   rX   r#  	is_causalloggerwarning_oncer3   rK   r  r   r   attention_dropoutr   r   kv_projection_sizero   	num_headsrl   r  r   expertsr-   r   r   r2   kv_projr1   rX   r#  r3   s      r4   r+   JetMoeAttention.__init__  s     	" !8!8 9 :, , %&!//
!'!9!9"("4"4v7Q7Q"Q#)#=#= 33**}}d* (xxv'9'94;R;RUV;V]bcr6   r7   r  position_embeddingspast_key_valuesr(   c                    UR                   S S n/ UQSPU R                  P7nU R                  R                  U5      u  pn
U R	                  U5      R                  SSS9u  pUR                  U5      R                  SS5      nUR                  U5      R                  SS5      nU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R!                  SU R"                  SS5      nUR!                  SU R"                  SS5      nU" U UUUU4U R$                  (       d  SOU R&                  U R(                  S.UD6u  nnUR                  " / UQU R"                  PSP76 nU R                  R+                  UU
5      nUR                  " / UQSP76 nUUU	4$ )Nr:   r9   r{   r!           )r  r  )rH   rl   r+  r   r,  r   r   r   r  updater#  r   get_interfacerX   _attn_implementationr   repeatr   r  r(  r  r   )r1   r7   r  r/  r0  r  input_shapehidden_shapequery_statesr   r   r  r  r   r   attention_interfacer  r  s                     r4   rD   JetMoeAttention.forward  s    $))#2.88b8$--8151A1A-1P.Y#'<<#>#D#DQB#D#O 
#((6@@AF__\2<<QB
#((6@@AF&#7RU#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
  &&q$**a;
#**1djj!Q?$7	%
  $}}C$2H2HLL	%
 	%
!\ "&&DDTZZDDll))+yA!&&88R8L-77r6   )r(  rX   r+  rl   r%  r,  r)  r#  r*  r  r   r  r   r   r   )rK   rL   rM   rN   r   r"   r   r+   r-   rP   
LongTensorr
   rG   rD   rQ   rR   rS   s   @r4   r"  r"    s    d| dd
 d dH /37;(,/8||/8 t+/8 #--4	/8
 /8 
u||U\\D0%2E2LL	M/8 /8r6   r"  c                     ^  \ rS rSrSS\S\S-  4U 4S j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$ )JetMoeDecoderLayeri  NrX   r#  c                    > [         TU ]  5         UR                  U l        [        U5      U l        [        UR                  5      U l        [        UR                  5      U l        [        X5      U l	        g r   )
r*   r+   r2   r   mlpr%   input_layernormpost_attention_layernormr"  self_attentionr-  s      r4   r+   JetMoeDecoderLayer.__init__	  s[    !--V$,V-?-?@(5f6H6H(I%-f@r6   r7   r  r   r0  	use_cacher/  r  r(   c           
          UnU R                  U5      nU R                  " SUUUUUUS.UD6u  n  n	X-   nUnU R                  U5      nU R                  U5      nX-   nU$ )N)r7   r  r   r0  rE  r/   )rA  rC  rB  r@  )
r1   r7   r  r   r0  rE  r/  r  residualr   s
             r4   rD   JetMoeDecoderLayer.forward  s     !,,];"11 
')%+ 3
 
q! !0 !55mD/ 0r6   )r2   rA  r@  rB  rC  r   )NNNFN)rK   rL   rM   rN   r"   r   r+   r-   rP   r<  r
   boolrG   r   r   rD   rQ   rR   rS   s   @r4   r>  r>    s    A| Ad
 A A /304(,!&HL|| t+ &&-	
  $; #5<<#=>E +, 
 r6   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
S	9/\\" \SS	9S.r\R*                  " 5       U 4S j5       rSrU =r$ )JetMoePreTrainedModeli1  rX   modelFr>  r0  Tr9   )index   r!   )r   r7   
attentionsc                 2  > [         TU ]  U5        [        U[        5      (       a5  [        R
                  " UR                  SU R                  R                  S9  g[        U[        [        -  5      (       a!  [        R                  " UR                  5        gg)zInitialize the weights.r2  )r@   stdN)r*   _init_weightsr}   r   initnormal_r/   rX   initializer_ranger   r   zeros_r   )r1   r  r3   s     r4   rS  #JetMoePreTrainedModel._init_weightsC  se     	f%f344LLSdkk6S6ST	I 566KK$ 7r6   rG  )rK   rL   rM   rN   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_outputsr-   r   rS  rQ   rR   rS   s   @r4   rL  rL  1  s    &+#-.#4"5N""&(BNScklDmn+$_A> ]]_% %r6   rL  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$ )JetMoeModeliM  rX   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(                  U l        U R+                  5         g s  snf )N)r'   rX   F)r*   r+   pad_token_idpadding_idx
vocab_sizer   	Embeddingr2   embed_tokens
ModuleListr   num_hidden_layersr>  layersr%   rms_norm_epsnormrU   
rotary_embgradient_checkpointingr5  	post_initr-  s      r4   r+   JetMoeModel.__init__O  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdDcy2Dcd
 "&"4"4&:M:MN	/v>&+#$*$?$?! 	 es   DN	input_idsr  r   r0  inputs_embedsrE  r  r(   c           
      B   US L US L-  (       a  [        S5      eU(       a  Uc  [        U R                  S9nUc  U R                  U5      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 R                  UUUUS9n	Un
U R                  X5      nU R                  S U R                  R                    H  nU" U
4UU	UUUS.UD6n
M     U R                  U
5      n
[        U
US9$ )	Nz:You must specify exactly one of input_ids or inputs_embedsrf  r   r!   )rf   )rX   rv  r  r0  r   )r/  r  r0  rE  r   )last_hidden_stater0  )
ValueErrorr   rX   rk  get_seq_lengthr-   rp   rH   rf   r  r   rq  rn  rm  rp  r   )r1   ru  r  r   r0  rv  rE  r  past_seen_tokenscausal_maskr7   r/  decoder_layers                r4   rD   JetMoeModel.forward`  sF    -t";<YZZ0*$++>O  --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L(;;')+%
 & #oomJ![[)H4;;+H+HIM)$7* /#) M J 		-0%++
 	
r6   )r5  rk  rr  rn  rp  rh  rq  ri  )NNNNNN)rK   rL   rM   rN   r"   r+   r   r    r   r-   r<  rP   r
   FloatTensorrJ  r   r   r   rD   rQ   rR   rS   s   @r4   rd  rd  M  s    | "   .2.204(,26!%5
##d*5
 t+5
 &&-	5

 5
 ((4/5
 $;5
 +,5
 
 5
    5
r6   rd  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   r{   r:   )r}   rG   rf   r-   r   r=   r   r   r   r   one_hotr@   rO   rH   r|   r   r   r  )r  r   r   r  compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr   selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthrm  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r4   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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\\R                  -  S\S-  S\4S jj5       5       rSrU =r$ )JetMoeForCausalLMi  zlm_head.weightzmodel.embed_tokens.weightc                 l  > [         TU ]  U5        [        U5      U l        UR                  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 )NFr   )r*   r+   rd  rM  ri  aux_loss_coefr   r   r2   lm_headtie_word_embeddingsr   r   r   rs  r   s     r4   r+   JetMoeForCausalLM.__init__  s      (
 ++#11yy!3!3V5F5FUS#)#=#= !33#)#=#=  	r6   Nru  r  r   r0  rv  labelsrE  logits_to_keepoutput_router_logitsr(   c
                 \   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                  " UU4SU R                  R                  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$ )N)ru  r  r   r0  rv  rE  r  ri  )lossaux_lossr   r0  r7   rP  r   rG  )rM  rx  r}   r   slicer  loss_functionrX   ri  r  r   r   r   r  r=   rf   r   r0  r7   rP  )r1   ru  r  r   r0  rv  r  rE  r  r  r  outputsr7   slice_indicesr   r  r  s                    r4   rD   JetMoeForCausalLM.forward  sN    +/** 	+
)%+'!5	+
 	+
  118B>SV8W8W~ot4]kmA}a,?@A%%  ;;11 	D /%%  ((	H !**X[[-EEE(#33!//))!//
 	
r6   )r  r  rM  r   r   r  ri  )	NNNNNNNr   F)rK   rL   rM   rN   _tied_weights_keysr+   r   r   r-   r<  rP   r
   r  rJ  r   r   rD   rQ   rR   rS   s   @r4   r  r    s    *,GH  .2.204(,26*.!%-.,19
##d*9
 t+9
 &&-	9

 9
 ((4/9
   4'9
 $;9
 ell*9
 #Tk9
 
#9
  9
r6   r  c                       \ rS rSrSrg)JetMoeForSequenceClassificationi;  rG  N)rK   rL   rM   rN   rQ   rG  r6   r4   r  r  ;  s    `cr6   r  )r  rd  rL  r  )r!   )r2  )Nr9   N)Mcollections.abcr   typingr   r-   r   torch.nnr   r    r   rT  activationsr	   cache_utilsr
   r   
generationr   integrationsr   r   masking_utilsr   modeling_layersr   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r   utils.output_capturingr   r    configuration_jetmoer"   
get_loggerrK   r&  Moduler%   rU   r   r   r   r   r   r  rP   r   r  rO   r   r"  r>  rL  rd  rG   r  r  r  __all__rG  r6   r4   <module>r     s  * %    $ & ! . ) Q / [ Q K F & R R G E . 
		H	% Y'JBII J (J(><BII ><B*BII *Z.Sryy .Sb7		 7tIS		 ISX( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2U8bii U8p&3 &R %O % %6 J
' J
 J
^ #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&dK
- K
\ d&FH] c kr6   