
    <hu                     T   S SK JrJrJr  S SKrS SKJs  Jr  S SKJr  S SK	J
r
  SSKJr  SSKJrJr  SSKJr  SS	KJr  SS
KJrJr  SSKJr  SSKJrJrJrJr  SSKJr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.  SSK/J0r0   " S S\Rb                  5      r2 " S S\Rb                  5      r3\" S5       " S S\Rb                  5      5       r4S r5SAS jr6S\Rn                  S\8S \Rn                  4S! jr9 SBS"\Rb                  S#\Rn                  S$\Rn                  S%\Rn                  S&\\Rn                     S'\:S(\:S)\(\*   4S* jjr; " S+ S,\Rb                  5      r< " S- S.\5      r= " S/ S0\Rb                  5      r>\+ " S1 S2\&5      5       r?\+ " S3 S4\?5      5       r@   SCS5\\Rn                  \A\Rn                     S4   S6\\8   S&\\Rn                     S \\Rn                  \84   4S7 jjrB\+ " S8 S9\?\5      5       rC " S: S;\\?5      rD " S< S=\\?5      rE " S> S?\\?5      rF/ S@QrGg)D    )CallableOptionalUnionN)nn)check_model_inputs   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)create_causal_mask!create_sliding_window_causal_mask)FlashAttentionKwargs)GenericForQuestionAnswering GenericForSequenceClassificationGenericForTokenClassificationGradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)OutputRecorder   )MixtralConfigc                   6   ^  \ rS rSrS\4U 4S jjrS rSrU =r$ )MixtralBlockSparseTop2MLP8   configc                   > [         TU ]  5         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)super__init__intermediate_sizeffn_dimhidden_size
hidden_dimr   Linearw1w2w3r	   
hidden_actact_fnselfr%   	__class__s     d/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/mixtral/modeling_mixtral.pyr+   "MixtralBlockSparseTop2MLP.__init__9   s    // ,,))DOOT\\F))DLL$//F))DOOT\\FV../    c                     U R                  U R                  U5      5      U R                  U5      -  nU R                  U5      nU$ N)r5   r1   r3   r2   )r7   hidden_statescurrent_hidden_statess      r9   forward!MixtralBlockSparseTop2MLP.forwardD   s>     $DGGM,B CdggmF\ \ $(= >$$r;   )r5   r-   r/   r1   r2   r3   )	__name__
__module____qualname____firstlineno__r!   r+   r@   __static_attributes____classcell__r8   s   @r9   r#   r#   8   s    	0} 	0% %r;   r#   c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )MixtralSparseMoeBlockJ   a  
This implementation is
strictly equivalent to standard MoE with full capacity (no
dropped tokens). It's faster since it formulates MoE operations
in terms of block-sparse operations to accommodate imbalanced
assignments of tokens to experts, whereas standard MoE either
(1) drop tokens at the cost of reduced performance or (2) set
capacity factor to number of experts and thus waste computation
and memory on padding.
c                   > [         TU ]  5         UR                  U l        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        UR"                  U l        g s  snf r'   )r*   r+   r.   r/   r,   r-   num_local_expertsnum_expertsnum_experts_per_toktop_kr   r0   gate
ModuleListranger#   expertsrouter_jitter_noisejitter_noise)r7   r%   _r8   s      r9   r+   MixtralSparseMoeBlock.__init__V   s     ,,//!33//
 IIdoot/?/?eL	}}QVW[WgWgQh%iQhA&?&GQh%ij #66 &js   *Cr>   returnc                    UR                   u  p#nU R                  (       aS  U R                  S:  aC  U[        R                  " U5      R                  SU R                  -
  SU R                  -   5      -  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  pgXfR                  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	[        R.                  " U	R                  SS9S5      R1                  5       n
U
 H  nU R2                  U   n[        R4                  " X   R7                  S5      5      u  pUSU4   R9                  SU5      nU" U5      XnUS4   -  nUR;                  SUUR                  UR                  5      5        M     UR9                  X#U5      nX4$ ) r   g      ?r    dimdtyper^   T)r^   keepdim)r_   device)num_classes   )r\   N)shapetrainingrV   torch
empty_likeuniform_viewrQ   FsoftmaxfloattopkrP   sumtor_   zerosrb   r   
functionalone_hotrN   permutegreaternonzerorT   wheresqueezereshape
index_add_)r7   r>   
batch_sizesequence_lengthr/   router_logitsrouting_weightsselected_expertsfinal_hidden_statesexpert_maskexpert_hitted
expert_idxexpert_layeridxtop_xcurrent_stater?   s                    r9   r@   MixtralSparseMoeBlock.forwarde   s   2?2E2E/
Z==T..2U--m<EEcDL]L]F]_beievev_vwwM%**2z:		-0))MqL,1JJ

