
    qi,z                        d dl mZ d dlmZ d dlZd dlmc mZ d dlmZ ddl	m
Z ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZ ddlmZmZ ddlmZ ddlmZmZm Z m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 e G d dejr                               Z: G d dejr                        Z; G d dejr                        Z< ed       G d dejr                               Z= G d  d!ejr                        Z>d" Z? ed#      dFd$       Z@d%ej                  d&eBd'ej                  fd(ZC	 dGd)ejr                  d*ej                  d+ej                  d,ej                  d-ej                  dz  d.eDd/eDd0e,e.   fd1ZE ee@       G d2 d3ejr                               ZF G d4 d5e!      ZGe/ G d6 d7e*             ZHe/ G d8 d9eH             ZI	 	 	 dHd:ej                  eJej                     z  dz  d;eBdz  d-ej                  dz  d'ej                  eBz  fd<ZKe/ G d= d>eHe             ZL G d? d@eeH      ZM G dA dBe eH      ZN G dC dDeeH      ZOg dEZPy)I    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_causal_mask!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)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )MixtralConfigc                        e Zd ZdZdef fdZdej                  dej                  dej                  dej                  fdZ xZ	S )	MixtralExpertsz2Collection of expert weights stored as 3D tensors.configc                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j                  d| j                  z  | j
                              | _        t        j                  t        j                  | j                  | j
                  | j                              | _        t        |j                     | _        y )N   )super__init__num_local_expertsnum_expertshidden_size
hidden_dimintermediate_sizeintermediate_dimr   	Parametertorchemptygate_up_proj	down_projr   
hidden_actact_fnselfr)   	__class__s     ^/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/mixtral/modeling_mixtral.pyr-   zMixtralExperts.__init__A   s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../    hidden_statestop_k_indextop_k_weightsreturnc                 f   t        j                  |      }t        j                         5  t         j                  j                  j                  || j                        }|j                  ddd      }t        j                  |j                  d      d      j                         }d d d        D ]  }|d   }|| j                  k(  rt        j                  |         \  }}	||	   }
t        j                  j                  |
| j                  |         j                  dd      \  }}| j                  |      |z  }t        j                  j                  || j                   |         }|||	|d f   z  }|j#                  d|	|j%                  |j&                                |S # 1 sw Y   xY w)N)num_classesr+   r%   r   )dimrF   )r5   
zeros_likeno_gradr   
functionalone_hotr/   permutegreatersumnonzerowherelinearr7   chunkr:   r8   
index_add_todtype)r<   r@   rA   rB   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 r>   forwardzMixtralExperts.forwardJ   s    $..}=]]_ 	S((--55ktO_O_5`K%--aA6K{8'DaHPPRJ	S
 % 
	nJ#AJT---#(;;{:/F#G Iy))4M}}++M4;L;LZ;XY__`agi_jHD"$(KK$5$:!$&MM$8$89NPTP^P^_iPj$k!$9M)U^`dJd<e$e!**1i9N9Q9QReRkRk9lm
	n #"#	S 	Ss   A=F&&F0)
__name__
__module____qualname____doc__r&   r-   r5   Tensorrb   __classcell__r=   s   @r>   r(   r(   =   sM    <0} 0#||# \\# ||	#
 
#r?   r(   c                   $     e Zd Z fdZd Z xZS )MixtralTopKRouterc                    t         |           |j                  | _        |j                  | _        |j                  | _        t        j                  t        j                  | j
                  | j                              | _        y N)r,   r-   num_experts_per_toktop_kr.   r/   r0   r1   r   r4   r5   r6   weightr;   s     r>   r-   zMixtralTopKRouter.__init__f   s[    //
!33 ,,ll5;;t/?/?#QRr?   c                 p   |j                  d| j                        }t        j                  || j                        }t
        j                  j                  j                  |j                         d      }t        j                  || j                  d      \  }}||j                  dd      z  }|}|||fS )NrF   rH   T)rI   keepdim)reshaper1   FrS   rp   r5   r   rL   softmaxfloattopkro   rP   )r<   r@   router_logitsrouter_top_valuerouter_indicesrouter_scoress         r>   rb   zMixtralTopKRouter.forwardm   s    %--b$//B<++33M4G4G4Ir3R+0::mTZZUW+X(.,00R0FF(m^;;r?   )rc   rd   re   r-   rb   rh   ri   s   @r>   rk   rk   e   s    S<r?   rk   c                   t     e Zd Z fdZdej
                  deej
                  ej
                  f   fdZ xZS )MixtralSparseMoeBlockc                     t         |           |j                  | _        |j                  | _        t        |      | _        t        |      | _	        y rm   )
