o
    eiz                     @   s  d dl mZ d dlmZ d dlZd dlm  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/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6m7Z7 ddl8m9Z9 eG dd dej:Z;G dd dej:Z<G dd dej:Z=edG dd dej:Z>G d d! d!ej:Z?d"d# Z@ed$dMd%d&ZAd'ejBd(eCd)ejBfd*d+ZD	,dNd-ej:d.ejBd/ejBd0ejBd1ejBdB d2eEd3eEd4e,e. fd5d6ZFeeAG d7d8 d8ej:ZGG d9d: d:e!ZHe/G d;d< d<e*ZIe/G d=d> d>eIZJ		?	dOd@ejBeKejB B dB dAeCdB d1ejBdB d)ejBeCB fdBdCZLe/G dDdE dEeIeZMG dFdG dGeeIZNG dHdI dIe eIZOG dJdK dKeeIZPg dLZQdS )P    )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is_grouped_mm_available)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )MixtralConfigc                       sH   e Zd ZdZdef fddZdejdejdejdejfd	d
Z  Z	S )MixtralExpertsz2Collection of expert weights stored as 3D tensors.configc                    sn   t    |j| _|j| _|j| _t	t
| jd| j | j| _t	t
| j| j| j| _t|j | _d S )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__ j/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/mixtral/modeling_mixtral.pyr+   A   s   
 zMixtralExperts.__init__hidden_statestop_k_indextop_k_weightsreturnc                 C   s  t |}t  % t jjj|| jd}|ddd}t |j	ddd
 }W d    n1 s1w   Y  |D ]O}|d }|| jkrDq8t || \}}	||	 }
tj|
| j| jddd\}}| || }tj|| j| }|||	|d f  }|d|	||j q8|S )N)num_classesr)   r%   r   )dimrD   )r3   
zeros_likeno_gradr   
functionalone_hotr-   permutegreatersumnonzerowherelinearr5   chunkr8   r6   
index_add_todtype)r:   r?   r@   rA   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stategateupcurrent_hidden_statesr=   r=   r>   forwardJ   s$   


"zMixtralExperts.forward)
__name__
__module____qualname____doc__r&   r+   r3   Tensorr`   __classcell__r=   r=   r;   r>   r'   =   s    	r'   c                       s$   e Zd Z fddZdd Z  ZS )MixtralTopKRouterc                    s>   t    |j| _|j| _|j| _t	t
| j| j| _d S N)r*   r+   num_experts_per_toktop_kr,   r-   r.   r/   r   r2   r3   r4   weightr9   r;   r=   r>   r+   f   s
   
zMixtralTopKRouter.__init__c                 C   sh   | d| j}t|| j}tjjj|	 dd}tj
|| jdd\}}||jddd }|}|||fS )NrD   rF   T)rG   keepdim)reshaper/   FrQ   rk   r3   r   rJ   softmaxfloattopkrj   rN   )r:   r?   router_logitsrouter_top_valuerouter_indicesrouter_scoresr=   r=   r>   r`   m   s   
zMixtralTopKRouter.forward)ra   rb   rc   r+   r`   rf   r=   r=   r;   r>   rg   e   s    rg   c                       s<   e Zd Z fddZdejdeejejf fddZ  ZS )MixtralSparseMoeBlockc                    s2   t    |j| _|j| _t|| _t|| _	d S rh   )
r*   r+   ri   rj   router_jitter_noisejitter_noiserg   r]   r'   expertsr9   r;   r=   r>   r+   x   s
   

zMixtralSparseMoeBlock.__init__r?   rB   c                 C   s   |j \}}}| jr| jdkr|t|d| j d| j 9 }|d|j d }| |\}}}| |||}|	|||}|S )Nr         ?rD   )
shapetrainingrx   r3   
empty_likeuniform_viewr]   ry   rm   )r:   r?   
batch_sizesequence_lengthr/   _rA   r@   r=   r=   r>   r`      s   "zMixtralSparseMoeBlock.forward)	ra   rb   rc   r+   r3   re   tupler`   rf   r=   r=   r;   r>   rv   w   s    (rv   RMSNormc                       sF   e Zd Zddeddf fddZdejdejfdd	Zd
d Z  Z	S )MixtralRMSNormư>epsrB   Nc                    s&   t    tt|| _|| _dS )z=
        MixtralRMSNorm is equivalent to T5LayerNorm
        N)r*   r+   r   r2   r3   onesrk   variance_epsilon)r:   r.   r   r;   r=   r>   r+      s   