XZ,[)..2t.DD),,]-@-@A#kk):6m>Q>QZgZnZn
 hh))112BP`P`1aiijkmnpqrkoo(o&CQGOOQ'J<<
3L[%<%D%DQ%GHJC *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5J5M5MmNaNa5bc ( 299*Wab"11r;   )rT   r-   rQ   r/   rV   rN   rP   )rB   rC   rD   rE   __doc__r+   rh   Tensorr@   rF   rG   rH   s   @r9   rJ   rJ   J   s-    	7%2U\\ %2ell %2 %2r;   rJ   RMSNormc                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )MixtralRMSNorm   c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z-
MixtralRMSNorm is equivalent to T5LayerNorm
N)r*   r+   r   	Parameterrh   onesweightvariance_epsilon)r7   r.   epsr8   s      r9   r+   MixtralRMSNorm.__init__   s/     	ll5::k#:; #r;   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      -  $ )Nrd   r\   T)ra   )	r_   rq   rh   float32powmeanrsqrtr   r   )r7   r>   input_dtypevariances       r9   r@   MixtralRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r;   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler   rf   r   r7   s    r9   
extra_reprMixtralRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr;   )r   r   )gư>)	rB   rC   rD   rE   r+   r@   r   rF   rG   rH   s   @r9   r   r      s    $;J Jr;   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..Nr\   rd   r`   )rf   rh   cat)xx1x2s      r9   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r;   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.
)	unsqueezer   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r9   apply_rotary_pos_embr      sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr;   r>   n_reprY   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)rf   expandrz   )r>   r   batchnum_key_value_headsslenhead_dims         r9   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr;   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"  US S 2S S 2S S 2S UR
                  S   24   n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$ )Nrd   r   re   r\   r]   )prg   r    )r   num_key_value_groupsrh   matmul	transposerf   r   rs   rm   r   rq   r_   r   rg   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r9   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#1==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r;   c                   F  ^  \ rS rSrSrS\S\4U 4S jjr  SS\R                  S\
\R                  \R                  4   S\\R                     S	\\   S
\\R                     S\\   S\
\R                  \\R                     \\
\R                        4   4S jjrSrU =r$ )MixtralAttention   z=Multi-headed attention from 'Attention Is All You Need' paperr%   	layer_idxc                   > [         TU ]  5         Xl        X l        [	        USS 5      =(       d    UR
                  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                  U R                  -  SS9U l        [        R                  " UR
                  UR                  U R                  -  SS9U l        [        R                  " UR
                  UR                  U R                  -  SS9U l        [        R                  " UR                  U R                  -  UR
                  SS9U l        g )Nr   g      TFr(   )r*   r+   r%   r   getattrr.   num_attention_headsr   r   r   r   attention_dropout	is_causalr   r0   q_projk_projv_projo_projr7   r%   r   r8   s      r9   r+   MixtralAttention.__init__   s.   "
D9mV=O=OSYSmSm=m$*$>$>&B\B\$\!}}d*!'!9!9ii 2 2F4N4NQUQ^Q^4^ejkii 2 2F4N4NQUQ^Q^4^ejkii 2 2F4N4NQUQ^Q^4^ejkii : :T]] JFL^L^ejkr;   r>   position_embeddingsr   past_key_valuecache_positionr   rY   c           
      `   UR                   S S n/ UQSPU R                  P7nU R                  U5      R                  U5      R	                  SS5      n	U R                  U5      R                  U5      R	                  SS5      n
U R                  U5      R                  U5      R	                  SS5      nUu  p[        XX5      u  pUb$  XUS.nUR                  XU R                  U5      u  p[        nU R                  R                  S:w  a  [        U R                  R                     nU" U U	U
UU4U R                  (       d  SOU R                  U R                   [#        U R                  SS 5      S.UD6u  nnUR$                  " / UQSP76 R'                  5       nU R)                  U5      nUU4$ )	Nr\   r    rd   )r   r   r   eager        sliding_window)r   r   r   )rf   r   r   rk   r   r   r   r   updater   r   r%   _attn_implementationr   rg   r   r   r   rz   r   r   )r7   r>   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r9   r@   MixtralAttention.forward   s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&#7RU#[ %#&nUL'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$7
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ "));;;;FFHkk+.L((r;   )r   r%   r   r   r   r   r   r   r   r   r   )NN)rB   rC   rD   rE   r   r!   intr+   rh   r   r   r   r
   
LongTensorr   r   r@   rF   rG   rH   s   @r9   r   r      s    Gl} l l& +/59*)||*) #5<<#=>*) !.	*)
 !*) !!1!12*) -.*) 
