
    Z jx                        S SK Jr  S SKJr  S SKrS SKJs  Jr  S SKJr  SSK	J
r  SSKJr  SSKJrJr  SS	KJr  SS
KJrJrJrJr  SSKJr  SSKJr  SSKJrJr  SSKJ r J!r!  SSK"J#r#J$r$  SSK%J&r&  SSK'J(r(J)r)J*r*  SSK+J,r,J-r-  SSK.J/r/J0r0  SSK1J2r2  \" S5       " S S\Rf                  5      5       r4 " S S\Rf                  5      r5 " S S\Rf                  5      r6S r7\" S5      SAS j5       r8S \Rr                  S!\:S"\Rr                  4S# jr; SBS$\Rf                  S%\Rr                  S&\Rr                  S'\Rr                  S(\Rr                  S-  S)\<S*\<S+\&\(   4S, jjr=\" \85       " S- S.\Rf                  5      5       r>\ " S/ S0\Rf                  5      5       r? " S1 S2\Rf                  5      r@ " S3 S4\Rf                  5      rA " S5 S6\5      rB\) " S7 S8\$5      5       rC\) " S9 S:\C5      5       rD   SCS;\Rr                  \E\Rr                     -  S-  S<\:S-  S(\Rr                  S-  S"\Rr                  \:-  4S= jjrF\) " S> S?\C\5      5       rG/ S@QrHg)D    )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)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )OlmoeConfigRMSNormc                   p   ^  \ rS rSrSS	U 4S jjjrS\R                  S\R                  4S jrS rSr	U =r
$ )
OlmoeRMSNorm0   returnc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z+
OlmoeRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      y/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/olmoe/modeling_olmoe.pyr)   OlmoeRMSNorm.__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rsqrtr.   r-   )r/   r6   input_dtypevariances       r3   forwardOlmoeRMSNorm.forward:   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r5   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler-   shaper.   )r/   s    r3   
extra_reprOlmoeRMSNorm.extra_reprA   s*    ))*+6$2G2G1HIIr5   )r.   r-   )gh㈵>)r&   N)__name__
__module____qualname____firstlineno__r)   r+   TensorrC   rH   __static_attributes____classcell__r2   s   @r3   r$   r$   0   s4    $ $;U\\ ;ell ;J Jr5   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$ )OlmoeRotaryEmbeddingE   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defaultrU   F)
persistentoriginal_inv_freq)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrV   rope_parametersrX   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r/   rV   devicerope_init_fnrU   r2   s        r3   r)   OlmoeRotaryEmbedding.__init__H   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuUr5   rd   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   r8   r;   )rd   r;   )	r_   getattrr0   num_attention_headsr+   arangeint64r<   float)rV   rd   rg   basedimattention_factorrU   s          r3   r`   4OlmoeRotaryEmbedding.compute_default_rope_parametersX   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r5   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   r9   r    mpscpuF)device_typeenabledr8   rr   rk   )rU   rp   expandrG   r<   rd   
isinstancetypestrr   	transposer+   catcosra   sinr;   )
r/   xposition_idsinv_freq_expandedposition_ids_expandedrx   freqsembr   r   s
             r3   rC   OlmoeRotaryEmbedding.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#)ra   rV   r]   r^   rX   N)NNN)rJ   rK   rL   rM   r+   rN   __annotations__r!   r)   staticmethodr   intrF   rp   r`   no_gradr   rC   rO   rP   rQ   s   @r3   rS   rS   E   s    llV{ V V  %)+/"*d"*(* t* 
~u$	%	* *: ]]_<  <r5   rS   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )OlmoeMLP   c                   > [         TU ]  5         Xl        UR                  U l        UR                  U l        [
        R                  " U R                  U R                  SS9U l        [
        R                  " U R                  U R                  SS9U l        [
        R                  " U R                  U R                  SS9U l	        [        UR                     U l        g NFbias)r(   r)   rV   r0   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnr/   rV   r2   s     r3   r)   OlmoeMLP.__init__   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r5   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ r   )r   r   r   r   )r/   r   r   s      r3   rC   OlmoeMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r5   )r   rV   r   r   r0   r   r   rJ   rK   rL   rM   r)   rC   rO   rP   rQ   s   @r3   r   r      s    0 r5   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..Nr9   r8   rz   )rG   r+   r   )r   x1x2s      r3   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r5   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  Applies Rotary Position Embedding to the query and key tensors.

Args:
    q (`torch.Tensor`): The query tensor.
    k (`torch.Tensor`): The key tensor.
    cos (`torch.Tensor`): The cosine part of the rotary embedding.
    sin (`torch.Tensor`): The sine part of the rotary embedding.
    unsqueeze_dim (`int`, *optional*, defaults to 1):
        The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
        sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
        that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
        k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
        cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
        the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
    `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
)	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r3   apply_rotary_pos_embr      sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0Gr5   r6   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)rG   r{   reshape)r6   r   batchnum_key_value_headsslenrj   s         r3   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr5   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$ )Nr8   r   r9   )rr   r;   )ptrainingr    )r   num_key_value_groupsr+   matmulr   r   
functionalsoftmaxr=   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U$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r5   c                   0  ^  \ rS rSrSrSS\S\S-  4U 4S jjjr SS\R                  S\
\R                  \R                  4   S	\R                  S-  S
\S-  S\\   S\
\R                  \R                  S-  \
\R                     S-  4   4S jjrSrU =r$ )OlmoeAttention   z=Multi-headed attention from 'Attention Is All You Need' paperNrV   	layer_idxc                   > [         TU ]  5         Xl        X l        [	        USUR
                  UR                  -  5      U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        SU l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR                  U R                  -  UR
                  UR                  S9U l        [)        UR
                  UR*                  S9U l        [)        UR
                  UR                  -  UR                  -  UR*                  S9U l        g )Nrj   g      Tr   r1   )r(   r)   rV   r   rl   r0   rm   rj   r   r   r   attention_dropout	is_causalr   r   attention_biasq_projk_projv_projo_projr$   rms_norm_epsq_normk_normr/   rV   r   r2   s      r3   r)   OlmoeAttention.__init__   s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
 #6#5#56;N;NO"6#=#==A[A[[agatat
r5   r6   position_embeddingsr   past_key_valuesr   r&   c           
         UR                   S S n/ UQSPU R                  P7nU R                  U R                  U5      5      nU R	                  U R                  U5      5      n	U R                  U5      n
U R                  R                  b  UR                  U R                  R                  * U R                  R                  S9  U	R                  U R                  R                  * U R                  R                  S9  U
R                  U R                  R                  * U R                  R                  S9  UR                  " U6 R                  SS5      nU	R                  " U6 R                  SS5      n	U
R                  " U6 R                  SS5      n
Uu  p[        XX5      u  pUb  UR                  XU R                  5      u  p[        R                   " U R                  R"                  [$        5      nU" U UU	U
U4U R&                  (       d  SOU R(                  U R*                  [-        U R                  SS 5      S.UD6u  pUR.                  " / UQSP76 R1                  5       nU R3                  U5      nX4$ )Nr9   )minmaxr    r8           sliding_window)r   r   r   )rG   rj   r   r   r   r   r   rV   clip_qkvclamp_viewr   r   updater   r   get_interface_attn_implementationr   r   r   r   rl   r   r   r   )r/   r6   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   attention_interfacer   r   s                   r3   rC   OlmoeAttention.forward   s9    $))#2.88b8$--8{{4;;}#=>[[]!;<
{{=1;;+T[[%9%9$9t{{?S?ST4;;#7#7"7T[[=Q=QRT[[%9%9$9t{{?S?ST#((,7AA!QG__l3==aC
#((,7AA!QG&#7RU#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
! "));;;;FFHkk+.((r5   )r   rV   rj   r   r   r   r   r   r   r   r   r   r   r   )rJ   rK   rL   rM   __doc__r!   r   r)   r+   rN   rF   r	   r   r   rC   rO   rP   rQ   s   @r3   r   r      s    G
{ 
sTz 
 
@ )-/)||/) #5<<#=>/) t+	/)
 /) +,/) 
u||U\\D0%2E2LL	M/) /)r5   r   c                      ^  \ rS rSrSrS\4U 4S jjrS\R                  S\R                  S\R                  S\R                  4S	 jr	S
r
U =r$ )OlmoeExpertsi-  z2Collection of expert weights stored as 3D tensors.rV   c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        [        R                  " [        R                  " U R                  SU R                  -  U R
                  5      5      U l        [        R                  " [        R                  " U R                  U R
                  U R                  5      5      U l        [        UR                     U l        g )Nr8   )r(   r)   num_local_expertsnum_expertsr0   
hidden_dimr   intermediate_dimr   r*   r+   emptygate_up_projr   r   r   r   r   s     r3   r)   OlmoeExperts.__init__1  s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r5   r6   top_k_indextop_k_weightsr&   c                 X   [         R                  " U5      n[         R                  " 5          [         R                  R                  R                  X R                  S9nUR                  SSS5      n[         R                  " UR                  SS9S5      R                  5       nS S S 5        W H  nUS   nXpR                  :X  a  M  [         R                  " WU   5      u  pX   n
[        R                  R                  XR                  U   5      R                  SSS9u  pU R                  U5      U-  n[        R                  R                  XR                   U   5      nXXS 4   -  nUR#                  SXR%                  UR&                  5      5        M     U$ ! , (       d  f       N= f)N)num_classesr8   r    r   )r9   rz   r9   )r+   
zeros_liker   r   r   one_hotr   permutegreatersumnonzerowherelinearr   chunkr   r   
index_add_r<   r;   )r/   r6   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r3   rC   OlmoeExperts.forward:  so    $..}=]]_((--55kO_O_5`K%--aA6K{8'DaHPPRJ 
 %J#AJ---#(;;{:/F#G I)4M}}++M;L;LZ;XY__`agi_jHD$(KK$5$:!$&MM$8$89NP^P^_iPj$k!$9)`dJd<e$e!**1i9Q9QReRkRk9lm % #"# _s   A7F
F))r   r   r   r   r   r   )rJ   rK   rL   rM   r   r!   r)   r+   rN   rC   rO   rP   rQ   s   @r3   r   r   -  sR    <0{ 0#||# \\# ||	#
 
# #r5   r   c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )OlmoeTopKRouteriU  c                 2  > [         TU ]  5         UR                  U l        UR                  U l        UR
                  U l        UR                  U l        [        R                  " [        R                  " U R                  U R                  5      5      U l        g r   )r(   r)   num_experts_per_toktop_kr   norm_topk_probr0   r   r   r*   r+   zerosr-   r   s     r3   r)   OlmoeTopKRouter.__init__V  si    //