r,   r-   rn   ro   router_jitter_noisejitter_noiserk   r_   r(   expertsr;   s     r>   r-   zMixtralSparseMoeBlock.__init__x   sA    //
"66%f-	%f-r?   r@   rC   c                    |j                   \  }}}| j                  rQ| j                  dkD  rB|t        j                  |      j                  d| j                  z
  d| j                  z         z  }|j                  d|j                   d         }| j                  |      \  }}}| j                  |||      }|j                  |||      }|S )Nr         ?rF   )
shapetrainingr   r5   
empty_likeuniform_viewr_   r   rs   )r<   r@   
batch_sizesequence_lengthr1   _rB   rA   s           r>   rb   zMixtralSparseMoeBlock.forward   s    2?2E2E/
OZ==T..2U--m<EEcDL]L]F]_beievev_vwwM%**2}/B/B2/FG(,		-(@%=+]KO%--j/:Vr?   )	rc   rd   re   r-   r5   rg   tuplerb   rh   ri   s   @r>   r}   r}   w   s1    .U\\ eELL%,,<V6W r?   r}   RMSNormc                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	MixtralRMSNormepsrC   Nc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        MixtralRMSNorm is equivalent to T5LayerNorm
        N)r,   r-   r   r4   r5   onesrp   variance_epsilon)r<   r0   r   r=   s      r>   r-   zMixtralRMSNorm.__init__   s1     	ll5::k#:; #r?   r@   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr+   rF   T)rr   )	rW   rV   r5   float32powmeanrsqrtr   rp   )r<   r@   input_dtypevariances       r>   rb   zMixtralRMSNorm.forward   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r?   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r   rp   r   r   )r<   s    r>   
extra_reprzMixtralRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr?   )gư>)
rc   rd   re   rv   r-   r5   rg   rb   r   rh   ri   s   @r>   r   r      s7    $ $$ $;U\\ ;ell ;Jr?   r   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )MixtralRotaryEmbeddinginv_freqNr)   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultr   F)
persistentoriginal_inv_freq)r,   r-   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr)   rope_parametersr   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r<   r)   devicerope_init_fnr   r=   s        r>   r-   zMixtralRotaryEmbedding.__init__   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr?   r   ztorch.deviceseq_lenrC   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimNr   r   r+   rW   )r   rW   )	r   getattrr0   num_attention_headsr5   arangeint64rV   rv   )r)   r   r   baserI   attention_factorr   s          r>   r   z6MixtralRotaryEmbedding.compute_default_rope_parameters   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r?   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   rF   r%   mpscpuF)device_typeenabledr+   rH   r   )r   rv   expandr   rV   r   
isinstancetypestrr!   	transposer5   catcosr   sinrW   )
r<   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r>   rb   zMixtralRotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$rm   )NNN)rc   rd   re   r5   rg   __annotations__r&   r-   staticmethodr   intr   rv   r   rK   r   rb   rh   ri   s   @r>   r   r      s    llV} V  '++/"*$*(* t* 
~u$	%	* *: U]]_<  <r?   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..NrF   r+   rH   )r   r5   r   )r   x1x2s      r>   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r?   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r>   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr?   r@   n_reprC   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r%   N)r   r   rs   )r@   r   batchnum_key_value_headsslenr   s         r>   	repeat_kvr     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr?   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr+   r   rF   )rI   rW   )pr   r%   )r   num_key_value_groupsr5   matmulr   r   rL   ru   r   rV   rW   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r>   eager_attention_forwardr     s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r?   c                       e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   dej                  dz  d	e
dz  d
ej                  dz  dee   de	ej                  ej                  dz  f   fdZ xZS )MixtralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr)   	layer_idxc                    t         |           || _        || _        t	        |dd       xs |j
                  |j                  z  | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j                  | j                  z  |j
                  d      | _        y )Nr   g      TFbias)r,   r-   r)   r   r   r0   r   r   r   r   r   attention_dropout	is_causalr   Linearq_projk_projv_projo_projr<   r)   r   r=   s      r>   r-   zMixtralAttention.__init__*  s2   "
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?   Nr@   position_embeddingsr   past_key_valuescache_positionr   rC   c           
      D   |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        j                  | j                  j                  t              } || |	|