u||Xell3XeELL>Q5RR	S*) *)r;   r   c                   8  ^  \ rS rSrS\S\4U 4S jjr    SS\R                  S\	\R                  \R                  4   S\
\R                     S\
\R                     S	\
\	\R                        S
\
\R                     S\\   S\R                  4S jjrSrU =r$ )MixtralDecoderLayeri(  r%   r   c                   > [         TU ]  5         UR                  U l        [        X5      U l        [        U5      U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        g )Nr   )r*   r+   r.   r   	self_attnrJ   block_sparse_moer   rms_norm_epsinput_layernormpost_attention_layernormr   s      r9   r+   MixtralDecoderLayer.__init__)  sk    !--)&< 5f =-f.@.@fFYFYZ(6v7I7IvObOb(c%r;   r>   r   r   r   r   r   r   rY   c           
          UnU R                  U5      nU R                  " SUUUUUUS.UD6u  pX-   nUnU R                  U5      nU R                  U5      u  pX-   nU$ )N)r>   r   r   r   r   r    )r   r   r   r   )
r7   r>   r   r   r   r   r   r   residualrW   s
             r9   r@   MixtralDecoderLayer.forward3  s     !,,];  >> 
' 3)%))
 
 !0 !55mD00? 0r;   )r   r.   r   r   r   )NNNN)rB   rC   rD   rE   r!   r   r+   rh   r   r   r   r   r   r   FloatTensorr@   rF   rG   rH   s   @r9   r   r   (  s    d} d d 26378<59 ||  #5<<#=>  !.	 
 u//0  !u||!45  !!1!12  +,  
		   r;   r   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$ )MixtralRotaryEmbeddingiV  r%   c                   > [         TU ]  5         [        US5      (       aZ  [        UR                  [
        5      (       a;  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)r*   r+   hasattr
isinstancer  dictgetr  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr%   r   rope_init_fnattention_scalingregister_bufferr  original_inv_freq)r7   r%   rb   r  r8   s       r9   r+   MixtralRotaryEmbedding.__init__W  s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r;   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enabledrd   r`   )r_   )r  rn   r   rf   rq   rb   r
  r  strrh   autocastr   r   r   r  r   r_   )
r7   r   r   inv_freq_expandedposition_ids_expandedr  freqsembr   r   s
             r9   r@   MixtralRotaryEmbedding.forwardh  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  r%   r  r  r  r  r  r=   )rB   rC   rD   rE   r!   r+   rh   no_gradr   r@   rF   rG   rH   s   @r9   r  r  V  s6    /} / /" ]]_<  <r;   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S	9\\S
.rSrg)MixtralPreTrainedModelix  r%   modelTr   past_key_valuesFr    )index)r~   r>   
attentionsr   N)rB   rC   rD   rE   r!   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_can_compile_fullgraph_supports_attention_backendr   rJ   r   r   _can_record_outputsrF   r   r;   r9   r#  r#  x  s\    &*#./#4"5N""&'(=QG,&r;   r#  c                     ^  \ rS rSrS\4U 4S jjr\\       SS\\	R                     S\\	R                     S\\	R                     S\\   S\\	R                     S	\\   S
\\	R                     S\\   S\4S jj5       5       rSrU =r$ )MixtralModeli  r%   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   )r%   F)r*   r+   pad_token_idpadding_idx
vocab_sizer   	Embeddingr.   embed_tokensrR   rS   num_hidden_layersr   layersr   r   normr  
rotary_embgradient_checkpointing	post_initr   s      r9   r+   MixtralModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEdeEd	 3Ede
 #6#5#56;N;NO	0?&+# 	 fs   C>	input_idsr   r   r%  inputs_embeds	use_cacher   r   rY   c                 z   US L US L-  (       a  [        S5      eU(       a  Uc
  [        5       nUc  U R                  U5      n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                  R                  c  [        O[        n
U
" U R                  U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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    )rb   )r%   input_embedsr   r   r%  r   )r   r   r   r   rD  r   )last_hidden_stater%  )
ValueErrorr   r:  get_seq_lengthrh   arangerf   rb   r   r%   r   r   r   r>  r<  r;  r=  r   )r7   rB  r   r   r%  rC  rD  r   r   past_seen_tokensmask_functionr   r>   r   decoder_layers                  r9   r@   MixtralModel.forward  sh    -t";<YZZ0*nO  --i8M!CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L.2kk.H.H.P*Vw#;;&))+%
 & #oomJ![[)H4;;+H+HIM)	$7*).#-	 	M J 		-0%++
 	
r;   )r:  r?  r<  r=  r7  r>  r8  )NNNNNNN)rB   rC   rD   rE   r!   r+   r   r   r   rh   r   r   r
   r   boolr   r   r   r@   rF   rG   rH   s   @r9   r4  r4    s    }    151537+/59$(59<
E,,-<
 !.<
 u//0	<

 "%<
   1 12<
 D><
 !!1!12<
 +,<
 
 <
  <
r;   r4  gate_logitsrN   c                    U b  [        U [        5      (       d  g[        U [        5      (       aB  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   r`   r\   )r
  r   rb   rh   r   rq   r   rs   rm   ro   rt   r   rn   rf   r   rz   rp   r   )rP  rN   rP   r   compute_device
layer_gateconcatenated_gate_logitsr   rW   r   r   tokens_per_expertrouter_prob_per_expertr|   r}   r;  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r9   load_balancing_loss_funcrZ    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/rSS0rSS/S/40rU 4S jrS rS	 r	\
\          SS
\\R                     S\\R                     S\\R                     S\\   S\\R"                     S\\R                     S\\   S\\   S\\R                     S\\\R                  4   S\\   S\4S jj5       5       rSrU =r$ )MixtralForCausalLMi0  zlm_head.weightlm_headcolwise_repr>   logitsc                 J  > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  U l	        UR                  U l        UR                  U l        U R                  5         g r'   )r*   r+   r4  r$  r8  r   r0   r.   r]  router_aux_loss_coefrM   rN   rO   r@  r6   s     r9   r+   MixtralForCausalLM.__init__6  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r;   c                     Xl         g r=   r$  )r7   decoders     r9   set_decoderMixtralForCausalLM.set_decoderB  s    
r;   c                     U R                   $ r=   rd  r   s    r9   get_decoderMixtralForCausalLM.get_decoderE  s    zzr;   rB  r   r   r%  rC  labelsrD  output_router_logitsr   logits_to_keepr   rY   c                 ~   Ub  UOU R                   R                  nU R                  " SU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(       aZ  [        UR                  U R                  U R                  U5      nUb+  UU R                  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, MixtralForCausalLM

