
    fTh                        S r SSKrSSKJrJrJrJr  SSKrSSKJ	s  J
r  SSKrSSKJ	r	  SSKJr  SSK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#  SSK$J%r%J&r&  SSK'J(r(  \" 5       (       a  SSKJ)r)  \&RT                  " \+5      r,   S5S\\RZ                  \\RZ                     S4   S\\.   S\\RZ                     S\\RZ                  \.4   4S jjr/ " S S\	R`                  5      r1\#Rd                  " \15         " S S\	R`                  5      r3S r4S6S jr5 " S S\	R`                  5      r6S \RZ                  S!\.S\RZ                  4S" jr7 " S# S$\	R`                  5      r8 " S% S&\85      r9 " S' S(\85      r:\8\9\:S).r; " S* S+\	R`                  5      r< " S, S-\	R`                  5      r=\% " S. S/\!5      5       r>\% " S0 S1\>5      5       r? " S2 S3\>\5      r@/ S4QrAg)7zPyTorch OLMoE model.    N)ListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)ALL_LAYERNORM_LAYERS)auto_docstringlogging   )OlmoeConfig)_flash_attention_forwardgate_logitsnum_expertsattention_maskreturnc                    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 )ap  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

See Switch Transformer (https://arxiv.org/abs/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   dim)
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesum	unsqueeze)r   r   top_kr   compute_device
layer_gateconcatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_losss                      `/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/olmoe/modeling_olmoe.pyload_balancing_loss_funcrF   +   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                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )OlmoeRMSNorm}   c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z+
OlmoeRMSNorm is equivalent to T5LayerNorm
N)super__init__r   	Parameterr'   onesweightvariance_epsilon)selfhidden_sizeeps	__class__s      rE   rL   OlmoeRMSNorm.__init__~   s/     	ll5::k#:; #    c                    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   r#   T)keepdim)	dtyper)   r'   float32powr.   rsqrtrP   rO   )rQ   hidden_statesinput_dtypevariances       rE   forwardOlmoeRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::rV   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r%   rO   r0   rP   rQ   s    rE   
extra_reprOlmoeRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrV   )rP   rO   )gh㈵>)	__name__
__module____qualname____firstlineno__rL   ra   re   __static_attributes____classcell__rT   s   @rE   rH   rH   }   s    $;J JrV   rH   c                   l   ^  \ rS rSrSS\4U 4S jjjr\R                  " 5       \S 5       5       r	Sr
U =r$ )OlmoeRotaryEmbedding   configc                   > [         TU ]  5         [        US5      (       aH  UR                  b;  UR                  R	                  SUR                  R	                  S5      5      U l        OSU l        UR                  U l        UR                  U l        Xl	        [        U R
                     U l        U R                  U R                  U5      u  o0l        U R                  SUSS9  U R                  U l        g )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)rK   rL   hasattrrs   getrt   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrq   r   rope_init_fnattention_scalingregister_bufferrw   original_inv_freq)rQ   rq   r&   rw   rT   s       rE   rL   OlmoeRotaryEmbedding.__init__   s    6>**v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%rV   c                 b   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[        R                  " USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r#   r   mpscpuF)device_typeenabledrX   r!   )rZ   )rw   r/   r1   r0   r)   r&   r$   ru   strr'   autocast	transposer(   cosr   sinrZ   )
rQ   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             rE   ra   OlmoeRotaryEmbedding.forward   sR    !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.)r   rq   r|   r   r}   r~   rt   N)rg   rh   ri   rj   r   rL   r'   no_gradr   ra   rk   rl   rm   s   @rE   ro   ro      s6    /{ / /" ]]_<  <rV   ro   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nr#   rX   r!   )r0   r'   r(   )r   x1x2s      rE   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rV   c                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXg4$ )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.
    position_ids (`torch.Tensor`, *optional*):
        Deprecated and unused.
    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.
)r4   r   )qkr   r   r   unsqueeze_dimq_embedk_embeds           rE   apply_rotary_pos_embr      sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0GrV   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)rK   rL   rq   rR   intermediate_sizer   Linear	gate_projup_proj	down_projr	   
hidden_actact_fnrQ   rq   rT   s     rE   rL   OlmoeMLP.__init__   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../rV   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ r   )r   r   r   r   )rQ   r   r   s      rE   ra   OlmoeMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	rV   )r   rq   r   r   rR   r   r   )rg   rh   ri   rj   rL   ra   rk   rl   rm   s   @rE   r   r      s    0 rV   r   r^   n_repc                     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)r0   r1   r2   )r^   r   batchnum_key_value_headsslenhead_dims         rE   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTrV   c                   |  ^  \ rS rSrSrSS\S\\   4U 4S jjjr       SS\	R                  S\\	R                     S\\	R                     S	\\   S
\S\S\\	R                     S\\\	R                  \	R                  4      S\\	R                  \\	R                     \\\	R                        4   4S jjrSrU =r$ )OlmoeAttention   z=Multi-headed attention from 'Attention Is All You Need' paperrq   	layer_idxc                 \  > [         TU ]  5         Xl        X l        Uc-  [        R                  SU R                  R                   S35        UR                  U l        UR                  U l	        UR                  U l        U R                  U R                  -  U l        UR                  U l        U R                  U R                  -  U l        UR                  U l        UR                   U l        SU l        U R                  U R                  -  U R                  :w  a&  [%        SU R                   SU R                   S35      e[&        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*                  S9U l        [5        U R                  UR6                  S9U l        [5        U R                  U R                  -  U R                  -  UR6                  S9U l        g )	Nz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.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).r   rS   )rK   rL   rq   r   loggerwarning_oncerT   rg   attention_dropoutrR   num_attention_heads	num_headsr   r   num_key_value_groupsr{   
rope_theta	is_causal
ValueErrorr   r   attention_biasq_projk_projv_projo_projrH   rms_norm_epsq_normk_normrQ   rq   r   rT   s      rE   rL   OlmoeAttention.__init__   s   " !8!8 9 :, , "(!9!9!--33((DNN:#)#=#= $(NNd6N6N$N!'-'E'E$ ++MMDNN*t/?/??QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii 0 0$2B2BI^I^_"4#3#39L9LM"/43K3KKQWQdQd
rV   r^   r   r   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr   c	                    UR                  5       u  pn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                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUu  nn[        XUU5      u  pUb%  UUUS.nUR                  XU R                   U5      u  p[#        XR$                  5      n[#        XR$                  5      n[&        R(                  " XR                  SS5      5      [*        R,                  " U R                  5      -  nUb#  US S 2S S 2S S 2S UR.                  S   24   nUU-   n[0        R2                  R5                  US[&        R6                  S9R9                  UR:                  5      n[0        R2                  R=                  UU R>                  U R@                  S	9n[&        R(                  " UU5      nUR                  5       XR                  XR                  4:w  a5  [C        S
XR                  XR                  4 SUR                  5        35      eUR                  SS5      RE                  5       nURG                  XU RH                  5      nU RK                  U5      nU(       d  S nUUU4$ )Nminmaxr   rX   r   r   r   r   r#   r"   rZ   )ptrainingz `attn_output` should be of size z	, but is )&sizer   r   r   r   r   rq   clip_qkvclamp_viewr   r   r   r   r   updater   r   r   r'   matmulmathsqrtr0   r   r*   r+   r[   r)   rZ   dropoutr   r   r   
contiguousr2   rR   r   )rQ   r^   r   r   r   r   r   r   r   kwargsbszq_lenr:   query_states
key_statesvalue_statesr   r   cache_kwargsattn_weightscausal_maskattn_outputs                         rE   ra   OlmoeAttention.forward   sV    &**,A{{4;;}#=>[[]!;<
{{=1;;+T[[%9%9$9t{{?S?ST4;;#7#7"7T[[=Q=QRT[[%9%9$9t{{?S?ST#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm&S#7RUWZ#[ %#&snUL'5'<'<ZW[WeWegs't$Jz+D+DE
 /H/HI||L2F2Fq!2LMPTPYPYZ^ZgZgPhh%(Aq2HJ4D4DR4H2H)HIK'+5L }},,\r,WZZ[g[m[mn}},,\T=S=S^b^k^k,lll<>#~~umm!LL2CP]P]3^2_ `$$&') 
 "++Aq1<<>!))#d6F6FGkk+. LL.88rV   )r   rq   r   rR   r   r   r   r   r{   r   r   r   r   r   r   r   r   r   NNNFFNN)rg   rh   ri   rj   __doc__r   r   intrL   r'   Tensor
