
    Z jy}                     2   S SK Jr  S SKJrJr  S SKrS SKJr  SSKJr	  SSK
Jr  SSKJrJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJrJr  SSKJrJr  SSKJrJr  SSK J!r!  SSK"J#r#J$r$J%r%  SSK&J'r'J(r(  SSK)J*r*  SSK+J,r,   " S S\RZ                  5      r.S r/\" S5      S@S j5       r0S\Rb                  S\2S\Rb                  4S jr3 SAS\RZ                  S \Rb                  S!\Rb                  S"\Rb                  S#\Rb                  S-  S$\4S%\4S&\!\#   4S' jjr5 " S( S)\RZ                  5      r6 " S* S+\RZ                  5      r7 " S, S-\RZ                  5      r8 " S. S/\RZ                  5      r9 " S0 S1\RZ                  5      r: " S2 S3\RZ                  5      r; " S4 S5\5      r< " S6 S7\5      r=\$ " S8 S9\=5      5       r>   SBS:\Rb                  \?\Rb                     -  S-  S;\2S-  S#\Rb                  S-  S\Rb                  \2-  4S< jjr@ " S= S>\=\5      rA/ S?QrBg)C    )Callable)AnyOptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_func_from_hub)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)capture_outputs   )
DbrxConfigc                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )DbrxRotaryEmbedding,   inv_freqNconfigc                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultr"   F)
persistentoriginal_inv_freq)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr#   rope_parametersr%   compute_default_rope_parametersr   attention_scalingregister_bufferclone)selfr#   devicerope_init_fnr"   	__class__s        w/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/dbrx/modeling_dbrx.pyr*   DbrxRotaryEmbedding.__init__/   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuU    r4   ztorch.deviceseq_lenreturnztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetahead_dimN      ?r      dtype)r4   rB   )	r.   getattrhidden_sizenum_attention_headstorcharangeint64tofloat)r#   r4   r:   basedimattention_factorr"   s          r7   r/   3DbrxRotaryEmbedding.compute_default_rope_parameters?   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r9   c                 L   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r   mpscpuF)device_typeenabledr@   rL   rA   )r"   rJ   expandshaperI   r4   
isinstancetypestrr   	transposerF   catcosr0   sinrB   )
r3   xposition_idsinv_freq_expandedposition_ids_expandedrS   freqsembr]   r^   s
             r7   forwardDbrxRotaryEmbedding.forward]   sN    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F#)r0   r#   r,   r-   r%   NNNN)__name__
__module____qualname____firstlineno__rF   Tensor__annotations__r   r*   staticmethodr   inttuplerJ   r/   no_gradr   re   __static_attributes____classcell__r6   s   @r7   r    r    ,   s    llVz V V  $(+/"*T!*(* t* 
~u$	%	* *: ]]_<  <r9   r    c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..NrP   r@   rU   )rW   rF   r\   )r_   x1x2s      r7   rotate_halfry   m   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r9   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  Applies Rotary Position Embedding to the query and key tensors.