||f| j                  sdn| j                   | j"                  t%        | j                  dd       d|\  }} |j&                  g |d j)                         }| j+                  |      }||fS )NrF   r%   r+   )r   r   r          sliding_window)r   r   r  )r   r   r   r   r   r   r   r   updater   r   get_interfacer)   _attn_implementationr   r   r   r   r   rs   r   r  )r<   r@   r  r   r  r  r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r>   rb   zMixtralAttention.forward8  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&S#7jRUWZ#[ j&#&snUL'6'='=j,X\XfXfht'u$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ *k));;;;FFHkk+.L((r?   )NN)rc   rd   re   rf   r&   r   r-   r5   rg   r   r	   
LongTensorr   r   rb   rh   ri   s   @r>   r   r   &  s    Gl} l l& )-26*)||*) #5<<#=>*) t+	*)
 *) ((4/*) -.*) 
u||U\\D00	1*)r?   r   c                       e Zd Zdedef fdZ	 	 	 	 	 ddej                  deej                  ej                  f   dz  dej                  dz  dej                  dz  d	e
dz  d
ej                  dz  dee   dej                  fdZ xZS )MixtralDecoderLayerr)   r   c                    t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )Nr   )r,   r-   r0   r   	self_attnr}   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr  s      r>   r-   zMixtralDecoderLayer.__init__f  sl    !--)&)<(0-f.@.@fFYFYZ(6v7I7IvObOb(c%r?   Nr@   r  r   r   r  r  r   rC   c           
          |}| j                  |      } | j                  d||||||d|\  }}	||z   }|}| j                  |      }| j                  |      }||z   }|S )N)r@   r  r   r   r  r   )r  r  r  r  )
r<   r@   r  r   r   r  r  r   residualr   s
             r>   rb   zMixtralDecoderLayer.forwardp  s     !,,];)4>> 
' 3)%+)
 
q !=0 55mD/ =0r?   )NNNNN)rc   rd   re   r&   r   r-   r5   rg   r   r  r	   r   r   rb   rh   ri   s   @r>   r  r  e  s    d} d d IM.204(,26|| #5<<#=>E t+	
 &&-  ((4/ +, 
r?   r  c                        e Zd ZU eed<   dZdZdgZdgZdZ	dZ
dZdZdZ eed      eedZ ej(                          fd	       Z xZS )
MixtralPreTrainedModelr)   modelTr  r  r   )index)rx   r@   
attentionsc                 `   t         |   |       | j                  j                  }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       y t	        |t              r#t        j                  |j                  d|       y y )Nr  )r   std)r,   _init_weightsr)   initializer_ranger   r(   initnormal_r7   r8   rk   rp   )r<   r   r$  r=   s      r>   r%  z$MixtralPreTrainedModel._init_weights  sy    f%kk++fn-LL,,3C@LL))= 12LLSc: 3r?   )rc   rd   re   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_outputsr5   rK   r%  rh   ri   s   @r>   r  r    sy    &*#./#4"5N!"&'(9C,& U]]_; ;r?   r  c                       e Zd Zdef fdZeee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dedz  dej                  dz  d	edz  d
ej                  dz  dee   defd                     Z xZS )MixtralModelr)   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr  r)   F)r,   r-   pad_token_idpadding_idx
vocab_sizer   	Embeddingr0   embed_tokens
ModuleListrangenum_hidden_layersr  layersr   r  normr   
rotary_embgradient_checkpointing	post_initr  s      r>   r-   zMixtralModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEde	 3e
 #6#5#56;N;NO	0?&+# 	 fs   DN	input_idsr   r   r  inputs_embeds	use_cacher  r   rC   c                    |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|F||j	                         nd}	t        j                  |	|	|j                  d   z   |j                        }||j                  d      }| j                  j                  t        nt        }
 |
| j                  |||||      }|}| j                  ||      }| j                  d | j                  j                   D ]  } ||f||||||d|} | j!                  |      }t#        ||	      S )
Nz:You must specify exactly one of input_ids or inputs_embedsr6  r   r%   )r   )r)   rE  r   r  r  r   )r   )r   r   r  rF  r  r  )last_hidden_stater  )
ValueErrorr
   r)   r;  get_seq_lengthr5   r   r   r   r   r  r   r   rA  r?  r>  r@  r   )r<   rD  r   r   r  rE  rF  r  r   past_seen_tokensmask_functioncausal_maskr@   r  decoder_layers                  r>   rb   zMixtralModel.forward  sx    -t";<YZZ0*$++>O  --i8M!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L.2kk.H.H.P*Vw#;;'))+%
 &"oom,oW![[)H4;;+H+HI 
	M)	*) /#-$7	 	M
	 		-0%++
 	
r?   )NNNNNNN)rc   rd   re   r&   r-   r"   r$   r   r5   r  rg   r	   FloatTensorboolr   r   r   rb   rh   ri   s   @r>   r4  r4    s    }     .2.204(,26!%26:
##d*:
 t+:
 &&-	:

 :
 ((4/:
 $;:
 ((4/:
 +,:
 
 :
    :
r?   r4  gate_logitsr/   c                    | t        | t              syt        | t              rC| d   j                  }t        j                  | D cg c]  }|j                  |       c}d      }t        j                  j                  j                  d      }t        j                  ||d      \  }}	t        j                  j                  j                  |	|      }
|>t        j                  |
j                         d      }t        j                  |d      }n|j                  \  }}|j                  d   ||z  z  }|dddddddf   j                  |||||f      j                  d||      j                        }t        j                   |
j                         |z  d      t        j                   |d      z  }|ddddddf   j                  ||||f      j                  d|      j                  |      }t        j                   ||z  d      t        j                   |d      z  }t        j                   ||j#                  d      z        }||z  S c c}w )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

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

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

    Returns:
        The auxiliary loss.
    Nr   rH   rF   )r   r   r   r5   r   rV   r   rL   ru   rw   rM   r   rv   r   r   rs   rP   r   )rQ  r/   ro   r   compute_device
layer_gateconcatenated_gate_logitsrouting_weightsr   selected_expertsrY   tokens_per_expertrouter_prob_per_expertr   r   r>  expert_attention_mask router_per_expert_attention_maskoverall_losss                      r>   load_balancing_loss_funcr]    s9   : *[%"@+u%$Q..#(99^i-jPZjmmN.K-jpq#r hh))112JPR1SO**_eDA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
O4::1=*B^_ 4AtT12V&
OUKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&
O[QRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1G1Q1QRS1TTUL+%%[ .ks   Ic                   n    e Zd ZddiZddiZddgdgfiZ fdZee	 	 	 	 	 	 	 	 	 	 dd	e	j                  dz  d
e	j                  dz  de	j                  dz  dedz  de	j                  dz  de	j                  dz  dedz  dedz  de	j                  dz  dee	j                  z  dee   defd              Z xZS )MixtralForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr@   logitsc                 N   t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        |j                  | _	        |j                  | _        |j                  | _        | j                          y )NFr   )r,   r-   r4  r   r9  r   r   r0   r`  router_aux_loss_coefr.   r/   rn   rC  r;   s     r>   r-   zMixtralForCausalLM.__init__U  s     !&)
 ++yy!3!3V5F5FUS$*$?$?!!33#)#=#=  	r?   NrD  r   r   r  rE  labelsrF  output_router_logitsr  logits_to_keepr   rC   c                 l   ||n| j                   j                  } | j                  d||||||||	d|}|j                  }t	        |
t
              rt        |
 d      n|
}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |}d}|rYt        |j                  | j                  | j                  |      }|+|| j                  |j                  |j                         z  z  }t#        ||||j$                  |j&                  |j(                  |j                        S )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)rD  r   r   r  rE  rF  rf  r  )lossaux_lossrb  r  r@   r"  rx   r  )r)   rf  r   rH  r   r   slicer`  loss_functionr9  r]  rx   r/   rn   rd  rV   r   r   r  r@   r"  )r<   rD  r   r   r  rE  re  rF  rf  r  rg  r   outputsr@   slice_indicesrb  ri  rj  s                     r>   rb   zMixtralForCausalLM.forwarda  sX   P %9$D $++JjJj 	
 +5$** 
+
)%+'!5)
+
 
+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r?   )
NNNNNNNNNr   )rc   rd   re   _tied_weights_keys_tp_plan_pp_planr-   r    r   r5   r  rg   r	   rO  rP  r   r   r   r   rb   rh   ri   s   @r>   r_  r_  O  sN   *,GH23H_-z:;H
  .2.204(,26*.!%,026-.R
##d*R
 t+R
 &&-	R

 R
 ((4/R
   4'R
 $;R
 #TkR
 ((4/R
 ell*R
 +,R
 
#R
  R
r?   r_  c                       e Zd Zy) MixtralForSequenceClassificationNrc   rd   re   r  r?   r>   rs  rs        r?   rs  c                       e Zd Zy)MixtralForTokenClassificationNrt  r  r?   r>   rw  rw    ru  r?   rw  c                       e Zd Zy)MixtralForQuestionAnsweringNrt  r  r?   r>   ry  ry    ru  r?   ry  )r_  ry  r4  r  rs  rw  )r%   )r  )Nr+   N)Qcollections.abcr   typingr   r5   torch.nn.functionalr   rL   rt    r   r'  activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   r   r   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!   r"   utils.output_capturingr#   r$   configuration_mixtralr&   Moduler(   rk   r}   r   r   r   r   rg   r   r   rv   r   r   r  r  r4  r   r]  r_  rs  rw  ry  __all__r  r?   r>   <module>r     s  4 %      & ! . )  S B  R K F & I I G E 0 $#RYY $# $#N<		 <$BII & Y'JRYY J (J(><RYY ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*;)ryy ;) +;)|%4 %P ;_ ; ;: N
) N
 N
f #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d e
/ e
 e
P	'GI_ 		$ACY 		"=?U 	r?   