>>> model = MixtralForCausalLM.from_pretrained("mistralai/Mixtral-8x7B-v0.1")
>>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mixtral-8x7B-v0.1")

>>> 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)rB  r   r   r%  rC  rD  rl  r   )lossaux_lossr_  r%  r>   r'  r~   r   )r%   rl  r$  rG  r
  r   slicer]  loss_functionr8  rZ  r~   rN   rO   ra  rq   rb   r   r%  r>   r'  )r7   rB  r   r   r%  rC  rk  rD  rl  r   rm  r   outputsr>   slice_indicesr_  ro  rp  s                     r9   r@   MixtralForCausalLM.forwardH  sU   P %9$D $++JjJj 	
 +/** 
+
)%+'!5)
+
 
+
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r;   )r]  r$  rN   rO   ra  r8  )
NNNNNNNNNr   )rB   rC   rD   rE   _tied_weights_keys_tp_plan_pp_planr+   rf  ri  r   r   r   rh   r   r   r
   r   rO  r   r   r   r   r   r@   rF   rG   rH   s   @r9   r\  r\  0  sY   *+=)H_-z:;H
  151537+/59-1$(/35934R
E,,-R
 !.R
 u//0	R

 "%R
   1 12R
 ))*R
 D>R
 'tnR
 !!1!12R
 c5<</0R
 +,R
 
#R
  R
r;   r\  c                       \ rS rSrSrg) MixtralForSequenceClassificationi  r   NrB   rC   rD   rE   rF   r   r;   r9   rz  rz        r;   rz  c                       \ rS rSrSrg)MixtralForTokenClassificationi  r   Nr{  r   r;   r9   r~  r~    r|  r;   r~  c                       \ rS rSrSrg)MixtralForQuestionAnsweringi  r   Nr{  r   r;   r9   r  r    r|  r;   r  )r\  r  r4  r#  rz  r~  )Nr    )r   )Nrd   N)Htypingr   r   r   rh   torch.nn.functionalr   rs   rl   transformers.utils.genericr   activationsr	   cache_utilsr
   r   
generationr   integrationsr   masking_utilsr   r   modeling_flash_attention_utilsr   modeling_layersr   r   r   r   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr   configuration_mixtralr!   Moduler#   rJ   r   r   r   r   r   r   rn   r   r   r   r  r#  r4  r   rZ  r\  rz  r~  r  __all__r   r;   r9   <module>r     st  6 - ,     9 ! . ) 7 R B  R K F & I I + 0%		 %$@2BII @2F Y'JRYY J (J((6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%4;)ryy ;)|+4 +\<RYY <D _  $ O
) O
 O
h "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&d k
/ k
 k
\	'GI_ 		$ACY 		"=?U 	r;   