
    fThs                        S SK Jr  S SKJrJr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Jr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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*  SSK+J,r,J-r-J.r.J/r/J0r0  SSK1J2r2  \/" 5       (       a  S SK3J4r4  SSK5J6r6  \0Rn                  " \85      r9 " S S\
Rt                  5      r; " S S\
Rt                  5      r<\" S5       " S S\
Rt                  5      5       r=S r>SDS jr?S\R                  S\AS \R                  4S! jrB SES"\
Rt                  S#\R                  S$\R                  S%\R                  S&\\R                     S'\CS(\C4S) jjrD " S* S+\
Rt                  5      rE " S, S-\
Rt                  5      rF " S. S/\
Rt                  5      rG\- " S0 S1\(5      5       rH\- " S2 S3\H5      5       rI " S4 S5\\,5      rJ   SFS6\\R                  \\R                     S4   S7\\A   S&\\R                     S \\R                  \A4   4S8 jjrK\- " S9 S:\H\5      5       rL\-" S;S<9 " S= S>\H5      5       rM\- " S? S@\H5      5       rN\- " SA SB\H5      5       rO/ SCQrPg)G    )partial)CallableListOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastMoeCausalLMOutputWithPastMoeModelOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )MixtralConfig)	BlockMask)make_flex_block_causal_maskc                   6   ^  \ rS rSrS\4U 4S jjrS rSrU =r$ )MixtralBlockSparseTop2MLP@   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/auris/envauris/lib/python3.13/site-packages/transformers/models/mixtral/modeling_mixtral.pyr1   "MixtralBlockSparseTop2MLP.__init__A   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)r;   r7   r9   r8   )r=   hidden_statescurrent_hidden_statess      r?   forward!MixtralBlockSparseTop2MLP.forwardL   s>     $DGGM,B CdggmF\ \ $(= >$$rA   )r;   r3   r5   r7   r8   r9   )	__name__
__module____qualname____firstlineno__r%   r1   rF   __static_attributes____classcell__r>   s   @r?   r)   r)   @   s    	0} 	0% %rA   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
$ )MixtralSparseMoeBlockR   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-   )r0   r1   r4   r5   r2   r3   num_local_expertsnum_expertsnum_experts_per_toktop_kr	   r6   gate
ModuleListranger)   expertsrouter_jitter_noisejitter_noise)r=   r+   _r>   s      r?   r1   MixtralSparseMoeBlock.__init__^   s     ,,//!33//
 IIdoot/?/?eL	}}QVW[WgWgQh%iQhA&?&GQh%ij #66 &js   *CrD   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	U	R                  SS9S:  R/                  SS9S   R1                  5       n
U
 H  nU R2                  U   n[        R4                  " X   5      u  pUSU4   R7                  SU5      nU" U5      XnUS4   -  nUR9                  SUUR                  UR                  5      5        M     UR7                  X#U5      nX4$ ) r         ?r$   dimdtypere   T)re   keepdim)rf   device)num_classes   )rc   )as_tupleN)shapetrainingr\   torch
empty_likeuniform_viewrW   FsoftmaxfloattopkrV   sumtorf   zerosri   r	   
functionalone_hotrT   permutenonzerotolistrZ   wherereshape
index_add_)r=   rD   
batch_sizesequence_lengthr5   router_logitsrouting_weightsselected_expertsfinal_hidden_statesexpert_maskexpert_hitted
expert_idxexpert_layeridxtop_xcurrent_staterE   s                    r?   rF   MixtralSparseMoeBlock.forwardm   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6:CCTCRSTU\\^'J<<
3L[%<=JC *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5J5M5MmNaNa5bc ( 299*Wab"11rA   )rZ   r3   rW   r5   r\   rT   rV   )rH   rI   rJ   rK   __doc__r1   rp   TensorrF   rL   rM   rN   s   @r?   rP   rP   R   s-    	7%2U\\ %2ell %2 %2rA   rP   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)r0   r1   r	   	Parameterrp   onesweightvariance_epsilon)r=   r4   epsr>   s      r?   r1   MixtralRMSNorm.__init__   s/     	ll5::k#:; #rA   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      -  $ )Nrk   rc   T)rh   )	rf   ry   rp   float32powmeanrsqrtr   r   )r=   rD   input_dtypevariances       r?   rF   MixtralRMSNorm.forward   sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::rA   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler   rn   r   r=   s    r?   
extra_reprMixtralRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIrA   )r   r   )gư>)	rH   rI   rJ   rK   r1   rF   r   rL   rM   rN   s   @r?   r   r      s    $;J JrA   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..Nrc   rk   rg   )rn   rp   cat)xx1x2s      r?   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''rA   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rA   rD   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)rn   expandr   )rD   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TrA   modulequerykeyvalueattention_maskscalingdropoutc                 @   [        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$ )Nrk   r
   rl   rc   rd   )pro   r$   )r   num_key_value_groupsrp   matmul	transposern   r	   r{   ru   r   ry   rf   r   ro   
contiguous)r   r   r   r   r   r   r   kwargs
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$$rA   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.   )r0   r1   r+   r   getattrr4   num_attention_headsr   r   r   r   attention_dropout	is_causalr	   r6   q_projk_projv_projo_projr=   r+   r   r>   s      r?   r1   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rA   rD   position_embeddingsr   past_key_valuecache_positionr   r_   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  ad  U R                  R                  S:X  a-  UR                  SS5      (       a  [        R                  S	5        O[         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$ )Nrc   r$   rk   )r   r   r   eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        sliding_window)r   r   r   )rn   r   r   rs   r   r   r   r   updater   r   r+   _attn_implementationgetloggerwarning_oncer   ro   r   r   r   r   r   r   )r=   rD   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r?   rF   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{{//69fjjI\^c>d>d##L
 '>dkk>^>^&_#$7
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ "));;;;FFHkk+.L((rA   )r   r+   r   r   r   r   r   r   r   r   r   )NN)rH   rI   rJ   rK   r   r%   intr1   rp   r   r   r   r   
LongTensorr   r   rF   rL   rM   rN   s   @r?   r   r      s    Gl} l l& +/590)||0) #5<<#=>0) !.	0)
 !0) !!1!120) -.0) 