Args:
    q (`torch.Tensor`): The query tensor.
    k (`torch.Tensor`): The key tensor.
    cos (`torch.Tensor`): The cosine part of the rotary embedding.
    sin (`torch.Tensor`): The sine part of the rotary embedding.
    unsqueeze_dim (`int`, *optional*, defaults to 1):
        The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
        sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
        that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
        k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
        cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
        the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
    `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
)	unsqueezery   )qkr]   r^   unsqueeze_dimq_embedk_embeds          r7   apply_rotary_pos_embr   t   sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0Gr9   hidden_statesn_repr;   c                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )z
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
r   N)rW   rV   reshape)r   r   batchnum_key_value_headsslenr>   s         r7   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr9   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub  X-   n
[
        R                  R                  U
S[        R                  S9R                  UR                  5      n
[
        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )Nr@   r   rP   rL   rB   ptrainingr   )r   num_key_value_groupsrF   matmulr[   r   
functionalsoftmaxfloat32rI   rB   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r7   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r9   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-  S\R                  S-  S	\
S-  S
\\R                  \R                  4   4
S jjrSrU =r$ )DbrxAttention   zYModular DBRX attention component that can be reused across different model architectures.N	layer_idxc                   > [         TU ]  5         Xl        UR                  U l        UR
                  U l        U R                  U R                  -  U l        UR                  U l	        X l
        UR                  nUR                  U l        UR                  U l        UR                  U l        U R                  U R                   -  U l        U R                  S-  U l        UR&                  U l        SU l        [*        R,                  " U R                  U R                  SU R                   -  U R                  -  -   SS9U l        [*        R,                  " U R                  U R                  SS9U l        g )Ng      Tr@   Fbias)r)   r*   r#   d_modelrD   n_heads	num_headsr>   max_seq_lenr+   r   attn_config
attn_pdropattention_dropoutclip_qkv
kv_n_headsr   r   r   r=   	is_causalr   LinearWqkvout_proj)r3   r#   r   r   r   r6   s        r7   r*   DbrxAttention.__init__   s&    	!>>((DNN:'-'9'9$"((!,!7!7#,,#.#9#9 $(NNd6N6N$N!}}d*%00IId..T5M5M1MPTP]P]1]]di
	 		$"2"2D4D4D5Qr9   r   r   position_embeddingspast_key_valuesr;   c                    UR                   S S n/ UQSPU R                  P7nU R                  U5      nU R                  b  U R                  * OS n	UR	                  XR                  S9nUR                  U R                  U R                  U R                  -  U R                  U R                  -  /SS9u  pnU
R                  U5      R                  SS5      n
UR                  U5      R                  SS5      nUR                  U5      R                  SS5      nUu  p[        XX5      u  pUb  UR                  XU R                  5      u  p[        R                  " U R                  R                   ["        5      nU" U U
UUU4U R$                  (       d  SOU R&                  U R(                  S.UD6u  nnUR*                  " / UQSP76 R-                  5       nU R/                  U5      nUU4$ )NrP   )minmaxr@   rU   r           )r   r   )rW   r>   r   r   clampsplitrD   r   viewr[   r   updater   r   get_interfacer#   _attn_implementationr   r   r   r   r   r   r   )r3   r   r   r   r   r   input_shapehidden_shape
qkv_statesmin_valquery_statesr   r   r]   r^   attention_interfacer   r   s                     r7   re   DbrxAttention.forward   s    $))#2.88b8$--8YY}-
$(MM$=4==.4%%'}}%E
1;1A1A  ((4==8((4==8
  2B 2
., $((6@@AF__\2<<QB
#((6@@AF&#7RU#[ &'6'='=jX\XfXf'g$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ "));;;;FFHmmK0L((r9   )r   r   r   r#   r>   rD   r   r   r+   r   r   r   r   r=   r   rg   rh   )ri   rj   rk   rl   __doc__rp   r*   rF   rm   
LongTensorr
   rq   re   rs   rt   ru   s   @r7   r   r      s    c
 !%R :R R> /37;(,3)||3) t+3) #--4	3)
 3) 
u||U\\)	*3) 3)r9   r   c            
          ^  \ rS rSrU 4S jrS\R                  S\R                  S\R                  S\R                  S\R                  4
S jrS	rU =r	$ )
DbrxExpertGLUi  c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        [
        R                  " [        R                  " U R                  U R                  -  U R                  5      5      U l	        [
        R                  " [        R                  " U R                  U R                  -  U R                  5      5      U l
        [
        R                  " [        R                  " U R                  U R                  -  U R                  5      5      U l        UR                  R                  SS5      n[        U   U l        g )Nnamesilu)r)   r*   rD   ffn_hidden_sizemoe_num_expertsr   	ParameterrF   emptyw1v1w2
ffn_act_fngetr	   activation_fn)r3   r#   act_fn_namer6   s      r7   r*   DbrxExpertGLU.__init__	  s    !--%55%55,,u{{4+?+?$BVBV+VX\XhXhij,,u{{4+?+?$BVBV+VX\XhXhij,,u{{4+?+?$BVBV+VX\XhXhij''++FF;#K0r9   r_   	expert_w1	expert_v1	expert_w2r;   c                     UR                  U5      nUR                  U5      nU R                  U5      nXV-  nUR                  UR                  5       5      nU$ rg   )r   r   t)	r3   r_   r   r   r   	gate_projup_projintermediate_states	down_projs	            r7   re   DbrxExpertGLU.forward  sU     HHY'	((9%&&y1	'1'..y{{}=	r9   )r   r   rD   r   r   r   r   
ri   rj   rk   rl   r*   rF   rm   re   rs   rt   ru   s   @r7   r   r     sP    1*/,,CH<<\a\h\h	 r9   r   c                      ^  \ rS rSrU 4S jrS\R                  S\R                  S\R                  S\R                  4S jrSrU =r	$ )	DbrxExpertsi!  c                    > [         TU ]  5         [        U5      U l        UR                  U l        UR
                  U l        UR                  U l        g rg   )r)   r*   r   mlprD   r   r   num_expertsr3   r#   r6   s     r7   r*   DbrxExperts.__init__"  sD     (!--%55!11r9   r   top_k_indextop_k_weightsr;   c                    UR                   S   nUR                  SU R                  5      n[        R                  " XR
                  UR                  S9n[        R                  " 5          [        R                  R                  R                  X R                  S9nUR                  SSS5      n[        R                  " UR                  SS9S5      R                  5       nS S S 5        SU R                  U R                   4nW GH  n	U	S   n	[        R                  " 5          [        R"                  " WU	   5      u  pS S S 5        U R$                  R&                  R)                  U5      U	   nU R$                  R*                  R)                  U5      U	   nU R$                  R,                  R)                  U5      U	   nU R%                  UW   XU5      nUR)                  SU R                  5      X;W
S 4   -  nUR/                  SX5        GM	     UR)                  USU R                  5      nU$ ! , (       d  f       GNT= f! , (       d  f       GN	= f)	Nr   rP   )rB   r4   )num_classesr@   r   )rP   rU   )rW   r   r   rF   
zeros_likerB   r4   rr   r   r   one_hotr   permutegreatersumnonzerorD   wherer   r   r   r   r   
index_add_)r3   r   r   r   
batch_sizenext_statesexpert_mask
expert_hitsplit_expert_shape
expert_idxidx	token_idxr   r   r   statess                   r7   re   DbrxExperts.forward)  s    #((+
%--b$2F2FG&&}<O<OXeXlXlm]]_((--55kO_O_5`K%--aA6K{8'DaHPPRJ 
 !$"6"68H8HI$J#AJ!&[-D!E !!!"45jAB!!"45jAB!!"45jABXXmI6CF[[T%9%9:]VY[_K_=``F""1i8 % "&&z2t7K7KL% _ !s   *A7H."I .
H= 
I	)r   rD   r   r   r   ru   s   @r7   r   r   !  sH    2|| \\ ||	
 
 r9   r   c                      ^  \ rS rSrU 4S jrS\R                  S\\R                  \R                  \R                  4   4S jr	Sr