LongTensorr
   boolr   ra   rk   rl   rm   s   @rE   r   r      s   G"
{ "
x} "
 "
N 2637*."'59KO@9||@9 !.@9 u//0	@9
 !@9  @9 @9 !!1!12@9 &eELL%,,,F&GH@9 
u||Xell3XeELL>Q5RR	S@9 @9rV   r   c                   f  ^  \ rS rSrSrU 4S jr       SS\R                  S\\R                     S\\R                     S\\
   S\S	\S
\\R                     S\\\R                  \R                  4      S\\R                  \\R                     \\\R                        4   4S jjrSrU =r$ )OlmoeFlashAttention2ic  a6  
OLMoE flash attention module. This module inherits from `OlmoeAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash attention and deal with padding tokens in case the input contains any of them.
c                 D   > [         TU ]  " U0 UD6  [        5       U l        g r   )rK   rL   r   _flash_attn_uses_top_left_mask)rQ   argsr   rT   s      rE   rL   OlmoeFlashAttention2.__init__j  s#    $)&)
 /P.Q+rV   r^   r   r   r   r   r   r   r   r   c	                 t   SnUR                  5       u  pn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                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUu  nn[        XUU5      u  pUb%  UUUS.nUR                  XU R                   U5      u  pUR                  SS5      nUR                  SS5      nUR                  SS5      nU R"                  (       a  U R$                  OSnUR&                  nU[(        R*                  :X  a  [(        R,                  " 5       (       a  [(        R.                  " 5       nOR[1        U R                  S5      (       a  U R                  R2                  nO U R                  R4                  R&                  n[6        R9                  SU S	35        UR;                  U5      nUR;                  U5      nUR;                  U5      n[=        UUUUUUU R>                  U R@                  S
9nURC                  XU RD                  5      RG                  5       nU RI                  U5      nU(       d  S nUWU4$ )NFr   r   rX   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r   use_top_left_maskr   )%r   r   r   r   r   r   rq   r   r   r   r   r   r   r   r   r   r   r   r   rZ   r'   r[   is_autocast_enabledget_autocast_gpu_dtypery   r  rO   r   r   r)   r   r   r   r2   rR   r   r   )rQ   r^   r   r   r   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   dropout_rater_   target_dtyper   r   s                           rE   ra   OlmoeFlashAttention2.forwardr  s,    "%**,A{{4;;}#=>[[]!;<
{{=1;;+T[[%9%9$9t{{?S?ST4;;#7#7"7T[[=Q=QRT[[%9%9$9t{{?S?ST
 $((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm&S#7RUWZ#[ %#&snUL'5'<'<ZW[WeWegs't$J $--a3))!Q/
#--a315t--C #((%--'((**$;;=&?@@#{{BB#{{1177 >$ (??<8L#|4J'??<8L. "AAnn	
 "))#d6F6FGRRTkk+. LL.88rV   )r   r   )rg   rh   ri   rj   r   rL   r'   r   r   r   r
   r   r   ra   rk   rl   rm   s   @rE   r   r   c  s    R 6:37*."'59KOZ9||Z9 !!1!12Z9 u//0	Z9
 !Z9  Z9 Z9 !!1!12Z9 &eELL%,,,F&GHZ9 
u||Xell3XeELL>Q5RR	SZ9 Z9rV   r   c                   `  ^  \ rS rSrSr       SS\R                  S\\R                     S\\R                     S\\	   S\
S\
S	\\R                     S
\\\R                  \R                  4      S\\R                  \\R                     \\\R                        4   4U 4S jjjrSrU =r$ )OlmoeSdpaAttentioni  z
OLMoE attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
`OlmoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
SDPA API.
r^   r   r   r   r   r   r   r   r   c	                   > U(       a)  [         R                  S5        [        TU ]  UUUUUUUUS9$ UR	                  5       u  pn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                  XU R                  U R                  5      R!                  SS5      nUR                  XU R"                  U R                  5      R!                  SS5      nUR                  XU R"                  U R                  5      R!                  SS5      nUu  nn[%        XUU5      u  pUb$  UXS.nUR'                  XU R(                  U5      u  p[+        XR,                  5      n[+        XR,                  5      nUnUb  US S 2S S 2S S 2S UR.                  S   24   nUR0                  R2                  S:X  a3  Ub0  UR5                  5       nUR5                  5       nUR5                  5       nUc  U
S:  a  S	OS
n[6        R8                  R:                  R=                  UUUUU R>                  (       a  U R@                  OSUS9nUR!                  SS5      R5                  5       nUR                  XU RB                  5      nU RE                  U5      nUS U4$ )Na  OlmoeModel is using OlmoeSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r^   r   r   r   r   r   r   r   r   r   rX   r   r   cudaTFr  )	attn_mask	dropout_pr   )#r   r   rK   ra   r   r   r   r   r   r   rq   r   r   r   r   r   r   r   r   r   r   r   r   r0   r&   ru   r   r'   r   r*   scaled_dot_product_attentionr   r   rR   r   )rQ   r^   r   r   r   r   r   r   r   r   r   r:   r   r   r   r   r   r   r   r   r   rT   s                        rE   ra   OlmoeSdpaAttention.forward  s0    [ 7?+-)-"3#-$7 # 	 	 &**,A{{4;;}#=>[[]!;<
{{=1;;+T[[%9%9$9t{{?S?ST4;;#7#7"7T[[=Q=QRT[[%9%9$9t{{?S?ST#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm&S#7RUWZ#[ %#&sUL'5'<'<ZW[WeWegs't$Jz+D+DE
 /H/HI$%%aA/E1A1A"1E/E&EFK ##v-+2I'224L#..0J'224L (/EAID5	hh))FF!04d,,3 G 
 "++Aq1<<>!&&s43C3CDkk+.D.00rV    r   )rg   rh   ri   rj   r   r'   r   r   r   r
   r   r   ra   rk   rl   rm   s   @rE   r  r    s     2637*."'59KOT1||T1 !.T1 u//0	T1
 !T1  T1 T1 !!1!12T1 &eELL%,,,F&GHT1 
u||Xell3XeELL>Q5RR	ST1 T1rV   r  )eagerflash_attention_2sdpac                   b   ^  \ rS rSrU 4S jrS\R                  S\R                  4S jrSrU =r	$ )OlmoeSparseMoeBlocki5  c                   > [         TU ]  5         UR                  U l        UR                  U l        UR
                  U l        [        R                  " UR                  U R                  SS9U l	        [        R                  " [        U R                  5       Vs/ s H  n[        U5      PM     sn5      U l        g s  snf r   )rK   rL   r   num_experts_per_tokr5   norm_topk_probr   r   rR   gate
ModuleListranger   experts)rQ   rq   r:   rT   s      rE   rL   OlmoeSparseMoeBlock.__init__6  s    !--//
$33IIf00$2B2BO	}}dFVFV@W%X@W1hv&6@W%XY%Xs   B;r^   r   c                    UR                   u  p#nUR                  SU5      nU R                  U5      n[        R                  " US[
        R                  S9n[
        R                  " X`R                  SS9u  pgU R                  (       a  XfR                  SSS9-  nUR                  UR                  5      n[
        R                  " X#-  U4UR                  UR                  S9n[
        R                  R                   R#                  XpR$                  S9R'                  S	SS
5      n	[)        U R$                  5       H~  n
U R*                  U
   n[
        R,                  " X   5      u  pUS U4   R/                  SU5      nU" U5      XmUS 4   -  nUR1                  S
XR                  UR                  5      5        M     UR/                  X#U5      nX4$ )Nr#   r   r   r!   T)r"   rY   )rZ   r&   )num_classesrX   r   )r0   r   r  Fr+   r'   r/   r,   r5   r  r3   r)   rZ   zerosr&   r   r*   r-   r   permuter   r!  wherer2   
index_add_)rQ   r^   r?   r@   
hidden_dimrouter_logitsr9   r;   final_hidden_statesr<   
expert_idxexpert_layeridxtop_xcurrent_statecurrent_hidden_statess                   rE   ra   OlmoeSparseMoeBlock.forward>  s   2?2E2E/
Z%**2z:		-0))MqL,1JJ

