
    iF                        d dl mZ d dlmZ d dlZd dlmZ d dlmZ ddl	m
Z ddlmZ dd	lmZ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 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(m)Z)m*Z* ddl+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2  e*jf                  e4      Z5 ed       G d dejl                               Z7 G d dejl                        Z8 G d dejl                        Z9 G d dejl                        Z: G d  d!ejl                        Z; G d" d#ejl                        Z<d$ Z= ed%      dDd&       Z>d'ej~                  d(e@d)ej~                  fd*ZA	 dEd+ejl                  d,ej~                  d-ej~                  d.ej~                  d/ej~                  dz  d0eBd1eBd2e%e'   fd3ZC G d4 d5ejl                        ZD G d6 d7e      ZEe( G d8 d9e#             ZFe( G d: d;eF             ZG	 	 	 dFd<ej~                  eHej~                     z  dz  d=e@dz  d/ej~                  dz  d)ej~                  e@z  fd>ZI G d? d@eFe      ZJ G dA dBeeF      ZKg dCZLy)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                   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 )	JetMoeRMSNormepsreturnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z<
        JetMoeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizer&   	__class__s      f/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/models/jetmoe/modeling_jetmoe.pyr*   zJetMoeRMSNorm.__init__2   s1     	ll5::k#:; #    hidden_statesc                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor,   float32powmeanrsqrtr/   r.   )r0   r5   input_dtypevariances       r3   forwardzJetMoeRMSNorm.forward:   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r4   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler.   shaper/   )r0   s    r3   
extra_reprzJetMoeRMSNorm.extra_reprA   s*    ))*+6$2G2G1HIIr4   )gư>)
__name__
__module____qualname__floatr*   r,   TensorrB   rF   __classcell__r2   s   @r3   r%   r%   0   s7    $ $$ $;U\\ ;ell ;Jr4   r%   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )JetMoeRotaryEmbeddinginv_freqNconfigc                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultrP   F)
persistentoriginal_inv_freq)r)   r*   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrQ   rope_parametersrS   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r0   rQ   devicerope_init_fnrP   r2   s        r3   r*   zJetMoeRotaryEmbedding.__init__H   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr4   r_   ztorch.deviceseq_lenr'   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  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.
        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   r7   r:   )r_   r:   )	rZ   getattrr1   num_attention_headsr,   arangeint64r;   rJ   )rQ   r_   ra   basedimattention_factorrP   s          r3   r[   z5JetMoeRotaryEmbedding.compute_default_rope_parametersX   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r4   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r8   r!   mpscpuF)device_typeenabledr7   rk   re   )rP   rJ   expandrE   r;   r_   
isinstancetypestrr   	transposer,   catcosr\   sinr:   )
r0   xposition_idsinv_freq_expandedposition_ids_expandedrp   freqsembry   rz   s
             r3   rB   zJetMoeRotaryEmbedding.forwardv   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$N)NNN)rG   rH   rI   r,   rK   __annotations__r"   r*   staticmethodr   intrD   rJ   r[   no_gradr   rB   rL   rM   s   @r3   rO   rO   E   s    llV| V  &*+/"*t#*(* t* 
~u$	%	* *: U]]_<  <r4   rO   c                   6     e Zd Zdedededdf fdZd Z xZS )JetMoeParallelExpertsnum_experts
input_sizeoutput_sizer'   Nc                     t         |           t        j                  t	        j
                  |||            | _        || _        || _        || _	        y)a  
        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   )r0   r   r   r   r2   s       r3   r*   zJetMoeParallelExperts.__init__   sD    " 	ll5;;{K#TU&$&r4   c                     |j                  |d      }g }t        | j                        D ]7  }|j                  t	        j
                  ||   | j                  |                9 t        j                  |d      }|S )a  
        Forward pass of the JetMoeParallelExperts module.

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

        Returns:
            Tensor: Output tensor.
        r   rr   )	splitranger   appendFlinearr.   r,   rx   )r0   inputsexpert_size
