
    qiI              
          d 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 dd
lmZ ddlmZ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%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,  ejZ                  e.      Z/	 	 	 d4dej`                  e1ej`                     z  dz  de2dz  dej`                  dz  dej`                  e2z  fdZ3e G d dejh                               Z5 G d dejh                        Z6 G d dejh                        Z7 G d d e)      Z8 G d! d"e*      Z9 G d# d$e"      Z: G d% d&e      Z; G d' d(e(      Z< G d) d*e'      Z= G d+ d,e#      Z> G d- d.e%      Z? G d/ d0e&      Z@ G d1 d2e$      ZAg d3ZBy)5zPyTorch Mixtral model.    N)nn   )initialization)ACT2FN)CacheDynamicCache)use_experts_implementation)create_causal_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)PreTrainedModel)Unpack)TransformersKwargslogging)OutputRecorder   )	MistralAttentionMistralForCausalLMMistralForQuestionAnswering MistralForSequenceClassificationMistralForTokenClassificationMistralModelMistralPreTrainedModelMistralRMSNormMistralRotaryEmbedding   )MixtralConfiggate_logitsnum_expertsattention_maskreturnc                    | 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   dim)
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesum	unsqueeze)r    r!   top_kr"   compute_device
layer_gateconcatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_losss                      ]/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/mixtral/modular_mixtral.pyload_balancing_loss_funcrJ   5   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                        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 )Nr   )super__init__num_local_expertsr!   hidden_size
hidden_dimintermediate_sizeintermediate_dimr   	Parameterr+   emptygate_up_proj	down_projr   
hidden_actact_fnselfrM   	__class__s     rI   rP   zMixtralExperts.__init__   s    !33 ,, & 8 8LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../    hidden_statestop_k_indextop_k_weightsr#   c                 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   )r'   r%   r'   )r+   
zeros_likeno_gradr   r.   r1   r!   permutegreaterr7   nonzerowherelinearrX   chunkr[   rY   
index_add_r-   dtype)r]   r`   ra   rb   final_hidden_statesr@   
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 rI   forwardzMixtralExperts.forward   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   rP   r+   Tensorry   __classcell__r^   s   @rI   rL   rL      sM    <0} 0#||# \\# ||	#
 
#r_   rL   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)rO   rP   num_experts_per_tokr9   rQ   r!   rR   rS   r   rV   r+   rW   weightr\   s     rI   rP   zMixtralTopKRouter.__init__   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 )Nr'   r%   T)r&   keepdim)r6   rS   Frl   r   r+   r   r.   r/   r3   r0   r9   r7   )r]   r`   router_logitsrouter_top_valuerouter_indicesrouter_scoress         rI   ry   zMixtralTopKRouter.forward   s    %--b$//B<++33M4G4G4Ir3R+0::mTZZUW+X(.,00R0FF(m^;;r_   )rz   r{   r|   rP   ry   r   r   s   @rI   r   r      s    S<r_   r   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 r   )
rO   rP   r   r9   router_jitter_noisejitter_noiser   rv   rL   expertsr\   s     rI   rP   zMixtralSparseMoeBlock.__init__   sA    //
"66%f-	%f-r_   r`   r#   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   g      ?r'   )
r4   trainingr   r+   
empty_likeuniform_viewrv   r   r6   )r]   r`   rC   rD   rS   r>   rb   ra   s           rI   ry   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_   )	rz   r{   r|   rP   r+   r~   r)   ry   r   r   s   @rI   r   r      s1    .U\\ eELL%,,<V6W r_   r   c                       e Zd Zy)MixtralRMSNormNrz   r{   r|    r_   rI   r   r          r_   r   c                       e Zd Zy)MixtralRotaryEmbeddingNr   r   r_   rI   r   r      r   r_   r   c                       e Zd Zy)MixtralAttentionNr   r   r_   rI   r   r      r   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 )MixtralDecoderLayerrM   	layer_idxc                    t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)eps)rO   rP   rR   r   	self_attnr   mlpr   rms_norm_epsinput_layernormpost_attention_layernorm)r]   rM   r   r^   s      rI   rP   zMixtralDecoderLayer.__init__   sl    !--)&)<(0-f.@.@fFYFYZ(6v7I7IvObOb(c%r_   Nr`   position_embeddingsr"   position_idspast_key_valuescache_positionkwargsr#   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   r   residualr>   s
             rI   ry   zMixtralDecoderLayer.forward   s     !,,];)4>> 