u||Xell3XeELL>Q5RR	S0) 0)rA   r   c                     ^  \ rS rSrS\S\4U 4S jjr        SS\R                  S\	\R                     S\	\R                     S\	\\R                        S	\	\   S
\	\   S\	\   S\	\R                     S\	\\R                  \R                  4      S\\   S\\R                  \	\\R                  \R                  4      4   4S jjrSrU =r$ )MixtralDecoderLayeri6  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   )r0   r1   r4   r   	self_attnrP   block_sparse_moer   rms_norm_epsinput_layernormpost_attention_layernormr   s      r?   r1   MixtralDecoderLayer.__init__7  sk    !--)&< 5f =-f.@.@fFYFYZ(6v7I7IvObOb(c%rA   rD   r   r   r   r   output_router_logits	use_cacher   r   r   r_   c
                     UnU R                  U5      nU R                  " SUU	UUUUUUS.U
D6u  pX-   nUnU R                  U5      nU R                  U5      u  pX-   nU4nU(       a  X4-  nU(       a  X4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
        `(batch, sequence_length)` where padding elements are indicated by 0.
    past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    output_router_logits (`bool`, *optional*):
        Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
        should not be returned during inference.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
)rD   r   r   r   r   r   r  r    )r  r  r  r  )r=   rD   r   r   r   r   r  r  r   r   r   residualself_attn_weightsr   outputss                  r?   rF   MixtralDecoderLayer.forwardA  s    F !,,]; ,0>> 
,
' 3)%)/)
,
 
,
( !0 !55mD'+'<'<]'K$ 0 "++G''GrA   )r  r4   r  r  r  )NNNFFFNN)rH   rI   rJ   rK   r%   r   r1   rp   r   r   r   r   boolr   r   FloatTensorrF   rL   rM   rN   s   @r?   r   r   6  s;   d} d d 26378<,1/4$)59KOC||C !.C u//0	C
 !u||!45C $D>C 'tnC D>C !!1!12C &eELL%,,,F&GHC -.C 
u  (51B1BEDUDU1U+V"WW	XC CrA   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$ )MixtralRotaryEmbeddingi  r+   c                   > [         TU ]  5         [        US5      (       aH  UR                  b;  UR                  R	                  SUR                  R	                  S5      5      U l        OSU l        UR                  U l        UR                  U l        Xl	        [        U R
                     U l        U R                  U R                  U5      u  o0l        U R                  SUSS9  U R                  U l        g )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)r0   r1   hasattrr  r   r  max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr+   r   rope_init_fnattention_scalingregister_bufferr  original_inv_freq)r=   r+   ri   r  r>   s       r?   r1   MixtralRotaryEmbedding.__init__  s    6>**v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%rA   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   rc   r$   mpscpuF)device_typeenabledrk   rg   )rf   )r  rv   r   rn   ry   ri   