U =r$ )
DbrxRouteriH  c                    > [         TU ]  5         UR                  U l        UR                  U l        [
        R                  " U R                  UR                  SS9U l        g NFr   )	r)   r*   r   rD   moe_jitter_epsr   r   r   layerr   s     r7   r*   DbrxRouter.__init__I  sJ    !11$33YYt//1G1GeT
r9   r   r;   c                 (   U R                   (       aP  U R                  bC  U[        R                  " U5      R	                  SU R                  -
  SU R                  -   5      -  nUR                  SUR                  S   5      nU R                  U5      nU$ )Nr?   rP   )r   r  rF   
empty_likeuniform_r   rW   r  )r3   r   router_logitss      r7   re   DbrxRouter.forwardO  s    ==T00<U--m<EEd)))31D1D+D M &**2}/B/B2/FG

=1r9   )rD   r  r  )ri   rj   rk   rl   r*   rF   rm   rq   r   re   rs   rt   ru   s   @r7   r  r  H  s@    UU\\ eELL%,,X]XhXh<h6i  r9   r  c                      ^  \ rS rSrSrU 4S jrS rS\R                  S\	\R                  \R                  4   4S jr
SrU =r$ )	DbrxFFNiY  z0Modular DBRX MLP/FFN component with MoE support.c                    > [         TU ]  5         [        UR                  5      U l        [        UR                  5      U l        UR                  R                  U l        UR                  R                  U l	        g rg   )
r)   r*   r  
ffn_configrouterr   expertsmoe_normalize_expert_weights	moe_top_ktop_k)r3   r#   r   r6   s      r7   r*   DbrxFFN.__init__\  sY     !2!23"6#4#45,2,=,=,Z,Z)&&00
r9   c                    [         R                  R                  R                  USUR                  S9n[         R
                  " XR                  SS9u  p#U R                  b#  U[         R                  " X R                  SSS9-  nX#4$ )Nr   r   rP   rU   T)r   rL   keepdim)	rF   r   r   r   rB   topkr  r  norm)r3   r  router_top_valuerouter_indicess       r7   route_tokens_to_expertsDbrxFFN.route_tokens_to_expertsd  s~    ++33MqP]PcPc3d+0::mZZUW+X(,,8/%** $E$E2W[3    //r9   r   r;   c                 r    U R                  U5      nU R                  U5      u  p4U R                  XU5      nU$ rg   )r  r#  r  )r3   r   r  r   r   outputs         r7   re   DbrxFFN.forwardm  s8    M2%)%A%A-%P"m-Hr9   )r  r  r  r  )ri   rj   rk   rl   r   r*   r#  rF   rm   rq   re   rs   rt   ru   s   @r7   r  r  Y  s>    :10U\\ eELL%,,<V6W  r9   r  c                      ^  \ rS rSrSS\S\S-  4U 4S jjjr  SS\R                  S\R                  S\R                  S-  S	\
S-  S
\S\\R                  \R                  4   4S jjrSrU =r$ )DbrxNormAttentionNormit  Nr#   r   c                    > [         TU ]  5         X l        UR                  U l        [        R
                  " UR                  SS9U l        [        UUS9U l	        [        R
                  " UR                  SS9U l
        g )NFr   r#   r   )r)   r*   r   resid_pdropr   	LayerNormr   norm_1r   attnnorm_2r3   r#   r   r6   s      r7   r*   DbrxNormAttentionNorm.__init__u  sa    "!--ll6>>>!
	 ll6>>>r9   r   r   r   r   r   r;   c                 V   UnU R                  U5      R                  UR                  5      nU R                  " SUUUUS.UD6u  p[        R
                  R                  XR                  U R                  S9nX-   nUnU R                  U5      R                  UR                  5      nXa4$ N)r   r   r   r   r    )