' 3)%+)
 
q !=0 55mD/ =0r_   )NNNNN)rz   r{   r|   r   intrP   r+   r~   r)   
LongTensorr   r   r   ry   r   r   s   @rI   r   r      s    d} d d IM.204(,26|| #5<<#=>E t+	
 &&-  ((4/ +, 
r_   r   c                   V    e Zd Z eed      eedZ ej                         d        Z
y)MixtralPreTrainedModelr   )index)r   r`   
attentionsc                 l   t        j                  | |       | j                  j                  }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       y t	        |t              r#t        j                  |j                  d|       y y )Ng        )r2   std)r   _init_weightsrM   initializer_ranger(   rL   initnormal_rX   rY   r   r   )r]   moduler   s      rI   r   z$MixtralPreTrainedModel._init_weights  s{    %%dF3kk++fn-LL,,3C@LL))= 12LLSc: 3r_   N)rz   r{   r|   r   r   r   r   _can_record_outputsr+   rg   r   r   r_   rI   r   r     s7    '(9C,& U]]_; ;r_   r   c                       e Zd Z	 	 	 	 	 	 	 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y)MixtralModelN	input_idsr"   r   r   inputs_embeds	use_cacher   r   r#   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_embeds)rM   r   r   )r*   )rM   r   r"   r   r   r   )r   )r"   r   r   r   r   r   )last_hidden_stater   )
ValueErrorr   rM   embed_tokensget_seq_lengthr+   aranger4   r*   r8   sliding_windowr
   r   
rotary_emblayersrE   normr   )r]   r   r"   r   r   r   r   r   r   past_seen_tokensmask_functioncausal_maskr`   r   decoder_layers                  rI   ry   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)rz   r{   r|   r+   r   r~   r   FloatTensorboolr   r   r   ry   r   r_   rI   r   r     s     .2.204(,26!%26:
##d*:
 t+:
 &&-	:

 :
 ((4/:
 $;:
 ((4/:
 +,:
 
 :
r_   r   c                   B    e Zd ZddiZ fdZ	 	 	 	 	 	 	 	 	 	 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.weightc                     t         |   |       t        |      | _        |j                  | _        |j
                  | _        |j                  | _        y r   )rO   rP   r   modelrouter_aux_loss_coefrQ   r!   r   r\   s     rI   rP   zMixtralForCausalLM.__init__[  sF     !&)
$*$?$?!!33#)#=#= r_   Nr   r"   r   r   r   labelsr   output_router_logitsr   logits_to_keepr   r#   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)r   r"   r   r   r   r   r   r   )lossaux_losslogitsr   r`   r   r   r   )rM   r   r   r   r(   r   slicelm_headloss_function
vocab_sizerJ   r   r!   r   r   r-   r*   r   r   r`   r   )r]   r   r"   r   r   r   r   r   r   r   r   r   outputsr`   slice_indicesr   r   r   s                     rI   ry   zMixtralForCausalLM.forwardb  sX   L %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   )rz   r{   r|   _tied_weights_keysrP   r+   r   r~   r   r   r   r   r   r   r   ry   r   r   s   @rI   r   r   X  s   *,G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   c                       e Zd Zy) MixtralForSequenceClassificationNr   r   r_   rI   r   r     r   r_   r   c                       e Zd Zy)MixtralForTokenClassificationNr   r   r_   rI   r   r     r   r_   r   c                       e Zd Zy)MixtralForQuestionAnsweringNr   r   r_   rI   r   r     r   r_   r   )r   r   r   r   r   r   )Nr   N)Cr}   r+   torch.nn.functionalr   r.   r    r   r   activationsr   cache_utilsr   r   integrationsr	   masking_utilsr
   r   modeling_layersr   modeling_outputsr   r   modeling_utilsr   processing_utilsr   utilsr   r   utils.output_capturingr   mistral.modeling_mistralr   r   r   r   r   r   r   r   r   configuration_mixtralr   
get_loggerrz   loggerr~   r)   r   rJ   ModulerL   r   r   r   r   r   r   r   r   r   r   r   r   __all__r   r_   rI   <module>r     s  &      & ! . 6 R 9 Q - & 0 4
 
 
 1 
		H	%
 #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d $#RYY $# $#N<		 <$BII &	^ 		3 		' 	%4 %P;3 ;$;
< ;
|\
+ \
~	'G 		$A 		"= 	r_   