
    cCiJv                     `   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K1J2r2   " S S\Rf                  5      r4 " S S\Rf                  5      r5\" S5       " S S\Rf                  5      5       r6S r7SBS jr8S\Rr                  S \:S!\Rr                  4S" jr; SCS#\Rf                  S$\Rr                  S%\Rr                  S&\Rr                  S'\\Rr                     S(\<S)\<S*\(\*   4S+ jjr= " S, S-\Rf                  5      r> " S. S/\5      r? " S0 S1\Rf                  5      r@\+ " S2 S3\&5      5       rA\+ " S4 S5\A5      5       rB   SDS6\\Rr                  \C\Rr                     S4   S7\\:   S'\\Rr                     S!\\Rr                  \:4   4S8 jjrD\+ " S9 S:\A\5      5       rE " S; S<\\A5      rF " S= S>\\A5      rG " S? S@\\A5      rH/ SAQrIg)E    )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)deprecate_kwarg)OutputRecorder   )MixtralConfigc                   6   ^  \ rS rSrS\4U 4S jjrS rSrU =r$ )MixtralBlockSparseTop2MLP9   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     f/home/james-whalen/.local/lib/python3.13/site-packages/transformers/models/mixtral/modeling_mixtral.pyr,   "MixtralBlockSparseTop2MLP.__init__:   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)r6   r2   r4   r3   )r8   hidden_statescurrent_hidden_statess      r:   forward!MixtralBlockSparseTop2MLP.forwardE   s>     $DGGM,B CdggmF\ \ $(= >$$r<   )r6   r.   r0   r2   r3   r4   )	__name__
__module____qualname____firstlineno__r"   r,   rA   __static_attributes____classcell__r9   s   @r:   r$   r$   9   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
$ )MixtralSparseMoeBlockK   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/   r0   r-   r.   num_local_expertsnum_expertsnum_experts_per_toktop_kr   r1   gate
ModuleListranger$   expertsrouter_jitter_noisejitter_noise)r8   r&   _r9   s      r:   r,   MixtralSparseMoeBlock.__init__W   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trainingrW   torch
empty_likeuniform_viewrR   FsoftmaxfloattopkrQ   sumtor`   zerosrc   r   
functionalone_hotrO   permutegreaternonzerorU   wheresqueezereshape
index_add_)r8   r?   
batch_sizesequence_lengthr0   router_logitsrouting_weightsselected_expertsfinal_hidden_statesexpert_mask
expert_hit
expert_idxexpert_layeridxtop_xcurrent_stater@   s                    r:   rA   MixtralSparseMoeBlock.forwardf   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]];??x?#@!DLLN
$J<<
3L[%<%D%DQ%GHJC *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5J5M5MmNaNa5bc % 299*Wab"11r<   )rU   r.   rR   r0   rW   rO   rQ   )rC   rD   rE   rF   __doc__r,   ri   TensorrA   rG   rH   rI   s   @r:   rK   rK   K   s-    	7%2U\\ %2ell %2 %2r<   rK   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   	Parameterri   onesweightvariance_epsilon)r8   r/   epsr9   s      r:   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      -  $ )Nre   r]   T)rb   )	r`   rr   ri   float32powmeanrsqrtr   r   )r8   r?   input_dtypevariances       r:   rA   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   rg   r   )r8   s    r:   
extra_reprMixtralRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr<   )r   r   )gư>)	rC   rD   rE   rF   r,   rA   r   rG   rH   rI   s   @r:   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]   re   ra   )rg   ri   cat)xx1x2s      r:   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           r:   apply_rotary_pos_embr      sS    ( --
&C
--
&Cw;q>C/0Gw;q>C/0Gr<   r?   n_reprZ   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)rg   expandr{   )r?   r   batchnum_key_value_headsslenhead_dims         r:   	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$ )Nre   r   rf   r]   r^   )prh   r!   )r   num_key_value_groupsri   matmul	transposerg   r   rt   rn   r   rr   r`   r   rh   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r:   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                   :  ^  \ rS rSrSrS\S\4U 4S jjr\" SSSS	9  SS
\	R                  S\\	R                  \	R                  4   S\\	R                     S\\   S\\	R                     S\\   S\\	R                  \\	R                     4   4S jj5       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   r1   q_projk_projv_projo_projr8   r&   r   r9   s      r:   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<   past_key_valuepast_key_values4.58new_nameversionr?   position_embeddingsr   cache_positionr   rZ   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!   re   )r   r   r   eager        sliding_window)r   r   r   )rg   r   r   rl   r   r   r   r   updater   r   r&   _attn_implementationr   rh   r   r   r   r{   r   r   )r8   r?   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r:   rA   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'6'='=jX\XfXfht'u$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)rC   rD   rE   rF   r   r"   intr,   r   ri   r   r   r   r
   
LongTensorr   r   rA   rG   rH   rI   s   @r:   r   r      s    Gl} l l %0A6R ,059*)||*) #5<<#=>*) !.	*)
 "%*) !!1!12*) -.*) 
u||Xell33	4*) S*)r<   r   c                   4  ^  \ rS rSrS\S\4U 4S jjr\" SSSS9    SS	\R                  S
\
\R                  \R                  4   S\\R                     S\\R                     S\\   S\\R                     S\\   S\R                   4S jj5       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_attnrK   block_sparse_moer   rms_norm_epsinput_layernormpost_attention_layernormr   s      r:   r,   MixtralDecoderLayer.__init__+  sk    !--)&< 5f =-f.@.@fFYFYZ(6v7I7IvObOb(c%r<   r   r   r   r   r?   r   r   r   r   r   rZ   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   )
r8   r?   r   r   r   r   r   r   residualrX   s
             r:   rA   MixtralDecoderLayer.forward5  s     !,,];  >> 
' 3)%+)
 
 !0 !55mD00? 0r<   )r   r/   r   r   r   )NNNN)rC   rD   rE   rF   r"   r   r,   r   ri   r   r   r   r   r
   r   r   FloatTensorrA   rG   rH   rI   s   @r:   r   r   *  s    d} d d %0A6R
 2637+/59 ||  #5<<#=>  !.	 
 u//0  "%  !!1!12  +,  
		  S r<   r   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\R                  " 5       \
S 5       5       rSrU =r$ )MixtralRotaryEmbeddingiY  inv_freqr&   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defaultr  F)
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)r8   r&   rc   r  r9   s       r:   r,   MixtralRotaryEmbedding.__init__\  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enabledre   ra   )r`   )r  ro   r   rg   rr   rc   r  r  strri   autocastr   r   r   r  r   r`   )
r8   r   r   inv_freq_expandedposition_ids_expandedr  freqsembr   r   s
             r:   rA   MixtralRotaryEmbedding.forwardm  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>   )rC   rD   rE   rF   ri   r   __annotations__r"   r,   no_gradr   rA   rG   rH   rI   s   @r:   r  r  Y  s@    ll/} / /" ]]_<  <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)MixtralPreTrainedModeli}  r&   modelTr   r   Fr!   )index)r   r?   
attentionsr  N)rC   rD   rE   rF   r"   r&  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    rK   r   r   _can_record_outputsrG   r  r<   r:   r)  r)  }  s\    &*#./#4"5N""&'(=QG,&r<   r)  c                   "  ^  \ rS rSrS\4U 4S jjr\" 5       \       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_tokensrS   rT   num_hidden_layersr   layersr   r   normr  
rotary_embgradient_checkpointing	post_initr   s      r:   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   rZ   c                    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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   r!   )rc   )r&   input_embedsr   r   r   r   )r   r   r   r   rI  r   )last_hidden_stater   )
ValueErrorr   r&   r?  get_seq_lengthri   arangerg   rc   r   r   r   r   rC  rA  r@  rB  r   )r8   rG  r   r   r   rH  rI  r   r   past_seen_tokensmask_functionr   r?   r   decoder_layers                  r:   rA   MixtralModel.forward  so    -t";<YZZ0*$++>O  --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?  rD  rA  rB  r<  rC  r=  )NNNNNNN)rC   rD   rE   rF   r"   r,   r   r   r   ri   r   r   r
   r  boolr   r   r   rA   rG   rH   rI   s   @r:   r8  r8    s    }    151537+/59$(59<
E,,-<
 !.<
 u//0	<

 "%<
   1 12<
 D><
 !!1!12<
 +,<
 
 <
  <
r<   r8  gate_logitsrO   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   ra   r]   )r  r   rc   ri   r   rr   r   rt   rn   rp   ru   r   ro   rg   r   r{   rq   r   )rU  rO   rQ   r   compute_device
layer_gateconcatenated_gate_logitsr   rX   r   r   tokens_per_expertrouter_prob_per_expertr}   r~   r@  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r:   load_balancing_loss_funcr_    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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$ )MixtralForCausalLMi5  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,   r8  r*  r=  r   r1   r/   rb  router_aux_loss_coefrN   rO   rP   rE  r7   s     r:   r,   MixtralForCausalLM.__init__;  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r<   rG  r   r   r   rH  labelsrI  output_router_logitsr   logits_to_keepr   rZ   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)rG  r   r   r   rH  rI  ri  r   )lossaux_lossrd  r   r?   r,  r   r  )r&   ri  r*  rL  r  r   slicerb  loss_functionr=  r_  r   rO   rP   rf  rr   rc   r   r   r?   r,  )r8   rG  r   r   r   rH  rh  rI  ri  r   rj  r   outputsr?   slice_indicesrd  rl  rm  s                     r:   rA   MixtralForCausalLM.forwardG  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<   )rb  r*  rO   rP   rf  r=  )
NNNNNNNNNr   )rC   rD   rE   rF   _tied_weights_keys_tp_plan_pp_planr,   r   r   r   ri   r   r   r
   r  rT  r   r   r   r   r   rA   rG   rH   rI   s   @r:   ra  ra  5  sO   *+=)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<   ra  c                       \ rS rSrSrg) MixtralForSequenceClassificationi  r  NrC   rD   rE   rF   rG   r  r<   r:   rw  rw        r<   rw  c                       \ rS rSrSrg)MixtralForTokenClassificationi  r  Nrx  r  r<   r:   r{  r{    ry  r<   r{  c                       \ rS rSrSrg)MixtralForQuestionAnsweringi  r  Nrx  r  r<   r:   r}  r}    ry  r<   r}  )ra  r}  r8  r)  rw  r{  )Nr!   )r   )Nre   N)Jtypingr   r   r   ri   torch.nn.functionalr   rt   rm   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.deprecationr   utils.genericr    configuration_mixtralr"   Moduler$   rK   r   r   r   r   r   r   ro   r   r   r   r  r)  r8  r   r_  ra  rw  r{  r}  __all__r  r<   r:   <module>r     sw  6 - ,     9 ! . ) 7 R B  R K F & I I 0 + 0%		 %$@2BII @2F Y'JRYY J (J((6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%4<)ryy <)~,4 ,^!<RYY !<H _  $ O
) O
 O
h "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&d e
/ e
 e
P	'GI_ 		$ACY 		"=?U 	r<   