zMixtralRMSNorm.__init__r?   c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr)   rD   T)rl   )	rU   rT   r3   float32powmeanrsqrtr   rk   )r:   r?   input_dtypevariancer=   r=   r>   r`      s
   zMixtralRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r   rk   r{   r   )r:   r=   r=   r>   
extra_repr   s   zMixtralRMSNorm.extra_repr)r   )
ra   rb   rc   rp   r+   r3   re   r`   r   rf   r=   r=   r;   r>   r      s    r   c                       s~   e Zd ZU ejed< ddef fddZe			ddedB de	d de
dB d	ed
ef fddZe edd Z  ZS )MixtralRotaryEmbeddinginv_freqNr(   c                    s   t    |j| _|j| _|| _| jjd | _| j}| jdkr$t	| j }|| j|\}| _
| jd|dd | jd| dd d S )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;   r=   r>   r+      s   


zMixtralRotaryEmbedding.__init__r   ztorch.deviceseq_lenrB   ztorch.Tensorc                 C   sZ   | j d }t| ddp| j| j }d}d|tjd|dtjdj|tjd|   }||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_dimNrz   r   r)   rU   )r   rU   )	r   getattrr.   num_attention_headsr3   arangeint64rT   rp   )r(   r   r   baserG   attention_factorr   r=   r=   r>   r      s   
&z6MixtralRotaryEmbedding.compute_default_rope_parametersc           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	|dd+ | |  
dd}tj||fdd	}| | j }| | j }	W d    n1 slw   Y  |j|jd
|	j|jd
fS )Nr   rD   r%   mpscpuF)device_typeenabledr)   rF   r   )r   rp   expandr{   rT   r   
isinstancetypestrr!   	transposer3   catcosr   sinrU   )
r:   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   r=   r=   r>   r`      s   0&zMixtralRotaryEmbedding.forwardrh   )NNN)ra   rb   rc   r3   re   __annotations__r&   r+   staticmethodr   intr   rp   r   rI   r   r`   rf   r=   r=   r;   r>   r      s&   
 

r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..NrD   r)   rF   )r{   r3   r   )r   x1x2r=   r=   r>   rotate_half   s   r   rotary_pos_embc                 C   sD   | |}| |}| | t| |  }|| t||  }||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_embedr=   r=   r>   apply_rotary_pos_emb   s
   

r   r?   n_reprB   c                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||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   rm   )r?   r   batchnum_key_value_headsslenr   r=   r=   r>   	repeat_kv  s
   0r           modulequerykeyvalueattention_maskscalingdropoutkwargsc                 K   s   t || j}t || j}	t||dd| }
