
    qi{                        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* ddl+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2  ed       G d dejf                               Z4 G d dejf                        Z5 G d dejf                        Z6d Z7 ed      dAd       Z8d ejr                  d!e:d"ejr                  fd#Z;	 dBd$ejf                  d%ejr                  d&ejr                  d'ejr                  d(ejr                  dz  d)e<d*e<d+e&e(   fd,Z= ee8       G d- d.ejf                               Z>e G d/ d0ejf                               Z? G d1 d2ejf                        Z@ G d3 d4ejf                        ZA G d5 d6e      ZBe) G d7 d8e$             ZCe) G d9 d:eC             ZD	 	 	 dCd;ejr                  eEejr                     z  dz  d<e:dz  d(ejr                  dz  d"ejr                  e:z  fd=ZFe) G d> d?eCe             ZGg d@ZHy)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                   `     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      Z/opt/pipecat/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.   r4   input_dtypevariances       r2   forwardzOlmoeRMSNorm.forward:   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler,   shaper-   )r.   s    r2   
extra_reprzOlmoeRMSNorm.extra_reprA   s*    ))*+6$2G2G1HIIr3   )gh㈵>)r%   N)	__name__
__module____qualname__r(   r*   TensorrA   rE   __classcell__r1   s   @r2   r$   r$   0   s)    $;U\\ ;ell ;Jr3   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defaultrN   F)
persistentoriginal_inv_freq)r'   r(   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrO   rope_parametersrQ   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r.   rO   devicerope_init_fnrN   r1   s        r2   r(   zOlmoeRotaryEmbedding.__init__H   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr3   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   r6   r9   )r]   r9   )	rX   getattrr/   num_attention_headsr*   arangeint64r:   float)rO   r]   r_   basedimattention_factorrN   s          r2   rY   z4OlmoeRotaryEmbedding.compute_default_rope_parametersX   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r3   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   r7   r    mpscpuF)device_typeenabledr6   rj   rc   )rN   rh   expandrD   r:   r]   
isinstancetypestrr   	transposer*   catcosrZ   sinr9   )
r.   xposition_idsinv_freq_expandedposition_ids_expandedro   freqsembrx   ry   s
             r2   rA   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)rF   rG   rH   r*   rI   __annotations__r!   r(   staticmethodr   intrC   rh   rY   no_gradr   rA   rJ   rK   s   @r2   rM   rM   E   s    llV{ V  %)+/"*d"*(* t* 
~u$	%	* *: U]]_<  <r3   rM   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(   rO   r/   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnr.   rO   r1   s     r2   r(   zOlmoeMLP.__init__   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r3   c                     | j                  | j                  | j                  |            | j                  |      z        }|S r   )r   r   r   r   )r.   rz   r   s      r2   rA   zOlmoeMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r3   rF   rG   rH   r(   rA   rJ   rK   s   @r2   r   r      s    0r3   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..Nr7   r6   rq   )rD   r*   rw   )rz   x1x2s      r2   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   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krx   ry   unsqueeze_dimq_embedk_embeds          r2   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr3   r4   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)rD   rr   reshape)r4   r   batchnum_key_value_headsslenrb   s         r2   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr3   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 )Nr6   r   r7   )rj   r9   )ptrainingr    )r   num_key_value_groupsr*   matmulrv   r   
functionalsoftmaxr;   r:   r9   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r2   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$$r3   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' paperNrO   	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 )Nrb   g      Tr   r0   )r'   r(   rO   r   rd   r/   re   rb   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.   rO   r   r1   s      r2   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
r3   r4   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 )	Nr7   )minmaxr    r6   )ry   rx   r           sliding_window)r   r   r   )rD   rb   r   r   r   r   r   rO   clip_qkvclamp_viewrv   r   updater   r   get_interface_attn_implementationr   r   r   r   rd   r   r   r   )r.   r4   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   rx   ry   cache_kwargsattention_interfacer   r   s                     r2   rA   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((r3   r   )NN)rF   rG   rH   __doc__r!   r   r(   r*   rI   rC   r	   
LongTensorr   r   rA   rJ   rK   s   @r2   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)r3   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.rO   c                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )Nr6   )r'   r(   num_local_expertsnum_expertsr/   
hidden_dimr   intermediate_dimr   r)   r*   emptygate_up_projr   r   r   r   r   s     r2   r(   zOlmoeExperts.__init__4  s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r3   r4   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_classesr6   r    r   )r7   rq   r7   )r*   
zeros_liker   r   r   one_hotr   permutegreatersumnonzerowherelinearr   chunkr   r   
index_add_r:   r9   )r.   r4   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r2   rA   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)
rF   rG   rH   r   r!   r(   r*   rI   rA   rJ   rK   s   @r2   r   r   0  sM    <0{ 0#||# \\# ||	#
 
#r3   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_probr/   r   r   r)   r*   zerosr,   r   s     r2   r(   zOlmoeTopKRouter.__init__Y  si    //
!--$33 ,,ll5;;t/?/?#QRr3   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 )Nr7   )r9   rj   rq   T)rj   r8   )r   r   Fr   r,   r*   r   r   r   rh   topkr	  r
  r   r:   r9   )r.   r4   router_logitsrouter_top_valuerouter_indicesrouter_scoress         r2   rA   zOlmoeTopKRouter.forwarda  s    %--b$//B<++33MZ\3]+0::mTZZUW+X(. 0 4 4T 4 JJ+..}/B/BC(m^;;r3   r   rK   s   @r2   r  r  X  s    S	<r3   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     r2   r(   zOlmoeSparseMoeBlock.__init__n  s&    #F+	#F+r3   r4   r%   c                     |j                   \  }}}|j                  d|      }| j                  |      \  }}}| j                  |||      j	                  |||      }|S )Nr7   )rD   r   r  r  r   )	r.   r4   
batch_sizesequence_lengthr   _r   r   r   s	            r2   rA   zOlmoeSparseMoeBlock.forwards  sh    2?2E2E/
OZ%**2z:(,		-(@%=+"ll=+}U]]
 #"r3   )rF   rG   rH   r(   r*   rI   rA   rJ   rK   s   @r2   r  r  m  s#    ,
#U\\ #ell #r3   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 )OlmoeDecoderLayerrO   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)rO   r   r   )r'   r(   r/   r   	self_attnr  mlpr$   r   input_layernormpost_attention_layernormr   s      r2   r(   zOlmoeDecoderLayer.__init__~  sl    !--'vK&v.+F,>,>FDWDWX(4V5G5GVM`M`(a%r3   Nr4   r   r{   r   	use_cacher   r   r   r%   c                     |}	| j                  |      } | j                  d|||||||d|\  }}
|	|z   }|}	| j                  |      }| j                  |      }|	|z   }|S )N)r4   r   r{   r   r"  r   r    )r   r  r!  r  )r.   r4   r   r{   r   r"  r   r   r   residualr  s              r2   rA   zOlmoeDecoderLayer.forward  s     !,,];)4>> 	
')%+) 3	
 	
q !=0 !55mD/ =0r3   )NNNFNN)rF   rG   rH   r!   r   r(   r*   rI   r   r	   boolrC   r   r   rA   rJ   rK   s   @r2   r  r  }  s    b{ bs b /304(,!&26HL|| t+ &&-	
  $; ((4/ #5<<#=>E +, 
r3   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dZ ej$                         d	        Zy
)OlmoePreTrainedModelrO   modelTr  r   r   )index)r  r4   
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_weightsrs   r   initnormal_r   rO   initializer_ranger   r  r,   )r.   r   s     r2   r.  z"OlmoePreTrainedModel._init_weights  s    %%dF3fl+LL,,3DKK<Y<YZLL))9V9VW0LLSdkk6S6ST 1r3   N)rF   rG   rH   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_outputs_supports_attention_backendr*   r   r.  r$  r3   r2   r(  r(    sm    &*#,-#4"5N'qA*$ #'U]]_U Ur3   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 )
OlmoeModelrO   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   rO   F)r'   r(   pad_token_idpadding_idx
vocab_sizer   	Embeddingr/   embed_tokens
ModuleListrangenum_hidden_layersr  layersr$   r   normrM   
rotary_embgradient_checkpointing	post_initr   s      r2   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]   )rO   rL  r   r   r   r{   )r   r   r{   r   r"  r   )last_hidden_stater   )
ValueErrorr
   rO   rB  get_seq_lengthr*   rf   rD   r]   r   r   rH  rF  rE  rG  r   )r.   rK  r   r{   r   rL  r"  r   r   past_seen_tokenscausal_maskr4   r   decoder_layers                 r2   rA   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%++
 	
r3   )NNNNNNN)rF   rG   rH   r!   r(   r   r   r   r*   r   rI   r	   FloatTensorr&  r   r   r   rA   rJ   rK   s   @r2   r;  r;    s    {    .2.204(,26!%26;
##d*;
 t+;
 &&-	;

 ;
 ((4/;
 $;;
 ((4/;
 +,;
 
 ;
    ;
r3   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   rq   r7   )rs   rC   r]   r*   rw   r:   r   r   r   r  r   r=   rh   rD   rr   r   r   r   )rU  r   r	  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr  selected_expertsr   tokens_per_expertrouter_prob_per_expertr  r  rE  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r2   load_balancing_loss_funcra    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_outputr4   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _
        |j                  | _        | j                          y r   )r'   r(   r;  r)  r@  r   r   r/   rd  router_aux_loss_coefr   r  rJ  r   s     r2   r(   zOlmoeForCausalLM.__init__m  s     '
 ++yy!3!3V5F5FUS$*$?$?!!--#)#=#=  	r3   NrK  r   r{   r   rL  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)rK  r   r{   r   rL  r"  rj  r   )lossaux_lossrf  r   r4   r+  r  r$  )rO   rj  r)  rN  rs   r   slicerd  loss_functionr@  ra  r  r   r  rh  r:   r]   r   r   r4   r+  )r.   rK  r   r{   r   rL  ri  r"  rj  r   rk  r   outputsr4   slice_indicesrf  rm  rn  s                     r2   rA   zOlmoeForCausalLM.forwardy  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!//))!//
 	
r3   )
NNNNNNNNNr   )rF   rG   rH   _tied_weights_keys_tp_plan_pp_planr(   r   r   r*   r   rI   r	   rT  r&  r   r   r   r   rA   rJ   rK   s   @r2   rc  rc  g  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
r3   rc  )rc  r;  r(  )r    )r   )Nr6   N)Icollections.abcr   typingr   r*   torch.nn.functionalr   r   r   r   r/  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$   rM   r   r   r   rI   r   r   rh   r   r   r   r  r  r  r(  r;  rC   ra  rc  __all__r$  r3   r2   <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 )*P)RYY P) +P)f $#299 $# $#N<bii <*#")) # (2 (V U? U U4 N
% N
 N
f #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d f
+_ f
 f
R Er3   