r.  rI   rB   r/  r   r   r   r,  r   r0  )r3   r   r   r   r   r   residual_states_s           r7   re   DbrxNormAttentionNorm.forward  s     (M255m6I6IJ99 
') 3+	

 
 --m?O?OZ^ZgZg-h%7'M255m6I6IJ--r9   )r/  r   r.  r0  r,  rg   )NN)ri   rj   rk   rl   r   rp   r*   rF   rm   r   r
   r   rq   re   rs   rt   ru   s   @r7   r)  r)  t  s    	?z 	?cDj 	? 	? /3(,.||. #--. t+	.
 . . 
u||U\\)	*. .r9   r)  c                      ^  \ rS rSrS\S\4U 4S jjr   SS\R                  S\R                  S-  S\R                  S-  S	\
S-  S
\4
S jjrSrU =r$ )	DbrxBlocki  r#   r   c                    > [         TU ]  5         UR                  U l        UR                  U l        X l        [        UUS9U l        [        US9U l	        g )Nr+  r#   )
r)   r*   r   rD   r,  r   r)  norm_attn_normr  ffnr1  s      r7   r*   DbrxBlock.__init__  sN    !>>!--"3
 &)r9   Nr   r   r   r   r   c                     U R                   " SUUUUS.UD6u  paU R                  U5      n[        R                  R	                  XR
                  U R                  S9nXa-   nU$ r4  )r=  r>  r   r   r   r,  r   )r3   r   r   r   r   r   resid_statess          r7   re   DbrxBlock.forward  sv     '+&9&9 '
