
    iW|                        d dl mZ d dlmZ d dlZd dlmc mZ d dlmZ ddl	m
Z ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZ ddlmZ ddlmZ ddlmZmZ ddlm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3  ed       G d dejh                               Z5 G d dejh                        Z6 G d dejh                        Z7d Z8 ed      dAd       Z9d ejt                  d!e;d"ejt                  fd#Z<	 dBd$ejh                  d%ejt                  d&ejt                  d'ejt                  d(ejt                  dz  d)e=d*e=d+e&e(   fd,Z> ee9       G d- d.ejh                               Z?e G d/ d0ejh                               Z@ G d1 d2ejh                        ZA G d3 d4ejh                        ZB G d5 d6e      ZCe) G d7 d8e$             ZDe) G d9 d:eD             ZE	 	 	 dCd;ejt                  eFejt                     z  dz  d<e;dz  d(ejt                  dz  d"ejt                  e;z  fd=ZGe) G d> d?eDe             ZHg d@ZIy)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is_grouped_mm_available)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )OlmoeConfigRMSNormc                   `     e Zd Zdd fdZdej
                  dej
                  fdZd Z xZS )OlmoeRMSNormreturnc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z;
        OlmoeRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__s      d/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/models/olmoe/modeling_olmoe.pyr)   zOlmoeRMSNorm.__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-   )r/   r5   input_dtypevariances       r3   forwardzOlmoeRMSNorm.forward:   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r4   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler-   shaper.   )r/   s    r3   
extra_reprzOlmoeRMSNorm.extra_reprA   s*    ))*+6$2G2G1HIIr4   )gh㈵>)r&   N)	__name__
__module____qualname__r)   r+   TensorrB   rF   __classcell__r2   s   @r3   r%   r%   0   s)    $;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 )OlmoeRotaryEmbedding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defaultrO   F)
persistentoriginal_inv_freq)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrP   rope_parametersrR   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r/   rP   devicerope_init_fnrO   r2   s        r3   r)   zOlmoeRotaryEmbedding.__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:   )	rY   getattrr0   num_attention_headsr+   arangeint64r;   float)rP   r^   r`   basedimattention_factorrO   s          r3   rZ   z4OlmoeRotaryEmbedding.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   rd   )rO   ri   expandrE   r;   r^   
isinstancetypestrr   	transposer+   catcosr[   sinr:   )
r/   xposition_idsinv_freq_expandedposition_ids_expandedrp   freqsembry   rz   s
             r3   rB   zOlmoeRotaryEmbedding.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+   rJ   __annotations__r"   r)   staticmethodr   intrD   ri   rZ   no_gradr   rB   rK   rL   s   @r3   rN   rN   E   s    llV{ V  %)+/"*d"*(* t* 
~u$	%	* *: U]]_<  <r4   rN   c                   $     e Zd Z fdZd Z xZS )OlmoeMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFbias)r(   r)   rP   r0   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnr/   rP   r2   s     r3   r)   zOlmoeMLP.__init__   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r4   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r   )r   r   r   r   )r/   r{   r   s      r3   rB   zOlmoeMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r4   rG   rH   rI   r)   rB   rK   rL   s   @r3   r   r      s    0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      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   )qkry   rz   unsqueeze_dimq_embedk_embeds          r3   apply_rotary_pos_embr      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   reshape)r5   r   batchnum_key_value_headsslenrc   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   
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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	ej                  ej                  f   dej                  dz  d	e
dz  d
ej                  dz  dee   de	ej                  ej                  dz  e	ej                     dz  f   fdZ xZS )OlmoeAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrP   	layer_idxc                 0   t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j
                  |j                  | j                  z  |j                        | _        t        j                  |j                  | j                  z  |j
                  |j                        | _        t)        |j
                  |j*                        | _        t)        |j
                  |j                  z  |j                  z  |j*                        | _        y )Nrc   g      Tr   r1   )r(   r)   rP   r   re   r0   rf   rc   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/   rP   r   r2   s      r3   r)   z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
r4   r5   position_embeddingsr   past_key_valuescache_positionr   r&   c           
         |j                   d d }g |d| j                  }| j                  | j                  |            }	| j	                  | j                  |            }
| j                  |      }| j                  j                  |	j                  | j                  j                   | j                  j                         |
j                  | j                  j                   | j                  j                         |j                  | j                  j                   | j                  j                          |	j                  | j                  dd      }	 |
j                  | j                  dd      }
 |j                  | j                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        j                   | j                  j"                  t$              } || |	|