XZ,[)22r42HHO),,]-@-@A#kk):6m>Q>QZgZnZn
 hh))112BP`P`1aiijkmnpqr   0 01J<<
3L[%<=JC
 *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5M5MmNaNa5bc 2 299*Wab"11rV   )r!  r  r  r   r5   )
rg   rh   ri   rj   rL   r'   r   ra   rk   rl   rm   s   @rE   r  r  5  s)    Z$2U\\ $2ell $2 $2rV   r  c                     ^  \ rS rSrS\S\4U 4S jjr        SS\R                  S\	\R                     S\	\R                     S\	\   S	\	\   S
\	\   S\	\   S\	\R                     S\	\\R                  \R                  4      S\\R                  \	\\R                  \R                  4      4   4S jjrSrU =r$ )OlmoeDecoderLayerie  rq   r   c                 (  > [         TU ]  5         UR                  U l        [        UR                     " 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)rq   r   r   )rK   rL   rR   OLMOE_ATTENTION_CLASSES_attn_implementation	self_attnr  mlprH   r   input_layernormpost_attention_layernormr   s      rE   rL   OlmoeDecoderLayer.__init__f  sv    !--01L1LMU[q&v.+F,>,>FDWDWX(4V5G5GVM`M`(a%rV   r^   r   r   r   r   output_router_logitsr   r   r   r   c
                    UnU R                  U5      nU R                  " SUUUUUUUU	S.U
D6u  pnX-   nUnU R                  U5      nU R                  U5      u  pX-   nU4nU(       a  X4-  nU(       a  X4-  nU(       a  X4-  nU$ )aY  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*):
        attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
        query_sequence_length, key_sequence_length)` if default attention is used.
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    output_router_logits (`bool`, *optional*):
        Whether or not to return the logits of all the routers. They are useful for computing the router loss,
        and should not be returned during inference.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence
    position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
        Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
        with `head_dim` being the embedding dimension of each attention head.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
r  r  )r;  r9  r<  r:  )rQ   r^   r   r   r   r   r>  r   r   r   r   residualself_attn_weightspresent_key_valuer+  outputss                   rE   ra   OlmoeDecoderLayer.forwardp  s    L !,,]; ?Cnn 
?
')%)/) 3
?
 
?
;*; !0 !55mD'+xx'>$ 0 "++G++G''GrV   )rR   r;  r:  r<  r9  )NNNFFFNN)rg   rh   ri   rj   r   r   rL   r'   r   r   r   r
   r   r   FloatTensorra   rk   rl   rm   s   @rE   r5  r5  e  s    b{ bs b 2637*.,1/4$)59KOI||I !.I u//0	I
 !I $D>I 'tnI D>I !!1!12I &eELL%,,,F&GHI 
u  (51B1BEDUDU1U+V"WW	XI IrV   r5  c                   F    \ rS rSr\rSrSrS/rS/r	Sr
SrSrSrSrS rSrg	)
OlmoePreTrainedModeli  modelTr5  past_key_valuesFc                    U R                   R                  n[        U[        R                  5      (       aW  UR
                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        5      (       a&  UR
                  R                  R                  S5        g [        U[        R                  5      (       ad  UR
                  R                  R                  SUS9  UR                  b2  UR
                  R                  UR                     R                  5         g g g )Nr  )r.   stdg      ?)rq   initializer_ranger$   r   r   rO   datanormal_r   zero_rH   fill_	Embeddingpadding_idx)rQ   modulerK  s      rE   _init_weights"OlmoePreTrainedModel._init_weights  s    kk++fbii((MM&&CS&9{{&  &&( '--MM$$S)--MM&&CS&9!!-""6#5#56<<> . .rV   r  N)rg   rh   ri   rj   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cacherT  rk   r  rV   rE   rG  rG    sG    L&*#,-#4"5!N  $"?rV   rG  c                   H  ^  \ rS rSrS\4U 4S jjrS rS r\           SS\	\
R                     S\	\
R                     S\	\
R                     S	\	\\\\
R                      4      S
\	\
R                      S\	\   S\	\   S\	\   S\	\   S\	\   S\	\
R                     S\\\4   4S jj5       rS\
R                  S\
R                  S\
R                  S	\S\4
S jr\S\
R                  S\S\S\
R0                  S\
R2                  S\
R                  S\4S j5       rSrU =r$ )
OlmoeModeli  rq   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   )rq   F)rK   rL   pad_token_idrR  
vocab_sizer   rQ  rR   embed_tokensr  r   rA   r5  layersrH   r   normro   
rotary_embgradient_checkpointing	post_initr   s      rE   rL   OlmoeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammCHIaIaCbcCbiv1Cbc
 !!3!39L9LM	.f=&+# 	 ds   C?c                     U R                   $ r   re  rd   s    rE   get_input_embeddingsOlmoeModel.get_input_embeddings  s       rV   c                     Xl         g r   rm  rQ   values     rE   set_input_embeddingsOlmoeModel.set_input_embeddings  s    !rV   	input_idsr   r   rI  inputs_embedsr   r   output_hidden_statesr>  return_dictr   r   c                 X   Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nUb  UOU R                   R                  nU
b  U
OU R                   R
                  n
US L US L-  (       a  [        S5      eU R                  (       a/  U R                  (       a  U(       a  [        R                  S5        SnUc  U R                  U5      nSnU(       aP  [        U[        5      (       d;  SnUc  [        5       nO+[        R                  " U5      n[        R                  S5        UcD  Ub  UR!                  5       OSn["        R$                  " XUR&                  S   -   UR(                  S9nUc  UR+                  S5      nU R-                  X%XU5      nUnU R/                  X5      nU(       a  S	OS nU(       a  S	OS nU	(       a  S	OS nS nU R0                  S U R                   R2                    H  nU(       a  UU4-  nU R                  (       a6  U R                  (       a%  U R5                  UR6                  UUUUUU	UUU5
      nOU" UUUUUU	UUUS
9	nUS   nU(       a  UU(       a  SOS   nU(       a	  UUS   4-  nU	(       d  M  US   c  M  UUS   4-  nM     U R9                  U5      nU(       a  UU4-  nU(       a  UOS nU(       a  UR;                  5       nU
(       d  [=        S UUUU4 5       5      $ [?        UUUUUS9$ )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   r&   r  )r   r   r   r   r>  r   r   r   rX   r#   c              3   .   #    U  H  oc  M  Uv   M     g 7fr   r  ).0vs     rE   	<genexpr>%OlmoeModel.forward.<locals>.<genexpr>n  s     t$bq$bs   	)last_hidden_staterI  r^   
attentionsr+  ) rq   r   r>  rw  r   use_return_dictr   ri  r   r   r   re  r$   r
   r   from_legacy_cacheget_seq_lengthr'   aranger0   r&   r4   _update_causal_maskrh  rf  rA   _gradient_checkpointing_func__call__rg  to_legacy_cacher%   r   )rQ   ru  r   r   rI  rv  r   r   rw  r>  rx  r   return_legacy_cachepast_seen_tokensr   r^   r   all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                           rE   ra   OlmoeModel.forward  sS    2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<YZZ&&4==Yj I  --i8M $Z??"&&".."."@"@"Q##^ !CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L..>L]

 & #oomJ #7BD0d"6BD!![[)H4;;+H+HIM#!m%55!**t}} $ A A!**! #%("'! !.!#.!-#2&7)='#1(;
! *!,M%28I1q%Q" =#3"55##b(9(E!mB&7%99!O JR 		-0  -!11+4'$
#335Jt]J@QSa$bttt%+&+%+
 	
rV   input_tensorc           
      L   U R                   R                  S:X  a  Ub  SU;   a  U$ g Ub  UR                  5       OSn[        U[        5      nU R                   R                  S:X  a5  U(       d.  U(       d'  [
        R                  " UUUU R                  S9(       a  g UR                  UR                  pUR                  S   n
U(       a  UR                  5       nO5[        U[        R                  5      (       a  UR                  S   OXj-   S-   nU R                  UU
UUU	UUR                  S   S9nU R                   R                  S:X  aZ  UbW  UR                  R                  S	;   a=  U(       d6  [        R                   " U5      R"                  n[
        R$                  " X5      nU$ )
Nr  r  r   r  )rv  past_key_values_lengthis_trainingr   r#   )r@   target_lengthrZ   r&   r   r?   )r  xpunpu)rq   r8  r  r$   r   r   _ignore_causal_mask_sdpar   rZ   r&   r0   get_max_cache_shaper'   r   5_prepare_4d_causal_attention_mask_with_cache_positionru   finfor   _unmask_unattended)rQ   r   r  r   rI  r   r  using_static_cacherZ   r&   r@   r  r   	min_dtypes                 rE   r  OlmoeModel._update_causal_maskw  s    ;;++/BB)c^.C%%
 @O?Z?99;`a'E ;;++v5>PYj%>>*'7 MM	 $**L,?,?v&,,Q/+??AM nell;; $$R(%7!;  PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[KrV   r@   r  rZ   r&   r?   c                 \   U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n	[        R                  " X4XUS9nUS:w  a  [        R
                  " USS9nU[        R                  " X$S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU br  UR                  5       nU R                  S   n
USS2SS2SS2SU
24   U SS2SSSS24   -   nUS:H  nUSS2SS2SS2SU
24   R                  X5      USS2SS2SS2SU
24'   U$ )	a  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
        `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache,
        to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    device (`torch.device`):
        The device to place the 4D attention mask on.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
N   )
fill_valuerZ   r&   r   )diagonalrz  r#   r   )r"   r'   r  r   fulltriur  r2   r1   cloner0   masked_fill)r   r@   r  rZ   r&   r   r?   r   r   r  mask_lengthpadding_masks               rE   r  @OlmoeModel._prepare_4d_causal_attention_mask_with_cache_position  sX   B %.*<*<*>!*C(K& # E*..I** 0Y\bK !##jjqA5<<EH^H^_acdHeeeK%dD!Q&67>>z1bRTUK))//1,2226*1aL[L+@ANSTVZ\`bcScDdd+q05@Aq,;,AV5W5c5c 6Aq!\k\12 rV   )re  ri  rf  rg  rR  rh  rd  )NNNNNNNNNNN)rg   rh   ri   rj   r   rL   rn  rs  r   r   r'   r   r   r   r
   r   rE  r   r   r   ra   r  staticmethodr   rZ   r&   r  rk   rl   rm   s   @rE   ra  ra    s   {  !"  151537KO59$(,0/3/3&*59E
E,,-E
 !.E
 u//0	E

 "%tE4E4E/F(F"GHE
   1 12E
 D>E
 $D>E
 'tnE
 'tnE
 d^E
 !!1!12E
 
u,,	-E
 E
N?? ll? 	?
 ?  ?B 555 5 {{	5
 5 5 5 5rV   ra  c                      ^  \ rS rSrS/rU 4S jrS rS rS rS r	S r
S	 r\             SS
\\R                     S\\R                      S\\R                     S\\\R$                        S\\R$                     S\\R                     S\\   S\\   S\\   S\\   S\\   S\\R                     S\\\R                   4   S\\\4   4S jj5       rSrU =r$ )OlmoeForCausalLMi  zlm_head.weightc                 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   )rK   rL   ra  rH  rd  r   r   rR   lm_headrouter_aux_loss_coefr   r  rj  r   s     rE   rL   OlmoeForCausalLM.__init__  s}     '
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#= rV   c                 .    U R                   R                  $ r   rH  re  rd   s    rE   rn  %OlmoeForCausalLM.get_input_embeddings   s    zz&&&rV   c                 $    XR                   l        g r   r  rq  s     rE   rs  %OlmoeForCausalLM.set_input_embeddings  s    "'

rV   c                     U R                   $ r   r  rd   s    rE   get_output_embeddings&OlmoeForCausalLM.get_output_embeddings  s    ||rV   c                     Xl         g r   r  )rQ   new_embeddingss     rE   set_output_embeddings&OlmoeForCausalLM.set_output_embeddings	  s    %rV   c                     Xl         g r   rH  )rQ   decoders     rE   set_decoderOlmoeForCausalLM.set_decoder  s    
rV   c                     U R                   $ r   r  rd   s    rE   get_decoderOlmoeForCausalLM.get_decoder  s    zzrV   ru  r   r   rI  rv  labelsr   r   rw  r>  rx  r   logits_to_keepr   c                 v   Ub  UOU R                   R                  nU
b  U
OU R                   R                  n
U	b  U	OU R                   R                  n	Ub  UOU R                   R                  nU R                  UUUUUUUU	U
UUS9nUS   n[        U[        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      nSnUb  U R                  " UX`R                  40 UD6nSnU
(       af  [        U(       a  UR                  OUS   U R                  U R                  U5      nUb+  UU R                   UR#                  UR$                  5      -  -  nU(       d!  U4USS -   nU
(       a  U4U-   nUb  U4U-   $ U$ ['        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)ru  r   r   rI  rv  r   r   rw  r>  rx  r   r   r#   r   )lossaux_losslogitsrI  r^   r  r+  )rq   r   r>  rw  r  rH  r$   r   slicer  loss_functionrd  rF   r+  r   r  r  r)   r&   r   rI  r^   r  )rQ   ru  r   r   rI  rv  r  r   r   rw  r>  rx  r   r  loss_kwargsrC  r^   slice_indicesr  r  r  outputs                         rE   ra   OlmoeForCausalLM.forward  s   R 2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 &1%<k$++B]B] **)%+'/!5!5#)  
  
8B>SV8W8W~ot4]kmA}a,?@A%%ffooUUD/)4%%'"+  ((	H !11HKK4LLLY,F#"v-'+'7D7V#CVC(#33!//))!//
 	
rV   )r  rH  r   r  r  rd  )NNNNNNNNNNNNr   )rg   rh   ri   rj   _tied_weights_keysrL   rn  rs  r  r  r  r  r   r   r'   r   r   r   rE  r   r   r   r   r   ra   rk   rl   rm   s   @rE   r  r    s   *+
'(&  151537=A59-1$(,0/3/3&*5934b
E,,-b
 !.b
 u//0	b

 "$u'8'8"9:b
   1 12b
 ))*b
 D>b
 $D>b
 'tnb
 'tnb
 d^b
 !!1!12b
 c5<</0b
  
u//	0!b
 b
rV   r  )r  ra  rG  )NrX   N)Nr   )Br   r   typingr   r   r   r   r'   torch.nn.functionalr   r*   r%  torch.utils.checkpointactivationsr	   cache_utilsr
   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   pytorch_utilsr   utilsr   r   configuration_olmoer   r   
get_loggerrg   r   r   r   rF   ModulerH   appendro   r   r   r   r   r   r   r  r7  r  r5  rG  ra  r  __all__r  rV   rE   <module>r     s     / /      ! ; ; ) > h Q K - 1 , , J 
		H	% "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&dJ299 J(   L )<299 <F(8ryy "	UU\\ 	U# 	U%,, 	Ug9RYY g9Ti9> i9X\1 \1@ - -2")) -2`T		 Tn ?? ? ?4 V% V VrD
+_ D
N ErV   