a
    h5J                     @   s  d Z ddlmZmZ ddlZddlm  mZ ddl	ZddlmZ ddl
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 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#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ e,e-Z.d/eej/e0ej/ df ee1 eej/ eej/e1f dddZ2G dd dej3Z4G dd dej3Z5G dd de(Z6G dd de!Z7G dd deZ8G d d! d!e)Z9G d"d# d#e'Z:G d$d% d%e&Z;G d&d' d'e"Z<G d(d) d)e$Z=G d*d+ d+e%Z>G d,d- d-e#Z?g d.Z@dS )0zPyTorch Mixtral model.    )OptionalUnionN)nn   )ACT2FN)CacheDynamicCache)create_causal_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)Unpack)TransformersKwargslogging)deprecate_kwarg)OutputRecorder   )	MistralAttentionMistralForCausalLMMistralForQuestionAnswering MistralForSequenceClassificationMistralForTokenClassificationMistralModelMistralPreTrainedModelMistralRMSNormMistralRotaryEmbedding   )MixtralConfig)gate_logitsnum_expertsattention_maskreturnc                    s  | du st | tsdS t | trF| 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 rtj
| dd}	tj
|dd}
n|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  )to).0Z
layer_gateZcompute_devicer#   g/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/mixtral/modular_mixtral.py
<listcomp>Y       z,load_balancing_loss_func.<locals>.<listcomp>dim)
isinstancetupledevicetorchcatr   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshaper$   sum	unsqueeze)r   r    top_kr!   Zconcatenated_gate_logitsrouting_weights_selected_expertsexpert_maskZtokens_per_expertZrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersZexpert_attention_maskZ router_per_expert_attention_maskZoverall_lossr#   r&   r'   load_balancing_loss_func7   sJ    



rE   c                       s*   e Zd Zed fddZdd Z  ZS )MixtralBlockSparseTop2MLPconfigc                    sl   t    |j| _|j| _tj| j| jdd| _tj| j| jdd| _	tj| j| jdd| _
t|j | _d S )NFZbias)super__init__intermediate_sizeffn_dimhidden_size
hidden_dimr   Linearw1w2w3r   Z
hidden_actact_fnselfrH   	__class__r#   r'   rK      s    
z"MixtralBlockSparseTop2MLP.__init__c                 C   s(   |  | || | }| |}|S N)rT   rQ   rS   rR   )rV   hidden_statescurrent_hidden_statesr#   r#   r'   forward   s    
z!MixtralBlockSparseTop2MLP.forward)__name__
__module____qualname__r   rK   r\   __classcell__r#   r#   rW   r'   rF      s   rF   c                       s4   e Zd ZdZ fddZejejdddZ  ZS )MixtralSparseMoeBlocka  
    This implementation is
    strictly equivalent to standard MoE with full capacity (no
    dropped tokens). It's faster since it formulates MoE operations
    in terms of block-sparse operations to accommodate imbalanced
    assignments of tokens to experts, whereas standard MoE either
    (1) drop tokens at the cost of reduced performance or (2) set
    capacity factor to number of experts and thus waste computation
    and memory on padding.
    c                    sl   t     j| _ j| _ j| _ j| _	t
j| j| jdd| _t
 fddt| jD | _ j| _d S )NFrI   c                    s   g | ]}t  qS r#   )rF   )r%   r?   rG   r#   r'   r(      r)   z2MixtralSparseMoeBlock.__init__.<locals>.<listcomp>)rJ   rK   rN   rO   rL   rM   num_local_expertsr    num_experts_per_tokr=   r   rP   gateZ
ModuleListrangeexpertsZrouter_jitter_noisejitter_noiserU   rW   rG   r'   rK      s    
 zMixtralSparseMoeBlock.__init__)rZ   r"   c                 C   sn  |j \}}}| jr>| jdkr>|t|d| j d| j 9 }|d|}| |}tj	|dtj
d}tj|| jdd\}}||jddd }||j}tj|| |f|j|jd	}tjjj|| jd
ddd}	t|	jddd }
|
D ]f}| j| }t|	| d\}}|d|f d|}|||||df  }|d|||j q||||}||fS ) r   g      ?r,   r   )r+   dtyper*   T)r+   Zkeepdim)ri   r/   )Znum_classesr   )r,   N)r8   Ztrainingrg   r0   Z
empty_likeZuniform_viewrd   Fr3   r7   r4   r=   r;   r$   ri   Zzerosr/   r   r2   r5   r    ZpermuteZgreaterZnonzerorf   whereZsqueezer:   Z
index_add_)rV   rZ   rB   rC   rO   router_logitsr>   r@   Zfinal_hidden_statesrA   Z
expert_hitZ
expert_idxZexpert_layeridxZtop_xZcurrent_stater[   r#   r#   r'   r\      s,    "

zMixtralSparseMoeBlock.forward)	r]   r^   r_   __doc__rK   r0   Tensorr\   r`   r#   r#   rW   r'   ra      s   ra   c                   @   s   e Zd ZdS )MixtralRMSNormNr]   r^   r_   r#   r#   r#   r'   rr      s   rr   c                   @   s   e Zd ZdS )MixtralAttentionNrs   r#   r#   r#   r'   rt      s   rt   c                       s   e Zd Zeed fddZedddddeje	ejejf e
ej e
ej e
e	ej  e
ej ee ejd	d
dZ  ZS )MixtralDecoderLayer)rH   	layer_idxc                    sP   t    |j| _t||| _t|| _t|j|jd| _	t|j|jd| _
d S )N)eps)rJ   rK   rN   rt   	self_attnra   block_sparse_moerr   Zrms_norm_epsinput_layernormpost_attention_layernorm)rV   rH   rv   rW   r#   r'   rK      s    

zMixtralDecoderLayer.__init__Zpast_key_valuepast_key_valuesz4.58)new_nameversionN)rZ   position_embeddingsr!   position_idsr|   cache_positionkwargsr"   c           
   	   K   s`   |}|  |}| jf ||||||d|\}}	|| }|}| |}| |\}}	|| }|S )N)rZ   r   r!   r   r|   r   )rz   rx   r{   ry   )