||f| j&                  sdn| j(                  | j*                  t-        | j                  dd       d|\  }} |j.                  g |d j1                         }| j3                  |      }||fS )	Nr8   )minmaxr!   r7   )rz   ry   r           sliding_window)r   r   r   )rE   rc   r   r   r   r   r   rP   clip_qkvclamp_viewrw   r   updater   r   get_interface_attn_implementationr   r   r   r   re   r   r   r   )r/   r5   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   ry   rz   cache_kwargsattention_interfacer   r   s                     r3   rB   zOlmoeAttention.forward   sa    $))#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$Z__l3==aC
(|((,7AA!QG&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ *k));;;;FFHkk+.L((r4   r   )NN)rG   rH   rI   __doc__r"   r   r)   r+   rJ   rD   r	   
LongTensorr   r   rB   rK   rL   s   @r3   r   r      s    G
{ 
sTz 
@ )-262)||2) #5<<#=>2) t+	2)
 2) ((4/2) +,2) 
u||U\\D0%2E2LL	M2)r4   r   c                        e Zd ZdZdef fdZdej                  dej                  dej                  dej                  fdZ xZ	S )	OlmoeExpertsz2Collection of expert weights stored as 3D tensors.rP   c                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )Nr7   )r(   r)   num_local_expertsnum_expertsr0   
hidden_dimr   intermediate_dimr   r*   r+   emptygate_up_projr   r   r   r   r   s     r3   r)   zOlmoeExperts.__init__4  s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r4   r5   top_k_indextop_k_weightsr&   c                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesr7   r!   r   )r8   rr   r8   )r+   
zeros_liker   r   r   one_hotr   permutegreatersumnonzerowherelinearr   chunkr   r   
index_add_r;   r:   )r/   r5   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r3   rB   zOlmoeExperts.forward=  s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0)
rG   rH   rI   r   r"   r)   r+   rJ   rB   rK   rL   s   @r3   r   r   0  sM    <0{ 0#||# \\# ||	#
 
#r4   r   c                   $     e Zd Z fdZd Z xZS )OlmoeTopKRouterc                 .   t         |           |j                  | _        |j                  | _        |j
                  | _        |j                  | _        t        j                  t        j                  | j                  | j                              | _        y r   )r(   r)   num_experts_per_toktop_kr   norm_topk_probr0   r   r   r*   r+   zerosr-   r   s     r3   r)   zOlmoeTopKRouter.__init__Y  si    //
!--$33 ,,ll5;;t/?/?#QRr4   c                    |j                  d| j                        }t        j                  || j                        }t
        j                  j                  j                  |t
        j                  d      }t        j                  || j                  d      \  }}| j                  r||j                  dd      z  }|j                  |j                        }|}|||fS )Nr8   )r:   rk   rr   T)rk   r9   )r   r   Fr   r-   r+   r   r   r   ri   topkr
  r  r   r;   r:   )r/   r5   router_logitsrouter_top_valuerouter_indicesrouter_scoress         r3   rB   zOlmoeTopKRouter.forwarda  s    %--b$//B<++33MZ\3]+0::mTZZUW+X(. 0 4 4T 4 JJ+..}/B/BC(m^;;r4   r   rL   s   @r3   r  r  X  s    S	<r4   r  c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )OlmoeSparseMoeBlockc                 b    t         |           t        |      | _        t	        |      | _        y r   )r(   r)   r  r  r   expertsr   s     r3   r)   zOlmoeSparseMoeBlock.__init__n  s&    #F+	#F+r4   r5   r&   c                     |j                   \  }}}|j                  d|      }| j                  |      \  }}}| j                  |||      j	                  |||      }|S )Nr8   )rE   r   r  r  r   )	r/   r5   
batch_sizesequence_lengthr   _r   r   r   s	            r3   rB   zOlmoeSparseMoeBlock.forwards  sh    2?2E2E/
OZ%**2z:(,		-(@%=+"ll=+}U]]
 #"r4   )rG   rH   rI   r)   r+   rJ   rB   rK   rL   s   @r3   r  r  m  s#    ,
#U\\ #ell #r4   r  c                   "    e Zd Zdedef fdZ	 	 	 	 	 	 ddej                  dej                  dz  dej                  dz  de	dz  d	e
dz  d
ej                  dz  deej                  ej                  f   dz  dee   dej                  fdZ xZS )OlmoeDecoderLayerrP   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)rP   r   r   )r(   r)   r0   r   	self_attnr  mlpr%   r   input_layernormpost_attention_layernormr   s      r3   r)   zOlmoeDecoderLayer.__init__~  sl    !--'vK&v.+F,>,>FDWDWX(4V5G5GVM`M`(a%r4   Nr5   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   )r/   r5   r   r|   r   r#  r   r   r   residualr  s              r3   rB   zOlmoeDecoderLayer.forward  s     !,,];)4>> 	
')%+) 3	
 	