|d ur |
| }
tjj|
dtjd	|j
}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr)   r   rD   )rG   rU   )pr|   r%   )r   num_key_value_groupsr3   matmulr   r   rJ   ro   r   rT   rU   r   r|   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputr=   r=   r>   eager_attention_forward  s   
r   c                       s   e Zd ZdZdedef fddZ		ddejde	ejejf d	ejdB d
e
dB dejdB dee de	ejejdB f fddZ  ZS )MixtralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr(   	layer_idxc                    s   t    || _|| _t|dd p|j|j | _|j|j | _	| jd | _
|j| _d| _tj|j|j| j dd| _tj|j|j| j dd| _tj|j|j| j dd| _tj|j| j |jdd| _d S )Nr   g      TFbias)r*   r+   r(   r   r   r.   r   r   r   r   r   attention_dropout	is_causalr   Linearq_projk_projv_projo_projr:   r(   r   r;   r=   r>   r+   *  s   
 zMixtralAttention.__init__Nr?   position_embeddingsr   past_key_valuescache_positionr   rB   c                 K   s$  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d urW|||d}||
|| j	|\}
}t
| jjt}|| |	|
||f| jskdn| j| jt| jdd d|\}}|jg |dR   }| |}||fS )NrD   r%   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   rm   r   r   )r:   r?   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   r=   r=   r>   r`   8  s:   		

zMixtralAttention.forward)NN)ra   rb   rc   rd   r&   r   r+   r3   re   r   r   
LongTensorr   r   r`   rf   r=   r=   r;   r>   r   &  s(    r   c                       s   e Zd Zdedef fddZ					ddejdeejejf dB dejdB d	ej	dB d
e
dB dej	dB dee dejfddZ  ZS )MixtralDecoderLayerr(   r   c                    sP   t    |j| _t||| _t|| _t|j|jd| _	t|j|jd| _
d S )Nr   )r*   r+   r.   r   	self_attnrv   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr   r;   r=   r>   r+   f  s   

zMixtralDecoderLayer.__init__Nr?   r   r   r   r   r   r   rB   c           
   	   K   s\   |}|  |}| jd||||||d|\}}	|| }|}| |}| |}|| }|S )N)r?   r   r   r   r   r   r=   )r   r   r  r   )
r:   r?   r   r   r   r   r   r   residualr   r=   r=   r>   r`   p  s$   


	

zMixtralDecoderLayer.forward)NNNNN)ra   rb   rc   r&   r   r+   r3   re   r   r   r   r   r   r`   rf   r=   r=   r;   r>   r   e  s0    	r   c                       sl   e Zd ZU eed< dZdZdgZdgZdZ	dZ
dZe ZdZeeddeedZe  fd	d
Z  ZS )MixtralPreTrainedModelr(   modelTr   r   r   )index)rr   r?   
attentionsc                    sj   t  | | jj}t|tr#tj|jd|d tj|j	d|d d S t|t
r3tj|jd|d d S d S )Nr   )r   std)r*   _init_weightsr(   initializer_ranger   r'   initnormal_r5   r6   rg   rk   )r:   r   r  r;   r=   r>   r    s   

z$MixtralPreTrainedModel._init_weights)ra   rb   rc   r&   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attnr    _can_compile_fullgraph_supports_attention_backendr#   rg   r   r   _can_record_outputsr3   rI   r  rf   r=   r=   r;   r>   r    s$   
 
r  c                       s   e Zd Zdef fddZeee							ddej	dB dej
dB dej	dB dedB d	ejdB d
edB dej	dB dee defddZ  ZS )MixtralModelr(   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _t d| _d| _|   d S )Nc                    s   g | ]}t  |qS r=   )r   ).0r   r(   r=   r>   
<listcomp>      z)MixtralModel.__init__.<locals>.<listcomp>r   r  F)r*   r+   pad_token_idpadding_idx
vocab_sizer   	Embeddingr.   embed_tokens
ModuleListrangenum_hidden_layerslayersr   r   normr   
rotary_embgradient_checkpointing	post_initr9   r;   r  r>   r+     s   zMixtralModel.__init__N	input_idsr   r   r   inputs_embeds	use_cacher   r   rB   c              
   K   s  |d u |d uA rt d|r|d u rt| jd}|d u r!| |}|d u r=|d ur-| nd}	tj|	|	|jd  |jd}|d u rF|	d}| jj