input_listoutput_listiresultss          r3   rB   zJetMoeParallelExperts.forward   sq     \\+1\5
t''( 	HAqxx
1t{{1~FG	H))KQ/r4   rG   rH   rI   r   r*   rB   rL   rM   s   @r3   r   r      s)    'C 'S 's 't '.r4   r   c                   2     e Zd Zdededef fdZd Z xZS )JetMoeTopKGatingr   r   top_kc                     t         |           || _        || _        || _        t        j                  ||d      | _        y)a  
        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)r0   r   r   r   r2   s       r3   r*   zJetMoeTopKGating.__init__   s:     	&$
YYz;UC
r4   c                    | j                  |      j                         }|j                  | j                  d      \  }}t	        j
                  |d      j                  |      }t	        j                  |j                  d      | j                  g|j                  |j                        }|j                  d|d      }|j                         j                  d      }|j                         }|j!                         }	|	j#                  d      \  }
}|j%                  | j                  d      }|j!                         }||   }|||||fS )Nr!   rr   r   r:   r_   trunc)rounding_mode)r   rJ   topkr   r,   softmaxtype_aszerossizer   r:   r_   scatterlongsumtolistflattensortdiv)r0   r5   logitstop_k_logitstop_k_indicestop_k_gatesr   gatesr   top_k_experts_index_sorted_expertsbatch_indexbatch_gatess                 r3   rB   zJetMoeTopKGating.forward   s.   M*002&,kk$**!k&D#mmmLa8@@O a $"2"23;;L;LU`UgUg
 a2jjl&&q) "((* &--/"/"4"4Q"7*..tzz.Q "))+!"67#[+{FRRr4   r   rM   s   @r3   r   r      s'    D3 DS D D(Sr4   r   c                   .     e Zd ZdZdef fdZd Z xZS )	JetMoeMoEz
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    rQ   c                 @   t         |           |j                  | _        |j                  | _        t
        |j                     | _        t        j                  j                  t        j                  | j                              | _        t        |j                  | j                  | j                  dz        | _        t        |j                  | j                  | j                        | _        t#        | j                  |j                  |j$                        | _        y )Nr7   r   r   r   )r)   r*   r1   r   intermediate_sizer	   activation_function
activationr,   r   r+   r   r   r   num_local_expertsinput_linearoutput_linearr   num_experts_per_tokrouterr0   rQ   r2   s     r3   r*   z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,,
r4   c                 8   |j                         \  }}}|j                  d|      }| j                  |      \  }}}}}	||   }
| j                  |
|      }|j	                  dd      }| j                  |d         |d   z  }| j                  ||      }||dddf   z  }t        j                  ||z  | j                  f|j                  |j                        }|j                  d||      }|j                  ||| j                        }|| j                  z   }|S )a  
        Forward pass of the mixture of experts layer.

        Args:
            layer_input (Tensor):
                Input tensor.

        Returns:
            Tensor:
                Output tensor.
            Tensor:
                Router logits.
        r8   r7   rr   r   r!   Nr   )r   reshaper   r   chunkr   r   r,   r   r   r:   r_   	index_addviewr   )r0   layer_inputbszlengthemb_sizer   r   r   r   router_logitsexpert_inputsr5   chunked_hidden_statesexpert_outputsr   layer_outputs                   r3   rB   zJetMoeMoE.forward   s%    !, 0 0 2VX!))"h7BF++kBZ?;[-#K0))-E - 3 3A2 3 >(=a(@ADYZ[D\\++M;G'+ag*>>S6\4??;>CWCW`n`u`uvq+~F#((fdooF#dii/r4   )rG   rH   rI   __doc__r"   r*   rB   rL   rM   s   @r3   r   r      s    
| 
 r4   r   c                   :     e Zd ZdZdef fdZd Zd Zd Z xZ	S )	JetMoeMoAz
    A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    rQ   c                 h   t         |           |j                  | _        |j                  | _        |j                  |j                  z  | _        |j                  | _	        t        j                  j                  t        j                  | j
                              | _        t        | j                  | j
                  | j                        | _        t        | j                  | j                  | j
                        | _        t%        | j
                  | j                  | j                        | _        y )Nr   )r)   r*   r   r   r1   r   kv_channelsnum_key_value_headsr   r   r,   r   r+   r   r   r   r   r   r   r   r   s     r3   r*   zJetMoeMoA.__init__'  s    !33 ,,!--0J0JJ//