q !=0 !55mD/ =0r4   )NNNFNN)rG   rH   rI   r"   r   r)   r+   rJ   r   r	   boolrD   r   r   rB   rK   rL   s   @r3   r  r  }  s    b{ bs b /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
 eed      eedZ e       ZdZ ej(                         d	        Zy
)OlmoePreTrainedModelrP   modelTr  r   r   )index)r  r5   
attentionsc                    t        j                  | |       t        |t              rmt	        j
                  |j                  d| j                  j                         t	        j
                  |j                  d| j                  j                         y t        |t              r7t	        j
                  |j                  d| j                  j                         y y )Nr   )r>   std)r   _init_weightsrt   r   initnormal_r   rP   initializer_ranger   r  r-   )r/   r   s     r3   r/  z"OlmoePreTrainedModel._init_weights  s    %%dF3fl+LL,,3DKK<Y<YZLL))9V9VW0LLSdkk6S6ST 1r4   N)rG   rH   rI   r"   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpar   r  r  r   _can_record_outputsr   _can_compile_fullgraph_supports_attention_backendr+   r   r/  r%  r4   r3   r)  r)    sz    &*#,-#4"5N'qA*$ 	 !  #'U]]_U Ur4   r)  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 )
OlmoeModelrP   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   rP   F)r(   r)   pad_token_idpadding_idx
vocab_sizer   	Embeddingr0   embed_tokens
ModuleListrangenum_hidden_layersr  layersr%   r   normrN   
rotary_embgradient_checkpointing	post_initr   s      r3   r)   zOlmoeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammCHIaIaCbcivy1c
 !!3!39L9LM	.f=&+# 	 d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_embedsr?  r   r!   )r^   )rP   rN  r   r   r   r|   )r   r   r|   r   r#  r   )last_hidden_stater   )
ValueErrorr
   rP   rD  get_seq_lengthr+   rg   rE   r^   r   r   rJ  rH  rG  rI  r   )r/   rM  r   r|   r   rN  r#  r   r   past_seen_tokenscausal_maskr5   r   decoder_layers                 r3   rB   zOlmoeModel.forward  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   rJ   r	   FloatTensorr'  r   r   r   rB   rK   rL   s   @r3   r=  r=    s    {    .2.204(,26!%26;
##d*;
 t+;
 &&-	;

 ;
 ((4/;
 $;;
 ((4/;
 +,;
 
 ;
    ;
r4   r=  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  r   r>   ri   rE   rs   r   r   r   )rW  r   r
  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr  selected_expertsr   tokens_per_expertrouter_prob_per_expertr  r  rG  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r3   load_balancing_loss_funcrc    s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&
O[QRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1G1Q1QRS1TTUL+%%[ .ks   Ic                   n    e Zd ZddiZddiZddgdgfiZ fdZee	 	 	 	 	 	 	 	 	 	 dd	e	j                  dz  d
e	j                  dz  de	j                  dz  dedz  de	j                  dz  de	j                  dz  dedz  dedz  de	j                  dz  dee	j                  z  dee   defd              Z xZS )OlmoeForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr5   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _
        |j                  | _        | j                          y r   )r(   r)   r=  r*  rB  r   r   r0   rf  router_aux_loss_coefr   r	  rL  r   s     r3   r)   zOlmoeForCausalLM.__init__o  s     '
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	r4   NrM  r   r|   r   rN  labelsr#  output_router_logitsr   logits_to_keepr   r&   c                 l   ||n| j                   j                  } | j                  d||||||||	d|}|j                  }t	        |
t
              rt        |
 d      n|
}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |}d}|rYt        |j                  | j                  | j                  |      }|+|| j                  |j                  |j                         z  z  }t#        ||||j$                  |j&                  |j(                  |j                        S )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)rM  r   r|   r   rN  r#  rl  r   )lossaux_lossrh  r   r5   r,  r  r%  )rP   rl  r*  rP  rt   r   slicerf  loss_functionrB  rc  r  r   r	  rj  r;   r^   r   r   r5   r,  )r/   rM  r   r|   r   rN  rk  r#  rl  r   rm  r   outputsr5   slice_indicesrh  ro  rp  s                     r3   rB   zOlmoeForCausalLM.forward{  sX   R %9$D $++JjJj 	
 +5$** 
+
)%+'!5)
+
 
+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r4   )
NNNNNNNNNr   )rG   rH   rI   _tied_weights_keys_tp_plan_pp_planr)   r   r   r+   r   rJ   r	   rV  r'  r   r   r   r   rB   rK   rL   s   @r3   re  re  i  sN   *,GH23H_-z:;H
  .2.204(,26*.!%,026-.S
##d*S
 t+S
 &&-	S

 S
 ((4/S
   4'S
 $;S
 #TkS
 ((4/S
 ell*S
 +,S
 
#S
  S
r4   re  )re  r=  r)  )r!   )r   )Nr7   N)Jcollections.abcr   typingr   r+   torch.nn.functionalr   r   r   r   r0  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   r   utils.genericr   r   utils.output_capturingr   r    configuration_olmoer"   Moduler%   rN   r   r   r   rJ   r   r   ri   r   r   r   r  r  r  r)  r=  rD   rc  re  __all__r%  r4   r3   <module>r     s  & %      & ! . )  0 9 Q K F & b b G E , Y'J299 J (J(><299 ><Bryy  ( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*P)RYY P) +P)f $#299 $# $#N<bii <*#")) # (2 (V U? U U8 N
% N
 N
f #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d f
+_ f
 f
R Er4   