isinstancer  strrp   autocastr   r   r   r  r   rf   )
r=   r   r   inv_freq_expandedposition_ids_expandedr&  freqsembr   r   s
             r?   rF   MixtralRotaryEmbedding.forward  sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfk^^UC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   $BF  
F.)r  r+   r  r!  r  r  r  rC   )rH   rI   rJ   rK   r%   r1   rp   no_gradr   rF   rL   rM   rN   s   @r?   r  r    s6    /} / /" ]]_<  <rA   r  c                   N    \ rS rSr\rSrSrS/rS/r	Sr
SrSrSrSrSrSrS rSrg	)
MixtralPreTrainedModeli  modelTr   past_key_valuesFc                    U R                   R                  n[        U[        R                  5      (       aW  UR
                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        R                  5      (       ad  UR
                  R                  R                  SUS9  UR                  b2  UR
                  R                  UR                     R                  5         g g [        U[        5      (       a&  UR
                  R                  R                  S5        g g )Nr   )r   stdrb   )r+   initializer_ranger(  r	   r6   r   datanormal_r/   zero_	Embeddingpadding_idxr   fill_)r=   r   r6  s      r?   _init_weights$MixtralPreTrainedModel._init_weights  s    kk++fbii((MM&&CS&9{{&  &&( '--MM&&CS&9!!-""6#5#56<<> .//MM$$S) 0rA   r
  N)rH   rI   rJ   rK   r%   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr>  rL   r
  rA   r?   r2  r2    sS     L&*#./#4"5!N  $""&*rA   r2  c                   <  ^  \ rS rSrS\4U 4S jjrS rS r\\	          SS\
\R                     S\
\R                     S\
\R                     S	\
\\R                        S
\
\R                     S\
\   S\
\   S\
\   S\
\   S\
\R                     S\\   S\4S jj5       5       r SS\\R                  S4   S\R                  S\R                  S	\S\4
S jjr\S\R                  S\S\S\R4                  S\R                  S\S\S	\4S j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)r0   r1   pad_token_idr<  
vocab_sizer	   r;  r4   embed_tokensrX   rY   num_hidden_layersr   layersr   r  normr  
rotary_embgradient_checkpointing	post_initr   s      r?   r1   MixtralModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEdeEd	 3Ede
 #6#5#56;N;NO	0?&+# 	 fs   C?c                     U R                   $ rC   rQ  r   s    r?   get_input_embeddings!MixtralModel.get_input_embeddings  s       rA   c                     Xl         g rC   rZ  r=   r   s     r?   set_input_embeddings!MixtralModel.set_input_embeddings  s    !rA   	input_idsr   r   r4  inputs_embedsr  r   output_hidden_statesr  r   flash_attn_kwargsr_   c                    Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nUb  UOU R                   R                  nUS L US L-  (       a  [        S5      eU R                  (       a/  U R                  (       a  U(       a  [        R                  S5        SnU(       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%                  X%XU5      nUnU R'                  X5      nU(       a  SOS nU(       a  SOS nU	(       a  SOS nU R(                   H  nU(       a  UU4-  nU R                  (       a@  U R                  (       a/  U R+                  [-        UR.                  40 UD6UUUUUU	UU
U5
      nOU" U4UUUUU	UU
US.UD6nUS   nU(       a	  UUS   4-  nU	(       d  M  UUS	   4-  nM     U R1                  U5      nU(       a  UU4-  n[3        UUUUUS
9$ )Nz:You must specify exactly one of input_ids or inputs_embedszZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr   r$   ri   r
  )r   r   r   r   r  r  r   r   rc   )last_hidden_stater4  rD   
attentionsr   )r+   r   r  rc  r  
ValueErrorrV  ro   r   r   r   rQ  get_seq_lengthrp   arangern   ri   r   _update_causal_maskrU  rS  _gradient_checkpointing_funcr   __call__rT  r   )r=   ra  r   r   r4  rb  r  r   rc  r  r   rd  past_seen_tokensr   rD   r   all_hidden_statesall_self_attnsall_router_logitsdecoder_layerlayer_outputss                        r?   rF   MixtralModel.forward  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==##p "	0*nO  --i8M!CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L..>L]
 & #oomJ #7BD0d"6BD![[M#!m%55!**t}} $ A AM22H6GH! #%("'! !.!!#.!-#2&7)='#1(;! (! *!,M =#3"55##!mB&7%99!K )N 		-0  -!11%+++%+
 	
rA   r&   input_tensorc                    U R                   R                  S:X  a]  UbN  UbK  US S 2S4   R                  5       R                  5       UR	                  5       S   :g  nU(       a  [        S5      eUb  SU;   a  U$ g U R                   R                  S:X  a,  [        U[        R                  5      (       a  [        U5      nU$ Ub  UR                  5       OSn[        U[        5      n[        U[        5      n	U R                   R                  S:X  aQ  U(       dJ  U	(       dC  U(       d<  [        R                  " UUUU R                   R                  U R                   S9(       a  g UR"                  n
[        R$                  " U
5      R&                  nUR(                  S	   nU	(       d  U(       a  UR+                  5       nO5[        U[        R                  5      (       a  UR(                  S   OX|-   S	-   nU R-                  UUUU
UUR(                  S   U R                   US
9nU R                   R                  S:X  a:  Ub7  UR.                  R0                  S;   a  U(       d  [        R2                  " X5      nU$ )Nflash_attention_2rc   r   zYou are attempting to perform batched generation with padding_side='right' this may lead to unexpected behaviour for Flash Attention version of Mixtral. Make sure to  call `tokenizer.padding_side  = 'left'` before tokenizing the input. r   flex_attentionr   )rb  past_key_values_lengthr   is_trainingr$   )r   target_lengthrf   r   r   r+   r4  )cudaxpunpu)r+   r   rx   itemsizeri  r(  rp   r   r'   rj  r   r   r   _ignore_causal_mask_sdpar   ro   rf   finfominrn   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionri   r  _unmask_unattended)r=   r   rv  r   r4  r   is_padding_rightro  using_static_cacheusing_sliding_window_cacherf   	min_dtyper   r|  r   s                  r?   rl   MixtralModel._update_causal_maskR  s;    ;;++/BB)o.I#1!R%#8#<#<#>#C#C#EIZIZI\]^I_#_ #$a 
 )c^.C%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`a'E%/AS%T" KK,,6'+E%%>>*'7#{{99 MM ""KK&**	&,,Q/%);+??AM
 nell;; $$R(%7!;  PP+')#))!,;;+ Q 	
 KK,,6*%%**.DD%
 1CCK[KrA   r   r|  rf   r   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n	[        R                  " X4XUR
                  S9n[        R                  " X$R
                  S9UR                  SS5      :  n
UR                  5       n[        USS5      (       av  UR                  bi  [        U[        5      (       a  X:  aO  [        R                  " X$R
                  S9UR                  SS5      UR                  -
  :*  nU
R                  U5        X-  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                   S   U:  a  U SS2SU24   n U R                   S   nUSS2SS2SS2SU24   U SS2SSSS24   R#                  UR
                  5      -   nUS	:H  nUSS2SS2SS2SU24   R%                  X5      USS2SS2SS2SU24'   U$ )
aS  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
    config (`MixtralConfig`):
        The model's configuration class
    past_key_values (`Cache`):
        The cache class that is being used currently to generate
N   )
fill_valuerf   ri   rf  rc   r$   use_sliding_windowTr   )re   rp   r  r  fullri   rk  r   get_text_configr   r   r(  r   bitwise_or_r   clonern   ry   masked_fill)r   r   r|  rf   r   r   r+   r4  r   r  diagonal_attend_masktext_configsliding_attend_maskmask_lengthpadding_masks                  r?   r  BMixtralModel._prepare_4d_causal_attention_mask_with_cache_position  s   B %.*<*<*>!*C(K@ = E*..I** 0Y\j\q\qK $)<<F[F[#\_m_u_uA` $  !002K{$8$??KD^D^Dj "/3EFF/Ji*/,,}MbMb*c&..r158R8RR+' )445HI/K%dD!Q&67>>z1bRTUK))//1!''+m;%3A~~4E%FN,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c 6Aq!\k\12 rA   )rQ  rV  rS  rT  r<  rU  rP  )
NNNNNNNNNN)F)rH   rI   rJ   rK   r%   r1   r[  r_  r!   r    r   rp   r   r   r   r  r  r   r   r   rF   r   r   rl  staticmethodr   rf   r  rL   rM   rN   s   @r?   rM  rM    s   }  !"  151537=A59$(,0/3/359p
E,,-p
 !.p
 u//0	p

 "$u'8'8"9:p
   1 12p
 D>p
 $D>p
 'tnp
 'tnp
 !!1!12p
 $$89p
 
 p
  p
p #(TellK78T llT 	T
 T  Tl BBB B {{	B
 B B B B BrA   rM  c                       \ rS rSrSrg)KwargsForCausalLMi  r
  N)rH   rI   rJ   rK   rL   r
  rA   r?   r  r    s    3rA   r  gate_logitsrT   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 )ap  
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

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

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

Returns:
    The auxiliary loss.
Nr   rg   rc   )r(  r   ri   rp   r   ry   r	   r{   ru   rw   r|   r   rv   rn   r   r   rx   r   )r  rT   rV   r   compute_device
layer_gateconcatenated_gate_logitsr   r]   r   r   tokens_per_expertrouter_prob_per_expertr   r   rR  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 rS	 r	S
 r
S rS rS r\\            SS\\R$                     S\\R&                     S\\R$                     S\\\R*                        S\\R*                     S\\R$                     S\\   S\\   S\\   S\\   S\\R$                     S\\\R&                  4   S\\   S\4S jj5       5       rSrU =r$ )MixtralForCausalLMiC  zlm_head.weightlm_headcolwise_reprD   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-   )r0   r1   rM  r3  rP  r	   r6   r4   r  router_aux_loss_coefrS   rT   rU   rW  r<   s     r?   r1   MixtralForCausalLM.__init__I  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	rA   c                 .    U R                   R                  $ rC   r3  rQ  r   s    r?   r[  'MixtralForCausalLM.get_input_embeddingsU      zz&&&rA   c                 $    XR                   l        g rC   r  r^  s     r?   r_  'MixtralForCausalLM.set_input_embeddingsX      "'

rA   c                     U R                   $ rC   r  r   s    r?   get_output_embeddings(MixtralForCausalLM.get_output_embeddings[  s    ||rA   c                     Xl         g rC   r  )r=   new_embeddingss     r?   set_output_embeddings(MixtralForCausalLM.set_output_embeddings^  s    %rA   c                     Xl         g rC   r3  )r=   decoders     r?   set_decoderMixtralForCausalLM.set_decodera  s    
rA   c                     U R                   $ rC   r  r   s    r?   get_decoderMixtralForCausalLM.get_decoderd  s    zzrA   ra  r   r   r4  rb  labelsr  r   rc  r  r   logits_to_keepr   r_   c                    Ub  UOU R                   R                  nU
b  U
OU R                   R                  n
U	b  U	OU R                   R                  n	U R                  " SUU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                  " UX`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)
ra  r   r   r4  rb  r  r   rc  r  r   )lossaux_lossr  r4  rD   rh  r   r
  )r+   r   r  rc  r3  rg  r(  r   slicer  loss_functionrP  r  r   rT   rU   r  ry   ri   r   r4  rD   rh  )r=   ra  r   r   r4  rb  r  r  r   rc  r  r   r  r   r  rD   slice_indicesr  r  r  s                       r?   rF   MixtralForCausalLM.forwardg  s   R 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 %9$D $++JjJj 	
 +/** +
)%+'/!5!5)+
 +
  118B>SV8W8W~ot4]kmA}a,?@A%%ffooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
rA   )r  r3  rT   rU   r  rP  )NNNNNNNNNNNr   )rH   rI   rJ   rK   _tied_weights_keys_tp_plan_pp_planr1   r[  r_  r  r  r  r  r!   r    r   rp   r   r   r   r  r  r   r   r   r  r   rF   rL   rM   rN   s   @r?   r  r  C  s   *+=)H_-z:;H
'(&  151537=A59-1$(,0/3/35934[
E,,-[
 !.[
 u//0	[

 "$u'8'8"9:[
   1 12[
 ))*[
 D>[
 $D>[
 'tn[
 'tn[
 !!1!12[
 c5<</0[
 *+[
 
#[
  [
rA   r  a  
    The Mixtral Model transformer with a sequence classification head on top (linear layer).

    [`MixtralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    )custom_introc                   *  ^  \ rS rS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\	\   S\4S jj5       5       rSrU =r$ ) MixtralForSequenceClassificationi  c                    > [         TU ]  U5        UR                  U l        [        U5      U l        [
        R                  " UR                  U R                  SS9U l        U R                  5         g r-   )
r0   r1   
num_labelsrM  r3  r	   r6   r4   scorerW  r<   s     r?   r1   )MixtralForSequenceClassification.__init__  sS      ++!&)
YYv114??O
 	rA   c                 .    U R                   R                  $ rC   r  r   s    r?   r[  5MixtralForSequenceClassification.get_input_embeddings  r  rA   c                 $    XR                   l        g rC   r  r^  s     r?   r_  5MixtralForSequenceClassification.set_input_embeddings  r  rA   ra  r   r   r4  rb  r  r  r   rc  r_   c
                    U R                  UUUUUUUU	S9n
U
R                  nU R                  U5      nUb  UR                  S   nOUR                  S   nU R                  R
                  c  US:w  a  [        S5      eU R                  R
                  c  SnOUb  XR                  R
                  :g  R                  UR                  [        R                  5      n[        R                  " UR                  S   UR                  [        R                  S9nUU-  R                  S5      nO.Sn[        R                  U R                  R                    S35        U[        R                  " XR                  S	9U4   nSnUb  U R#                  XUU R                  S
9n[%        UUU
R&                  U
R(                  U
R*                  S9$ )e  
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
    Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
    config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
    `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
r   r   r4  rb  r  r   rc  Nr   r$   z=Cannot handle batch sizes > 1 if no padding token is defined.rc   )ri   rf   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rf  )r  r  pooled_logitsr+   )r  r  r4  rD   rh  )r3  rg  r  rn   r+   rO  ri  ry   ri   rp   int32rk  argmaxr   r   r>   rH   r  r   r4  rD   rh  )r=   ra  r   r   r4  rb  r  r  r   rc  transformer_outputsrD   r  r   last_non_pad_tokennon_pad_masktoken_indicesr  r  s                      r?   rF   (MixtralForSequenceClassification.forward  s   * 8<zz)%+'/!5 8B 	8
 ,==M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||J}}MOaab%%VR_hlhshs%tD/ /??-;;*55
 	
rA   )r3  r  r  	NNNNNNNNN)rH   rI   rJ   rK   r1   r[  r_  r!   r    r   rp   r   r   r   r  r  r   rF   rL   rM   rN   s   @r?   r  r    s    '(  151537+/59-1$(,0/3A
E,,-A
 !.A
 u//0	A

 "%A
   1 12A
 ))*A
 D>A
 $D>A
 'tnA
 
*A
  A
rA   r  c                   *  ^  \ rS rS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\	\   S\4S jj5       5       rSrU =r$ )MixtralForTokenClassificationi+  c                   > [         TU ]  U5        UR                  U l        [        U5      U l        [        USS 5      b  UR                  nO[        USS 5      b  UR                  nOSn[        R                  " U5      U l
        [        R                  " UR                  UR                  5      U l        U R                  5         g )Nclassifier_dropouthidden_dropoutg?)r0   r1   r  rM  r3  r   r  r  r	   Dropoutr   r6   r4   r  rW  )r=   r+   r  r>   s      r?   r1   &MixtralForTokenClassification.__init__-  s      ++!&)
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	rA   c                 .    U R                   R                  $ rC   r  r   s    r?   r[  2MixtralForTokenClassification.get_input_embeddings=  r  rA   c                 $    XR                   l        g rC   r  r^  s     r?   r_  2MixtralForTokenClassification.set_input_embeddings@  r  rA   ra  r   r   r4  rb  r  r  r   rc  r_   c
                    U R                  UUUUUUUU	S9n
U
R                  nU R                  U5      nU R                  U5      nSnUb  U R	                  XU R
                  5      n[        UUU
R                  U
R                  S9$ )r  r  N)r  r  rD   rh  )	r3  rg  r   r  r  r+   r   rD   rh  )r=   ra  r   r   r4  rb  r  r  r   rc  r  sequence_outputr  r  s                 r?   rF   %MixtralForTokenClassification.forwardC  s    * ,0::)%+'/!5 ,6 	,
 "33,,7O,%%fdkkBD$!//))	
 	
rA   )r   r3  r  r  r  )rH   rI   rJ   rK   r1   r[  r_  r!   r    r   rp   r   r   r   r  r  r   rF   rL   rM   rN   s   @r?   r  r  +  s     '(  151537+/59-1$(,0/3*
E,,-*
 !.*
 u//0	*

 "%*
   1 12*
 ))**
 D>*
 $D>*
 'tn*
 
*
  *
rA   r  c                   f  ^  \ rS rSrSrU 4S jrS rS r\\	         SS\
\R                     S\
\R                     S\
\R                     S	\
\\\\R"                     4      S
\
\R"                     S\
\R                     S\
\R                     S\
\   S\
\   S\4S jj5       5       rSrU =r$ )MixtralForQuestionAnsweringir  r3  c                    > [         TU ]  U5        [        R                  " UR                  S5      U l        [        U5      U l        U R                  5         g )Nrk   )	r0   r1   r	   r6   r4   
qa_outputsrM  r3  rW  r<   s     r?   r1   $MixtralForQuestionAnswering.__init__v  s@     ))F$6$6:!&)
 	rA   c                 .    U R                   R                  $ rC   r  r   s    r?   r[  0MixtralForQuestionAnswering.get_input_embeddings~  r  rA   c                 $    XR                   l        g rC   r  r^  s     r?   r_  0MixtralForQuestionAnswering.set_input_embeddings  r  rA   ra  r   r   r4  rb  start_positionsend_positionsr   rc  r_   c
           
         U R                  UUUUUUU	S9nUR                  nU R                  U5      nUR                  SSS9u  pUR	                  S5      R                  5       nUR	                  S5      R                  5       nSnUb  Ub  U R                  " XXg40 U
D6n[        UUUUR                  UR                  S9$ )a  
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
    Labels for position (index) of the start of the labelled span for computing the token classification loss.
    Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
    are not taken into account for computing the loss.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
    Labels for position (index) of the end of the labelled span for computing the token classification loss.
    Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
    are not taken into account for computing the loss.
)r   r   r4  rb  r   rc  r$   rc   rg   N)r  start_logits
end_logitsrD   rh  )
r3  rg  r  splitsqueezer   r  r   rD   rh  )r=   ra  r   r   r4  rb  r  r  r   rc  r   r  r  r  r  r  r  s                    r?   rF   #MixtralForQuestionAnswering.forward  s    4 ,0::)%+'/!5 ,6 ,
 "331#)<<r<#: #++B/::<''+668
&=+D%%libhiD+%!!//))
 	
rA   )r3  r  r  )rH   rI   rJ   rK   rA  r1   r[  r_  r!   r    r   rp   r   r   r   r   r   r  r  r   rF   rL   rM   rN   s   @r?   r  r  r  s   '(  151537KO596:48,0/33
E,,-3
 !.3
 u//0	3

 "%tE4E4E/F(F"GH3
   1 123
 "%"2"233
   0 013
 $D>3
 'tn3
 
&3
  3
rA   r  )r  r  rM  r2  r  r  )Nr$   )r   )Nrk   N)Q	functoolsr   typingr   r   r   r   r   rp   torch.nn.functionalr	   r{   rt   activationsr   cache_utilsr   r   r   r   
generationr   integrationsr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r    r!   r"   r#   configuration_mixtralr%   !torch.nn.attention.flex_attentionr&   integrations.flex_attentionr'   
get_loggerrH   r   Moduler)   rP   r   r   r   r   r   r   rv   r   r   r   r  r2  rM  r  r  r  r  r  r  __all__r
  rA   r?   <module>r     s  6  9 9     ! O O ) 7 > B  L F & h h 0  !!;J 
		H	%%		 %$@2BII @2F Y'JRYY J (J((6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4A)ryy A)HN")) Nb<RYY <D *_ * *8 d) d dN	 ?,j >
 "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&d @
/ @
 @
F S
'= S
S
l C
$: C
 C
L F
"8 F
 F
RrA   