HH&&u{{4??'CD	1$2B2BDOOUYUeUef243C3CTEUEUW[WfWfg&((**
r4   c                    |j                         \  }}}|j                  d|      }| j                  |      \  }}}}}	||||f}
||   }| j                  ||      }t	        j
                  ||z  | j                  z  | j                  f|j                  |j                        }|j                  d||      }|j                  ||| j                  d      }||	|
fS )z
        Map inputs to attention experts according to routing decision and compute query projection inside each experts.
        r8   r   r   )r   r   r   r   r,   r   r   r1   r:   r_   r   r   )r0   r   r   r   r   r   r   r   r   r   	topo_infor   r   r   r   s                  r3   mapzJetMoeMoA.map9  s     !, 0 0 2VX!))"h7UYU`U`alUmRk;]);[Q	 $K0**=+F 6\DJJ&(8(89AUAU^l^s^s
 q*>O#((fdjj"E]I55r4   c                    |j                         \  }}}}|j                  d|      }|\  }}}	}
||   }| j                  ||
      }||	dddf   z  }t        j                  ||z  | j
                  f|j                  |j                        }|j                  d||      }|j                  ||| j
                        }|| j                  z   }|S )zu
        Compute output projection inside each attention experts and merge the outputs of different experts.
        r8   Nr   r   )r   r   r   r,   r   r   r:   r_   r   r   r   )r0   r   r   r   r   kr1   r   r   r   r   r   r   r   r   s                  r3   reducezJetMoeMoA.reduceP  s     '2&6&6&8#VQ!))"k:FOCk; $$89++M;G (+ag*>> S6\4??;>CWCW`n`u`uvq+~F#((fdooF#dii/r4   c                     t        d      )Nz-This module doesn't support call and forward.)NotImplementedError)r0   r   s     r3   rB   zJetMoeMoA.forwardf  s    !"QRRr4   )
rG   rH   rI   r   r"   r*   r   r   rB   rL   rM   s   @r3   r   r     s$    
| 
$6.,Sr4   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..Nr8   r7   rr   )rE   r,   rx   )r{   x1x2s      r3   rotate_halfr   j  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r4   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   )qr   ry   rz   unsqueeze_dimq_embedk_embeds          r3   apply_rotary_pos_embr   q  sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr4   r5   n_repr'   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   rs   r   )r5   r   batchr   slenrd   s         r3   	repeat_kvr     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr4   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 )Nr7   r   r8   )rk   r:   )ptrainingr!   )r   num_key_value_groupsr,   matmulrw   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               r3   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$$r4   c                        e Zd ZdZddededz  f fdZ	 	 	 	 ddej                  dej                  dz  dej                  dz  d	e
dz  d
ej                  dz  deej                  ej                  dz  eej                     dz  f   fdZ xZS )JetMoeAttentionzH
    Multi-headed attention from 'Attention Is All You Need' paper.
    NrQ   	layer_idxc                 b   t         |           || _        || _        d| _        |-t
        j                  d| j                  j                   d       d| _	        |j                  | _        |j                  | _        |j                  |j                  z  | _        |j                  | _        |j                   | _        |j                  | _        | j$                  dz  | _        t)        |      | _        t,        j.                  j1                  |j2                  | j                  dz  d	      | _        y)
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      r7   Fr   )r)   r*   rQ   r  	is_causalloggerwarning_oncer2   rG   r  r   r   attention_dropoutr   r   kv_projection_sizerg   	num_headsrd   r   r   expertsr,   r   r   r1   kv_projr0   rQ   r  r2   s      r3   r*   zJetMoeAttention.__init__  s    	" !8!8 9 :, , %&!//
!'!9!9"("4"4v7Q7Q"Q#)#=#= 33**}}d* (xxv'9'94;R;RUV;V]bcr4   r5   r   position_embeddingspast_key_valuescache_positionr'   c                    |j                   d d }g |d| j                  }| j                  j                  |      \  }	}
}| j	                  |      j                  dd      \  }}|	j                  |      j                  dd      }	|j                  |      j                  dd      }|j                  |      j                  dd      }|\  }}t        |	|||      \  }	}|'|||d}|j                  ||| j                  |      \  }}t        j                  | j                  j                  t              }|j!                  d| j"                  dd      }|j!                  d| j"                  dd      } || |	|||f| j$                  sdn| j&                  | j(                  d|\  }} |j                  g || j"                  d }| j                  j+                  ||      } |j                  g |d }|||
fS )Nr8   r7   rr   r!   )rz   ry   r          )r   r   )rE   rd   r  r   r  r   r   rw   r   updater  r   get_interfacerQ   _attn_implementationr  repeatr   r   r  r   r   )r0   r5   r   r  r  r  r   input_shapehidden_shapequery_statesr   r   r  r  ry   rz   cache_kwargsattention_interfacer  r  s                       r3   rB   zJetMoeAttention.forward  s    $))#2.88b8$--8151A1A-1P.mY#'<<#>#D#DQB#D#O 
L#((6@@AF__\2<<QB
#((6@@AF&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
  &&q$**a;