') 3+	'

 '
# /--m?O?OZ^ZgZg-h$4r9   )r>  rD   r   r=  r,  rh   )ri   rj   rk   rl   r   rp   r*   rF   rm   r   r
   r   re   rs   rt   ru   s   @r7   r:  r:    sw    	*z 	*c 	* /37;(,|| t+ #--4	
   r9   r:  c                      ^  \ rS rSr% \\S'   SrSrS/rS/r	Sr
SrSrSrSr\\S.r\R&                  " 5       S	\R*                  4U 4S
 jj5       rSrU =r$ )DbrxPreTrainedModeli  r#   transformerTr:  r   F)r   
attentionsr   c                 <  > [         TU ]  U5        U R                  R                  n[	        U[
        5      (       aa  [        R                  " UR                  SUS9  [        R                  " UR                  SUS9  [        R                  " UR                  SUS9  g g )Nr   )meanstd)r)   _init_weightsr#   initializer_rangerX   r   initnormal_r   r   r   )r3   r   rI  r6   s      r7   rJ  !DbrxPreTrainedModel._init_weights  sm    f%kk++fm,,LL#6LL#6LL#6 -r9   r5  )ri   rj   rk   rl   r   rn   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flex_attn_supports_attention_backend_supports_flash_attn_supports_sdpa_can_compile_fullgraphr:  r   _can_record_outputsrF   rr   r   ModulerJ  rs   rt   ru   s   @r7   rD  rD    sv    %&*#$#4"5"&N""#
 ]]_7BII 7 7r9   rD  c                   J  ^  \ rS rSrSrS\4U 4S jjrS\R                  4S jr	S\R                  4S jr
\\\      SS
\R                  S	-  S\R                   S	-  S\R                  S	-  S\S	-  S\R$                  S	-  S\S	-  S\\   S\4S jj5       5       5       rSrU =r$ )	DbrxModeli  a  Transformer decoder consisting of *config.num_hidden_layers*. Each layer is a [`DbrxBlock`] layer.

Args:
    config ([`DbrxConfig`]): Model configuration class with all parameters of the model.
        Initializing with a config file does not load the weights associated with the model, only the
        configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
r#   c           	      0  > [         TU ]  U5        UR                  U l        UR                  U l        UR
                  U l        [        U5      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        [        R"                  " UR                  SS9U l        SU l        U R)                  5         g s  snf r
  )r)   r*   pad_token_idpadding_idx
vocab_size	emb_pdropr    
rotary_embr   	Embeddingr   wte
ModuleListrangen_layersr:  blocksr-  norm_fgradient_checkpointing	post_initr1  s      r7   r*   DbrxModel.__init__  s     !.. ++))-f5<< 1 16>>4CSCSTmmSXY_YhYhSi$jSiiYv%ASi$jkll6>>>&+# 	 %ks   6Dr;   c                     U R                   $ rg   rc  r3   s    r7   get_input_embeddingsDbrxModel.get_input_embeddings  s    xxr9   r   c                     Xl         g rg   rm  r3   r   s     r7   set_input_embeddingsDbrxModel.set_input_embeddings  s    r9   N	input_idsr   r`   r   inputs_embeds	use_cacher   c           
      B   US L US L-  (       a  [        S5      eU(       a  Uc  [        U R                  S9nUc  U R                  U5      nUcU  Ub  UR	                  5       OSn[
        R                  " UR                  S   UR                  S9U-   nUR                  S5      n[        U R                  UUUUS9n	Un
U R                  X5      nU R                  S U R                  R                    H  nU" U
4UU	UUUS.UD6n
M     U R                  U
5      n
[        U
US9$ )	Nz:You must specify exactly one of input_ids or inputs_embedsr<  r   r   )r4   )r#   rv  r   r   r`   )r   r   r`   r   rw  )last_hidden_stater   )
ValueErrorr   r#   rc  get_seq_lengthrF   rG   rW   r4   r|   r   ra  rg  num_hidden_layersrh  r   )r3   ru  r   r`   r   rv  rw  r   past_seen_tokenscausal_maskr   r   decoder_layers                r7   re   DbrxModel.forward  sD    -t";<YZZ0*$++>O  HHY/MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L(;;')+%
 & #oomJ![[)H4;;+H+HIM)$7*) /# M J M2%++
 	
r9   )rg  r`  ri  rh  r^  ra  r_  rc  )NNNNNN)ri   rj   rk   rl   r   r   r*   r   rb  ro  rs  r   r   r   rF   r   rm   r
   FloatTensorboolr   r   r   re   rs   rt   ru   s   @r7   r[  r[    s    z bll ",,    .2.204(,26!%5
##d*5
 t+5
 &&-	5

 5
 ((4/5
 $;5
 +,5
 
 5
    5
r9   r[  gate_logitsr   c                    U b  [        U [        5      (       d  g[        U [        5      (       aC  U S   R                  n[        R                  " U  Vs/ s H  oUR                  U5      PM     snSS9n[        R                  R                  R                  WSS9n[        R                  " XrSS9u  p[        R                  R                  R                  X5      n
Uc:  [        R                  " U
R                  5       SS9n[        R                  " USS9nGOUR                  u  pUR                  S   X-  -  nUSSS2SS2SS4   R                  XXU45      R                  SX!5      R                  W5      n[        R                   " U
R                  5       U-  SS9[        R                   " USS9-  nUSSS2SS2S4   R                  XX45      R                  SU5      R                  U5      n[        R                   " UU-  SS9[        R                   " USS9-  n[        R                   " XR#                  S5      -  5      nUU-  $ s  snf )ax  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
experts is too unbalanced.

Args:
    gate_logits:
        Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
        shape [batch_size X sequence_length, num_experts].
    num_experts:
        Number of experts
    top_k:
        The number of experts to route per-token, can be also interpreted as the `top-k` routing
        parameter.
    attention_mask (`torch.Tensor`, *optional*):
        The attention_mask used in forward function
        shape [batch_size X sequence_length] if not None.

Returns:
    The auxiliary loss.
Nr   rU   rP   )rX   rq   r4   rF   r\   rI   r   r   r   r  r   rH  rJ   rW   rV   r   r   r|   )r  r   r  r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr7  selected_expertsr   tokens_per_expertrouter_prob_per_expertr   sequence_lengthr|  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r7   load_balancing_loss_funcr  1  s+   : *[%"@"@+u%%$Q..#(99^i-j^iPZmmN.K^i-jpq#r hh))112JPR1SO**_DA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
4::1=*B^_ 4AtT12V&OKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&OQRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1Q1QRS1TTUL+%%[ .ks   Ic                     ^  \ rS rSrSS0rSS0rSS/S/40rS\4U 4S	 jjrS
\	R                  4S jrS\	R                  4S jrS
\	R                  4S jrS\	R                  4S jrS\4S jrS
\4S jr\\         S!S\R,                  S-  S\R.                  S-  S\R,                  S-  S\S-  S\R2                  S-  S\R,                  S-  S\S-  S\S-  S\\R.                  -  S\\   S
\4S jj5       5       rS r U =r!$ )"DbrxForCausalLMi  zlm_head.weightztransformer.wte.weightlm_headcolwise_gather_outputr   logitsr#   c                   > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  R                  U l        UR                  R                  U l        UR                  R                  U l        U R!                  5         g r
  )r)   r*   r[  rE  r_  r   r   rD   r  r  moe_loss_weightrouter_aux_loss_coefr   r   r  num_experts_per_tokrj  r   s     r7   r*   DbrxForCausalLM.__init__  s     $V, ++yy!3!3V5F5FUS$*$5$5$E$E!!,,<<#)#4#4#>#> r9   r;   c                 6    U R                   R                  5       $ rg   )rE  ro  rn  s    r7   ro  $DbrxForCausalLM.get_input_embeddings  s    4466r9   r   c                 :    U R                   R                  U5        g rg   )rE  rs  rr  s     r7   rs  $DbrxForCausalLM.set_input_embeddings  s    --e4r9   c                     U R                   $ rg   r  rn  s    r7   get_output_embeddings%DbrxForCausalLM.get_output_embeddings  s    ||r9   new_embeddingsc                     Xl         g rg   r  )r3   r  s     r7   set_output_embeddings%DbrxForCausalLM.set_output_embeddings  s    %r9   decoderc                     Xl         g rg   rE  )r3   r  s     r7   set_decoderDbrxForCausalLM.set_decoder  s    "r9   c                     U R                   $ rg   r  rn  s    r7   get_decoderDbrxForCausalLM.get_decoder  s    r9   Nru  r   r`   r   rv  labelsrw  output_router_logitslogits_to_keepr   c
                 z   Ub  UOU R                   R                  nU R                  " SUUUUUUUS.U
D6nUR                  n[	        U	[
        5      (       a  [        U	* S5      OU	nU R                  USS2USS24   5      nSnUb  U R                  " XU R                  40 U
D6nSnU(       aY  [        UR                  U R                  U R                  U5      nUb*  XR                  UR                  UR                   5      -  -  n[#        UUUUR$                  UR&                  UR(                  UR                  S9$ )a  
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, DbrxForCausalLM

>> model = DbrxForCausalLM.from_pretrained("transformers-community/dbrx-instruct")
>> tokenizer = AutoTokenizer.from_pretrained("transformers-community/dbrx-instruct")

>> 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 conscious, but I can talk to you."
```
N)ru  r   r`   r   rv  rw  r  )lossaux_lossr  r   r   rF  r  r5  )r#   r  rE  ry  rX   rp   slicer  loss_functionr_  r  r  r   r  r  rI   r4   r   r   r   rF  )r3   ru  r   r`   r   rv  r  rw  r  r  r   outputsr   slice_indicesr  r  r  s                    r7   re   DbrxForCausalLM.forward  sR   N %9$D $++JjJj 	
 +/*:*: 	+
)%+'!5	+
 	+
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r9   )r  r   r  r  rE  r_  )	NNNNNNNNr   )"ri   rj   rk   rl   _tied_weights_keys_tp_plan_pp_planr   r*   r   rb  ro  rs  r   r  r  r[  r  r  r   r   rF   r   rm   r
   r  r  rp   r   r   r   re   rs   rt   ru   s   @r7   r  r    s   *,DE23H_-z:;Hz 7bll 75",, 5ryy &BII &#9 # Y    .2.204(,26*.!%,0-.P
##d*P
 t+P
 &&-	P

 P
 ((4/P
   4'P
 $;P
 #TkP
 ell*P
 +,P
 
#P
  P
r9   r  )r  r[  rD  )r   )r   )Nr@   N)Ccollections.abcr   typingr   r   rF   r    r   rL  activationsr	   cache_utilsr
   r   
generationr   integrationsr   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   configuration_dbrxr   rY  r    ry   r   rm   rp   r   rJ   r   r   r   r   r  r  r)  r:  rD  r[  rq   r  r  __all__r5  r9   r7   <module>r     s.  * %     & ! . ) 4 / 9 Q K F & I I G 5 *><")) ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2R)BII R)jBII 2$")) $N "bii 6%.BII %.P* D7/ 74 U
# U
 U
t #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&ds
)? s
l Br9   