
    iI              
       "   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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j\                  e/      Z0	 	 	 d4dejb                  e2ejb                     z  dz  de3dz  dejb                  dz  dejb                  e3z  fdZ4e G d dejj                               Z6 G d dejj                        Z7 G d dejj                        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- d.e&      Z@ G d/ d0e'      ZA G d1 d2e%      ZBg d3ZCy)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is_grouped_mm_available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                      u/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/mixtral/modular_mixtral.pyload_balancing_loss_funcrK   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selfrN   	__class__s     rJ   rQ   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/   r2   r"   permutegreaterr8   nonzerowherelinearrY   chunkr\   rZ   
index_add_r.   dtype)r^   ra   rb   rc   final_hidden_statesrA   
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statess                 rJ   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    rQ   r,   Tensorrz   __classcell__r_   s   @rJ   rM   rM      sM    <0} 0#||# \\# ||	#
 
#r`   rM   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)rP   rQ   num_experts_per_tokr:   rR   r"   rS   rT   r   rW   r,   rX   weightr]   s     rJ   rQ   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)r7   rT   Frm   r   r,   r   r/   r0   r4   r1   r:   r8   )r^   ra   router_logitsrouter_top_valuerouter_indicesrouter_scoress         rJ   rz   zMixtralTopKRouter.forward   s    %--b$//B<++33M4G4G4Ir3R+0::mTZZUW+X(.,00R0FF(m^;;r`   )r{   r|   r}   rQ   rz   r   r   s   @rJ   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   )
rP   rQ   r   r:   router_jitter_noisejitter_noiser   rw   rM   expertsr]   s     rJ   rQ   zMixtralSparseMoeBlock.__init__   sA    //
"66%f-	%f-r`   ra   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(   )
r5   trainingr   r,   
empty_likeuniform_viewrw   r   r7   )r^   ra   rD   rE   rT   r?   rc   rb   s           rJ   rz   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`   )	r{   r|   r}   rQ   r,   r   r*   rz   r   r   s   @rJ   r   r      s1    .U\\ eELL%,,<V6W r`   r   c                       e Zd Zy)MixtralRMSNormNr{   r|   r}    r`   rJ   r   r          r`   r   c                       e Zd Zy)MixtralRotaryEmbeddingNr   r   r`   rJ   r   r      r   r`   r   c                       e Zd Zy)MixtralAttentionNr   r   r`   rJ   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 )MixtralDecoderLayerrN   	layer_idxc                    t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)eps)rP   rQ   rS   r   	self_attnr   mlpr   rms_norm_epsinput_layernormpost_attention_layernorm)r^   rN   r   r_   s      rJ   rQ   zMixtralDecoderLayer.__init__   sl    !--)&)<(0-f.@.@fFYFYZ(6v7I7IvObOb(c%r`   Nra   position_embeddingsr#   position_idspast_key_valuescache_positionkwargsr$   c           
          |}| j                  |      } | j                  d||||||d|\  }}	||z   }|}| j                  |      }| j                  |      }||z   }|S )N)ra   r   r#   r   r   r   r   )r   r   r   r   )
r^   ra   r   r#   r   r   r   r   residualr?   s
             rJ   rz   zMixtralDecoderLayer.forward   s     !,,];)4>> 
' 3)%+)
 
q !=0 55mD/ =0r`   )NNNNN)r{   r|   r}   r    intrQ   r,   r   r*   
LongTensorr   r   r   rz   r   r   s   @rJ   r   r      s    d} d d IM.204(,26|| #5<<#=>E t+	
 &&-  ((4/ +, 
r`   r   c                   d    e Zd Z e       Z eed      eedZ	 e
j                         d        Zy)MixtralPreTrainedModelr   )index)r   ra   
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        )r3   std)r   _init_weightsrN   initializer_ranger)   rM   initnormal_rY   rZ   r   r   )r^   moduler   s      rJ   r   z$MixtralPreTrainedModel._init_weights  s{    %%dF3kk++fn-LL,,3C@LL))= 12LLSc: 3r`   N)r{   r|   r}   r   _can_compile_fullgraphr   r   r   r   _can_record_outputsr,   rh   r   r   r`   rJ   r   r     sD    !  ((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)rN   r   r   )r+   )rN   input_embedsr#   r   r   r   )r   )r#   r   r   r   r   r   )last_hidden_stater   )
ValueErrorr   rN   embed_tokensget_seq_lengthr,   aranger5   r+   r9   sliding_windowr
   r   
rotary_emblayersrF   normr   )r^   r   r#   r   r   r   r   r   r   past_seen_tokensmask_functioncausal_maskra   r   decoder_layers                  rJ   rz   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)r{   r|   r}   r,   r   r   r   FloatTensorboolr   r   r   rz   r   r`   rJ   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   )rP   rQ   r   modelrouter_aux_loss_coefrR   r"   r   r]   s     rJ   rQ   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   ra   r   r   r   )rN   r   r   r   r)   r   slicelm_headloss_function
vocab_sizerK   r   r"   r   r   r.   r+   r   r   ra   r   )r^   r   r#   r   r   r   r   r   r   r   r   r   outputsra   slice_indicesr   r   r   s                     rJ   rz   zMixtralForCausalLM.forwarde  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   )r{   r|   r}   _tied_weights_keysrQ   r,   r   r   r   r   r   r   r   r   r   rz   r   r   s   @rJ   r   r   [  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`   rJ   r   r     r   r`   r   c                       e Zd Zy)MixtralForTokenClassificationNr   r   r`   rJ   r   r     r   r`   r   c                       e Zd Zy)MixtralForQuestionAnsweringNr   r   r`   rJ   r   r     r   r`   r   )r   r   r   r   r   r   )Nr   N)Dr~   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   r   utils.genericr   mistral.modeling_mistralr   r   r   r   r   r   r   r   r   configuration_mixtralr    
get_loggerr{   loggerr   r*   r   rK   ModulerM   r   r   r   r   r   r   r   r   r   r   r   r   __all__r   r`   rJ   <module>r     s  &      & ! . 6 R 9 Q - & I I +
 
 
 1 
		H	%
 #
*.	O&ell 33d:O&tO& LL4'	O&
 \\CO&d $#RYY $# $#N<		 <$BII &	^ 		3 		' 	%4 %P;3 ;*;
< ;
|\
+ \
~	'G 		$A 		"= 	r`   