#**1djj!Q?$7	%
  $}}C$2H2HLL	%
 	%
!\ 'k&&DDTZZDDll))+yA&k&&88R8L-77r4   r   )NNNN)rG   rH   rI   r   r"   r   r*   r,   rK   
LongTensorr
   rD   rB   rL   rM   s   @r3   r
  r
    s    d| dd
 dH /37;(,2628||28 t+28 #--4	28
 28 ((4/28 
u||U\\D0%2E2LL	M28r4   r
  c                   *    e Zd Zddededz  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j                  dz  deej                  ej                  f   dz  dee   dej                  fdZ xZS )JetMoeDecoderLayerNrQ   r  c                     t         |           |j                  | _        t        |      | _        t        |j                        | _        t        |j                        | _        t        ||      | _	        y r   )
r)   r*   r1   r   mlpr%   input_layernormpost_attention_layernormr
  self_attentionr  s      r3   r*   zJetMoeDecoderLayer.__init__  s]    !--V$,V-?-?@(5f6H6H(I%-fi@r4   r5   r   r|   r  	use_cacher  r  r   r'   c                     |}	| j                  |      } | j                  d|||||||d|\  }}
}
|	|z   }|}	| j                  |      }| j                  |      }|	|z   }|S )N)r5   r   r|   r  r,  r  r   )r)  r+  r*  r(  )r0   r5   r   r|   r  r,  r  r  r   residualr   s              r3   rB   zJetMoeDecoderLayer.forward  s     !,,];1d11 	
')%+) 3	
 	
q! !=0 !55mD/ =0r4   r   )NNNFNN)rG   rH   rI   r"   r   r*   r,   rK   r$  r
   boolrD   r   r   rB   rL   rM   s   @r3   r&  r&    s    A| Ad
 A /304(,!&26HL|| t+ &&-	
  $; ((4/ #5<<#=>E +, 
r4   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	      ge eed
      dZ ej(                          fd       Z xZS )JetMoePreTrainedModelrQ   modelFr&  r  Tr7   )index   r!   )r   r5   
attentionsc                     t         |   |       t        |t              r7t	        j
                  |j                  d| j                  j                         yt        |t        t        z        r t	        j                  |j                         yy)zInitialize the weights.r  )r>   stdN)r)   _init_weightsrt   r   initnormal_r.   rQ   initializer_ranger   r   zeros_r   )r0   r   r2   s     r3   r9  z#JetMoePreTrainedModel._init_weightsH  s_     	f%f34LLSdkk6S6ST	I 56KK$ 7r4   )rG   rH   rI   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   r9  rL   rM   s   @r3   r2  r2  6  s    &+#-.#4"5N""&(BNScklDmn+$_A> U]]_% %r4   r2  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j                  dz  dee   defd                     Z xZS )JetMoeModelrQ   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(                  | _        | j+                          y c c}w )N)r&   rQ   F)r)   r*   pad_token_idpadding_idx
vocab_sizer   	Embeddingr1   embed_tokens
ModuleListr   num_hidden_layersr&  layersr%   rms_norm_epsnormrO   
rotary_embgradient_checkpointingr  	post_initr  s      r3   r*   zJetMoeModel.__init__T  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdy	2d
 "&"4"4&:M:MN	/v>&+#$*$?$?! 	 es   DN	input_idsr   r|   r  inputs_embedsr,  r  r   r'   c                 D   |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|F||j	                         nd}	t        j                  |	|	|j                  d   z   |j                        }||j                  d      }t        | j                  |||||      }