!--$33 ,,ll5;;t/?/?#QRr5   c                    UR                  SU R                  5      n[        R                  " XR                  5      n[
        R                  R                  R                  U[
        R                  SS9n[
        R                  " X0R                  SS9u  pEU R                  (       a  XDR                  SSS9-  nUR                  UR                  5      nUnX&U4$ )Nr9   )r;   rr   rz   T)rr   r:   )r   r   Fr  r-   r+   r   r   r   rp   topkr  r  r  r<   r;   )r/   r6   router_logitsrouter_probsrouter_top_valuerouter_indicesrouter_scoress          r3   rC   OlmoeTopKRouter.forward^  s    %--b$//B<xx**22=Y[2\+0::lJJTV+W( 4 4T 4 JJ+..}/B/BC(^;;r5   )r   r  r   r  r-   r   rQ   s   @r3   r  r  U  s    S	< 	<r5   r  c                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )OlmoeSparseMoeBlockij  c                 b   > [         TU ]  5         [        U5      U l        [	        U5      U l        g r   )r(   r)   r  r  r   expertsr   s     r3   r)   OlmoeSparseMoeBlock.__init__k  s&    #F+	#F+r5   r6   r&   c                     UR                   u  p#nUR                  SU5      nU R                  U5      u  pVnU R                  XU5      R	                  X#U5      nU$ )Nr9   )rG   r   r  r(  r   )	r/   r6   
batch_sizesequence_lengthr   _r   r   r	  s	            r3   rC   OlmoeSparseMoeBlock.forwardp  s`    2?2E2E/
Z%**2z:(,		-(@%+"ll=}U]]
 #"r5   )r(  r  )
rJ   rK   rL   rM   r)   r+   rN   rC   rO   rP   rQ   s   @r3   r&  r&  j  s(    ,
#U\\ #ell # #r5   r&  c                     ^  \ rS rSrS\S\4U 4S jjr     SS\R                  S\R                  S-  S\R                  S-  S	\
S-  S
\S-  S\\R                  \R                  4   S-  S\\   S\R                  4S jjrSrU =r$ )OlmoeDecoderLayeriz  rV   r   c                   > [         TU ]  5         UR                  U l        [        XS9U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        g )N)rV   r   r   )r(   r)   r0   r   	self_attnr&  mlpr$   r   input_layernormpost_attention_layernormr   s      r3   r)   OlmoeDecoderLayer.__init__{  sj    !--'vK&v.+F,>,>FDWDWX(4V5G5GVM`M`(a%r5   Nr6   r   r   r   	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  pX-   nUnU R                  U5      nU R                  U5      nX-   nU$ )N)r6   r   r   r   r7  r    )r4  r2  r5  r3  )
r/   r6   r   r   r   r7  r   r   residualr-  s
             r3   rC   OlmoeDecoderLayer.forward  s     !,,];>> 
')%+ 3
 
 !0 !55mD/ 0r5   )r0   r4  r3  r5  r2  )NNNFN)rJ   rK   rL   rM   r!   r   r)   r+   rN   
LongTensorr	   boolrF   r   r   rC   rO   rP   rQ   s   @r3   r0  r0  z  s    b{ bs b /304(,!&HL|| t+ &&-	
  $; #5<<#=>E +, 
 r5   r0  c                       \ rS rSr% \\S'   SrSrS/rS/r	Sr
Sr\" \SS9\\S	.rSr\R&                  " 5       S
 5       rSrg)OlmoePreTrainedModeli  rV   modelTr0  r   r   )index)r  r6   
attentionsc                    [         R                  " X5        [        U[        5      (       ai  [        R
                  " UR                  SU R                  R                  S9  [        R
                  " UR                  SU R                  R                  S9  g [        U[        5      (       a5  [        R
                  " UR                  SU R                  R                  S9  g g )Nr   )r?   std)r   _init_weightsr|   r   initnormal_r   rV   initializer_ranger   r  r-   )r/   r   s     r3   rE  "OlmoePreTrainedModel._init_weights  s    %%d3fl++LL,,3DKK<Y<YZLL))9V9VW00LLSdkk6S6ST 1r5   r9  N)rJ   rK   rL   rM   r!   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpar   r  r0  r   _can_record_outputs_supports_attention_backendr+   r   rE  rO   r9  r5   r3   r?  r?    sk    &*#,-#4"5N'qA*$ #'
]]_U Ur5   r?  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$ )
OlmoeModeli  rV   c           	        > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [
        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        [        UR                  UR                  S9U l        [#        US9U l        SU l        U R)                  5         g s  snf )Nr   rV   F)r(   r)   pad_token_idpadding_idx
vocab_sizer   	Embeddingr0   embed_tokens
ModuleListrangenum_hidden_layersr0  layersr$   r   normrS   
rotary_embgradient_checkpointing	post_initr   s      r3   r)   OlmoeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammCHIaIaCbcCbiv1Cbc
 !!3!39L9LM	.f=&+# 	 ds   C?N	input_idsr   r   r   inputs_embedsr7  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_embedsrU  r   r    )rd   )rV   re  r   r   r   )r   r   r   r   r7  )last_hidden_stater   )
ValueErrorr
   rV   rZ  get_seq_lengthr+   rn   rG   rd   r   r   r`  r^  r]  r_  r   )r/   rd  r   r   r   re  r7  r   past_seen_tokenscausal_maskr6   r   decoder_layers                r3   rC   OlmoeModel.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%++
 	