d u rNtnt}
|
| j|||||d}|}| j||d}| jd | jj D ]}||f||||||d|}qm| |}t||d	S )
Nz:You must specify exactly one of input_ids or inputs_embedsr  r   r%   )r   )r(   r)  r   r   r   r   )r   )r   r   r   r*  r   r   )last_hidden_stater   )
ValueErrorr	   r(   r  get_seq_lengthr3   r   r{   r   r   r   r   r   r%  r#  r"  r$  r   )r:   r(  r   r   r   r)  r*  r   r   past_seen_tokensmask_functioncausal_maskr?   r   decoder_layerr=   r=   r>   r`     sT   

	
zMixtralModel.forward)NNNNNNN)ra   rb   rc   r&   r+   r"   r$   r   r3   r   re   r   FloatTensorboolr   r   r   r`   rf   r=   r=   r;   r>   r    s>    	
r  r)   gate_logitsr-   c                    s  | du s	t | tsdS t | tr#| d j tj fdd| D dd}tjjj|dd}tj||dd\}}tjj	||}|du rStj
| dd}	tj
|dd}
ng|j\}}|jd ||  }|dddddddf |||||fd|| }tj| | ddtj|dd }	|ddddddf ||||fd| }tj|| ddtj|dd }
t|	|
d }|| S )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   c                    s   g | ]}|  qS r=   )rT   )r  
layer_gatecompute_devicer=   r>   r     r  z,load_balancing_loss_func.<locals>.<listcomp>rF   rD   )r   r   r   r3   r   r   rJ   ro   rq   rK   r   rp   r{   r   rm   rT   rN   r   )r4  r-   rj   r   concatenated_gate_logitsrouting_weightsr   selected_expertsrW   tokens_per_expertrouter_prob_per_expertr   r   r"  expert_attention_mask router_per_expert_attention_maskoverall_lossr=   r6  r>   load_balancing_loss_func  s>   



r@  c                       s   e Zd ZddiZddiZddgdgfiZ fddZee																			
dde	j
d	B de	jd	B de	j
d	B ded	B de	jd	B de	j
d	B ded	B ded	B de	j
d	B dee	jB dee defddZ  ZS )MixtralForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr?   logitsc                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _|j| _|   d S )NFr   )r*   r+   r  r  r  r   r   r.   rB  router_aux_loss_coefr,   r-   ri   r'  r9   r;   r=   r>   r+   V  s   
zMixtralForCausalLM.__init__Nr   r(  r   r   r   r)  labelsr*  output_router_logitsr   logits_to_keepr   rB   c                 K   s   |dur|n| j j}| jd||||||||	d|}|j}t|
tr)t|
 dn|
}| |dd|ddf }d}|durK| j||| j	fi |}d}|rht
|j| j| j|}|durh|| j||j 7 }t||||j|j|j|jd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*  rG  r   )lossaux_lossrD  r   r?   r  rr   r=   )r(   rG  r  r+  r   r   slicerB  loss_functionr  r@  rr   r-   ri   rE  rT   r   r   r   r?   r  )r:   r(  r   r   r   r)  rF  r*  rG  r   rH  r   outputsr?   slice_indicesrD  rI  rJ  r=   r=   r>   r`   b  sN   (	zMixtralForCausalLM.forward)
NNNNNNNNNr   )ra   rb   rc   _tied_weights_keys_tp_plan_pp_planr+   r   r   r3   r   re   r   r2  r3  r   r   r   r   r`   rf   r=   r=   r;   r>   rA  P  sT    	
rA  c                   @      e Zd ZdS ) MixtralForSequenceClassificationNra   rb   rc   r=   r=   r=   r>   rS        rS  c                   @   rR  )MixtralForTokenClassificationNrT  r=   r=   r=   r>   rV    rU  rV  c                   @   rR  )MixtralForQuestionAnsweringNrT  r=   r=   r=   r>   rW    rU  rW  )rA  rW  r  r  rS  rV  )r%   )r   )Nr)   N)Rcollections.abcr   typingr   r3   torch.nn.functionalr   rJ   rn    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   r    utils.genericr!   r"   utils.output_capturingr#   r$   configuration_mixtralr&   Moduler'   rg   rv   r   r   r   r   re   r   r   rp   r   r   r   r  r  r   r@  rA  rS  rV  rW  __all__r=   r=   r=   r>   <module>   s   'A
>(S
Rh