|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f||
||||d|} | j                  |      }t        ||      S )	Nz:You must specify exactly one of input_ids or inputs_embedsrK  r   r!   )r_   )rQ   rZ  r   r  r  r|   )r  r   r  r,  r  r|   )last_hidden_stater  )
ValueErrorr   rQ   rP  get_seq_lengthr,   rh   rE   r_   r   r   rV  rS  rR  rU  r   )r0   rY  r   r|   r  rZ  r,  r  r   past_seen_tokenscausal_maskr5   r  decoder_layers                 r3   rB   zJetMoeModel.forwarde  s`    -t";<YZZ0*$++>O  --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L(;;'))+%
 & #oom\J![[)H4;;+H+HI 
	M)	$7* /#-)	 	M
	 		-0%++
 	
r4   )NNNNNNN)rG   rH   rI   r"   r*   r   r    r   r,   r$  rK   r
   FloatTensorr0  r   r   r   rB   rL   rM   s   @r3   rI  rI  R  s    | "   .2.204(,26!%26;
##d*;
 t+;
 &&-	;

 ;
 ((4/;
 $;;
 ((4/;
 +,;
 
 ;
    ;
r4   rI  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   rr   r8   )rt   rD   r_   r,   rx   r;   r   r   r   r   one_hotr>   rJ   rE   rs   r   r   r   )rc  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_lengthrR  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r3   load_balancing_loss_funcrs    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                   L    e Zd Zdd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j                  dz  deej                  z  dedz  defd              Z xZS )JetMoeForCausalLMzlm_head.weightzmodel.embed_tokens.weightc                 p   t         |   |       t        |      | _        |j                  | _        |j
                  | _        t        j                  |j                  |j                  d      | _	        |j                  | _
        |j                  | _        |j                  | _        | j                          y )NFr   )r)   r*   rI  r3  rN  aux_loss_coefr   r   r1   lm_headtie_word_embeddingsr   r   r   rX  r   s     r3   r*   zJetMoeForCausalLM.__init__  s      (
 ++#11yy!3!3V5F5FUS#)#=#= !33#)#=#=  	r4   NrY  r   r|   r  rZ  labelsr,  r  logits_to_keepoutput_router_logitsr'   c                 N    | j                   d||||||||
d|}|j                  }t        |	t              rt	        |	 d       n|	}| j                  |d d |d d f         }d }|* | j                  ||fd| j                  j                  i|}d }|
rYt        |j                  | j                  | j                  |      }|+|| j                  |j                  |j                        z  z  }t!        ||||j"                  |j$                  |j&                  |j                        S )N)rY  r   r|   r  rZ  r,  r  r|  rN  )lossaux_lossr   r  r5   r6  r   r.  )r3  r\  rt   r   slicerx  loss_functionrQ   rN  rs  r   r   r   rw  r;   r_   r   r  r5   r6  )r0   rY  r   r|   r  rZ  rz  r,  r  r{  r|  r   outputsr5   slice_indicesr   r~  r  s                     r3   rB   zJetMoeForCausalLM.forward  sT     +5$** 
+
)%+')!5
+
 
+
  118B>SV8W~ot4]kmA}a,?@A%4%%  ;;11 	D /%%  ((	H !**X[[-EEE(#33!//))!//
 	
r4   )
NNNNNNNNr   F)rG   rH   rI   _tied_weights_keysr*   r   r   r,   r$  rK   r
   rb  r0  r   r   rB   rL   rM   s   @r3   ru  ru    s   *,GH  .2.204(,26*.!%26-.,1;
##d*;
 t+;
 &&-	;

 ;
 ((4/;
   4';
 $;;
 ((4/;
 ell*;
 #Tk;
 
#;
  ;
r4   ru  c                       e Zd Zy)JetMoeForSequenceClassificationN)rG   rH   rI   r.  r4   r3   r  r  H  s    r4   r  )ru  rI  r2  r  )r!   )r  )Nr7   N)Mcollections.abcr   typingr   r,   r   torch.nnr   r    r   r:  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_loggerrG   r  Moduler%   rO   r   r   r   r   r   r   rK   r   r   rJ   r  r
  r&  r2  rI  rD   rs  ru  r  __all__r.  r4   r3   <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'% % % '(%2X8bii X8v(3 (V %O % %6 P
' P
 P
j #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&dM
- M
` d&FH] c kr4   