r5   )rZ  ra  r^  r_  rW  r`  rX  )NNNNNN)rJ   rK   rL   rM   r!   r)   r   r   r   r+   r<  rN   r	   FloatTensorr=  r   r   r   rC   rO   rP   rQ   s   @r3   rS  rS    s    {    .2.204(,26!%5
##d*5
 t+5
 &&-	5

 5
 ((4/5
 $;5
 +,5
 
 5
    5
r5   rS  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   rz   r9   )r|   rF   rd   r+   r   r<   r   r   r   r  r   r?   rp   rG   r{   r   r  r   )ro  r   r  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr-  selected_expertsr
  tokens_per_expertrouter_prob_per_expertr+  r,  r]  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r3   load_balancing_loss_funcr{  
  s+   : *[%"@"@+u%%$Q..#(99^i-j^iPZmmN.K^i-jpq#r hh))112JPR1SO**_DA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
4::1=*B^_ 4AtT12V&OKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&OQRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1Q1QRS1TTUL+%%[ .ks   Ic                   \  ^  \ rS rSrSS0rSS0rSS/S/40rU 4S jr\\	         SS
\
R                  S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\S	-  S\\
R                  -  S\\   S\4S jj5       5       rSrU =r$ )OlmoeForCausalLMi\  zlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr6   logitsc                 J  > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  U l	        UR                  U l
        UR                  U l        U R                  5         g r   )r(   r)   rS  r@  rX  r   r   r0   r~  router_aux_loss_coefr   r  rb  r   s     r3   r)   OlmoeForCausalLM.__init__b  s     '
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	r5   Nrd  r   r   r   re  labelsr7  output_router_logitslogits_to_keepr   r&   c
                 z   Ub  UOU R                   R                  nU R                  " SUUUUUUUS.U
D6nUR                  n[	        U	[
        5      (       a  [        U	* S5      OU	nU R                  USS2USS24   5      nSnUb  U R                  " XU R                  40 U
D6nSnU(       aY  [        UR                  U R                  U R                  U5      nUb*  XR                  UR                  UR                   5      -  -  n[#        UUUUR$                  UR&                  UR(                  UR                  S9$ )u  
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, OlmoeForCausalLM

>>> model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924")
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924")

>>> 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 sure if you’re conscious of this, but I’m'
```
N)rd  r   r   r   re  r7  r  )lossaux_lossr  r   r6   rB  r  r9  )rV   r  r@  rg  r|   r   slicer~  loss_functionrX  r{  r  r   r  r  r<   rd   r   r   r6   rB  )r/   rd  r   r   r   re  r  r7  r  r  r   outputsr6   slice_indicesr  r  r  s                    r3   rC   OlmoeForCausalLM.forwardn  sP   P %9$D $++JjJj 	
 +/** 	+
)%+'!5	+
 	+
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r5   )r~  r@  r   r  r  rX  )	NNNNNNNNr   )rJ   rK   rL   rM   _tied_weights_keys_tp_plan_pp_planr)   r   r   r+   r<  rN   r	   rn  r=  r   r   r   r   rC   rO   rP   rQ   s   @r3   r}  r}  \  s5   *,GH23H_-z:;H
  .2.204(,26*.!%,0-.Q
##d*Q
 t+Q
 &&-	Q

 Q
 ((4/Q
   4'Q
 $;Q
 #TkQ
 ell*Q
 +,Q
 
#Q
  Q
r5   r}  )r}  rS  r?  )r    )r   )Nr8   N)Icollections.abcr   typingr   r+   torch.nn.functionalr   r   r   r   rF  activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   r   r   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr   r   utils.output_capturingr   r   configuration_olmoer!   Moduler$   rS   r   r   r   rN   r   r   rp   r   r   r   r  r&  r0  r?  rS  rF   r{  r}  __all__r9  r5   r3   <module>r     s  & %      & ! . )  0 9 Q K F & I I G E , Y'J299 J (J(><299 ><Bryy  ( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*M)RYY M) +M)` $#299 $# $#N<bii <*#")) # &2 &R U? U U4 H
% H
 H
Z #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d d
+_ d
 d
N Er5   