rV   rZ   r   r!   r   r|   r   r   Zresidualr?   r#   r#   r'   r\      s$    

	
zMixtralDecoderLayer.forward)NNNN)r]   r^   r_   r   intrK   r   r0   rq   r.   r   
LongTensorr   r   FloatTensorr\   r`   r#   r#   rW   r'   ru      s    
    ru   c                   @   s   e Zd ZdS )MixtralRotaryEmbeddingNrs   r#   r#   r#   r'   r     s   r   c                   @   s$   e Zd ZdZeeddeedZdS )MixtralPreTrainedModelFr   )index)rn   rZ   
attentionsN)	r]   r^   r_   Z_can_compile_fullgraphr   ra   ru   rt   Z_can_record_outputsr#   r#   r#   r'   r     s
   
r   c                   @   sV   e Zd Zdeej eej eej ee eej ee	 eej e
e ed	ddZdS )MixtralModelN)		input_idsr!   r   r|   inputs_embeds	use_cacher   r   r"   c              
   K   s  |d u |d uA rt d|r0|d u r0t| jd}|d u rB| |}|d u rz|d urZ| nd}	tj|	|	|jd  |jd}|d u r|	d}| jj
d u rtnt}
|
| j|||||d}|}| ||}| jd | jj D ]"}||f||||||d|}q| |}t||dS )	Nz:You must specify exactly one of input_ids or inputs_embedsrG   r   r   )r/   )rH   Zinput_embedsr!   r   r|   r   )r   r!   r   r|   r   r   )last_hidden_stater|   )
ValueErrorr   rH   Zembed_tokensZget_seq_lengthr0   Zaranger8   r/   r<   Zsliding_windowr	   r
   Z
rotary_embZlayersrD   Znormr   )rV   r   r!   r   r|   r   r   r   r   Zpast_seen_tokensZmask_functionZcausal_maskrZ   r   Zdecoder_layerr#   r#   r'   r\   #  sT    

	
zMixtralModel.forward)NNNNNNN)r]   r^   r_   r   r0   r   rq   r   r   boolr   r   r   r\   r#   r#   r#   r'   r   "  s$          r   c                       s   e Zd ZdgZ fddZd	eej eej eej ee	 eej
 eej ee ee eej eeejf ee edddZ  ZS )
MixtralForCausalLMzlm_head.weightc                    s2   t  | t|| _|j| _|j| _|j| _d S rY   )rJ   rK   r   modelrouter_aux_loss_coefrb   r    rc   rU   rW   r#   r'   rK   e  s
    
zMixtralForCausalLM.__init__Nr   )r   r!   r   r|   r   labelsr   output_router_logitsr   logits_to_keepr   r"   c                 K   s   |dur|n| j j}| jf ||||||||	d|}|j}t|
trRt|
 dn|
}| |dd|ddf }d}|dur| j||| j	fi |}d}|rt
|j| j| j|}|dur|| 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   r   r   )lossaux_losslogitsr|   rZ   r   rn   )rH   r   r   r   r-   r   sliceZlm_headZloss_functionZ
vocab_sizerE   rn   r    rc   r   r$   r/   r   r|   rZ   r   )rV   r   r!   r   r|   r   r   r   r   r   r   r   outputsrZ   Zslice_indicesr   r   r   r#   r#   r'   r\   l  sN    &	zMixtralForCausalLM.forward)
NNNNNNNNNr   )r]   r^   r_   Z_tied_weights_keysrK   r   r0   r   rq   r   r   r   r   r   r   r   r   r\   r`   r#   r#   rW   r'   r   b  s4   	          r   c                   @   s   e Zd ZdS ) MixtralForSequenceClassificationNrs   r#   r#   r#   r'   r     s   r   c                   @   s   e Zd ZdS )MixtralForTokenClassificationNrs   r#   r#   r#   r'   r     s   r   c                   @   s   e Zd ZdS )MixtralForQuestionAnsweringNrs   r#   r#   r#   r'   r     s   r   )r   r   r   r   r   r   )Nr   N)Arp   typingr   r   r0   Ztorch.nn.functionalr   r2   rl   Ztorch.utils.checkpointZactivationsr   Zcache_utilsr   r   Zmasking_utilsr	   r
   Zmodeling_layersr   Zmodeling_outputsr   r   Zprocessing_utilsr   utilsr   r   Zutils.deprecationr   Zutils.genericr   Zmistral.modeling_mistralr   r   r   r   r   r   r   r   r   Zconfiguration_mixtralr   Z
get_loggerr]   loggerrq   r.   r   rE   ModulerF   ra   rr   rt   ru   r   r   r   r   r   r   r   __all__r#   r#   r#   r'   <module>   sN   ,
   RC/	@_