a
    hVv                  
   @   s  d dl mZmZ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 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+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 G dd dej3Z4G dd dej3Z5edG dd dej3Z6dd Z7d?dd Z8ej9e:ej9d!d"d#Z;d@ej3ej9ej9ej9eej9 e<e<e(e* d%d&d'Z=G d(d) d)ej3Z>G d*d+ d+eZ?G d,d- d-ej3Z@e+G d.d/ d/e&ZAe+G d0d1 d1eAZBdAeej9eCej9 df ee: eej9 eej9e:f d3d4d5ZDe+G d6d7 d7eAeZEG d8d9 d9eeAZFG d:d; d;eeAZGG d<d= d=eeAZHg d>ZIdS )B    )CallableOptionalUnionN)nn)check_model_inputs   )ACT2FN)CacheDynamicCache)GenerationMixin)use_kernel_forward_from_hub)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)deprecate_kwarg)OutputRecorder   )MixtralConfigc                       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selfr$   	__class__ h/var/www/html/assistant/venv/lib/python3.9/site-packages/transformers/models/mixtral/modeling_mixtral.pyr(   :   s    
z"MixtralBlockSparseTop2MLP.__init__c                 C   s(   |  | || | }| |}|S )N)r1   r.   r0   r/   )r3   hidden_statescurrent_hidden_statesr6   r6   r7   forwardE   s    
z!MixtralBlockSparseTop2MLP.forward)__name__
__module____qualname__r!   r(   r:   __classcell__r6   r6   r4   r7   r"   9   s   r"   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 )NFr&   c                    s   g | ]}t  qS r6   )r"   ).0_r#   r6   r7   
<listcomp>a       z2MixtralSparseMoeBlock.__init__.<locals>.<listcomp>)r'   r(   r+   r,   r)   r*   num_local_expertsnum_expertsnum_experts_per_toktop_kr   r-   gate
ModuleListrangeexpertsZrouter_jitter_noisejitter_noiser2   r4   r#   r7   r(   W   s    
 zMixtralSparseMoeBlock.__init__)r8   returnc                 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    dimdtyperQ   T)rQ   keepdim)rR   device)Znum_classes   )rO   N)shapetrainingrL   torchZ
empty_likeZuniform_viewrH   FsoftmaxfloattopkrG   sumtorR   ZzerosrU   r   
functionalone_hotrE   ZpermuteZgreaterZnonzerorK   whereZsqueezereshapeZ
index_add_)r3   r8   
batch_sizesequence_lengthr,   router_logitsrouting_weightsselected_expertsZfinal_hidden_statesexpert_maskZ
expert_hitZ
expert_idxZexpert_layeridxZtop_xZcurrent_stater9   r6   r6   r7   r:   f   s,    "

zMixtralSparseMoeBlock.forward)	r;   r<   r=   __doc__r(   rZ   Tensorr:   r>   r6   r6   r4   r7   r?   K   s   r?   ZRMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	MixtralRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        MixtralRMSNorm is equivalent to T5LayerNorm
        N)r'   r(   r   	ParameterrZ   Zonesweightvariance_epsilon)r3   r+   epsr4   r6   r7   r(      s    
zMixtralRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )NrV   rO   T)rT   )	rR   ra   rZ   float32powmeanZrsqrtrs   rr   )r3   r8   Zinput_dtypeZvariancer6   r6   r7   r:      s
    zMixtralRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tuplerr   rX   rs   )r3   r6   r6   r7   
extra_repr   s    zMixtralRMSNorm.extra_repr)rp   )r;   r<   r=   r(   r:   ry   r>   r6   r6   r4   r7   ro      s   ro   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..NrO   rV   rS   )rX   rZ   cat)xx1Zx2r6   r6   r7   rotate_half   s    r}   c                 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.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        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kcossinposition_idsZunsqueeze_dimZq_embedZk_embedr6   r6   r7   apply_rotary_pos_emb   s
    

r   )r8   n_reprM   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)rX   expandre   )r8   r   batchnum_key_value_headsslenhead_dimr6   r6   r7   	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rf|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )NrV   r   rW   rO   rP   )prY   r    )r   num_key_value_groupsrZ   matmul	transposerX   r   rb   r]   ru   ra   rR   r   rY   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightscausal_maskattn_outputr6   r6   r7   eager_attention_forward   s    
&r   c                       s   e Zd 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 eej ee e
ej	eej	 f d
ddZ  ZS )MixtralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr$   	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      TFr&   )r'   r(   r$   r   getattrr+   Znum_attention_headsr   r   r   r   attention_dropoutZ	is_causalr   r-   q_projk_projv_projo_projr3   r$   r   r4   r6   r7   r(      s    
zMixtralAttention.__init__past_key_valuepast_key_values4.58new_nameversionN)r8   position_embeddingsr   r   cache_positionr   rM   c                 K   s0  |j d d }g |d| jR }| ||dd}	| ||dd}
| ||dd}|\}}t|	|
||\}	}
|d ur|||d}||
|| j	|\}
}t
}| jjdkrt| jj }|| |	|
||f| jsdn| j| jt| jdd d|\}}|jg |dR   }| |}||fS )	NrO   r    rV   )r   r   r   eagerr   sliding_window)r   r   r   )rX   r   r   r[   r   r   r   r   updater   r   r$   Z_attn_implementationr   rY   r   r   r   re   r   r   )r3   r8   r   r   r   r   r   Zinput_shapeZhidden_shapeZquery_statesr   r   r   r   Zcache_kwargsZattention_interfacer   r   r6   r6   r7   r:      s:    
	

zMixtralAttention.forward)NN)r;   r<   r=   rm   r!   intr(   r   rZ   rn   rx   r   r	   
LongTensorr   r   r:   r>   r6   r6   r4   r7   r      s     r   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 )MixtralDecoderLayerr   c                    sP   t    |j| _t||| _t|| _t|j|jd| _	t|j|jd| _
d S )Nrt   )r'   r(   r+   r   	self_attnr?   block_sparse_moero   rms_norm_epsinput_layernormpost_attention_layernormr   r4   r6   r7   r(   +  s    

zMixtralDecoderLayer.__init__r   r   r   r   N)r8   r   r   r   r   r   r   rM   c           
   	   K   s`   |}|  |}| jf ||||||d|\}}	|| }|}| |}| |\}}	|| }|S )N)r8   r   r   r   r   r   )r   r   r   r   )
r3   r8   r   r   r   r   r   r   ZresidualrA   r6   r6   r7   r:   5  s$    

	
zMixtralDecoderLayer.forward)NNNN)r;   r<   r=   r!   r   r(   r   rZ   rn   rx   r   r   r   r   FloatTensorr:   r>   r6   r6   r4   r7   r   *  s    
    r   c                       sD   e Zd ZU ejed< ded fddZe e	dd Z
  ZS )	MixtralRotaryEmbeddinginv_freqNr#   c                    s   t    t|dr:t|jtr:|jd|jd| _nd| _|j| _	|j| _
|| _t| j | _| | j|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultr   F)
persistent)r'   r(   hasattr
isinstancer   dictgetr   Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenr$   r   Zrope_init_fnattention_scalingZregister_bufferr   Zoriginal_inv_freq)r3   r$   rU   r   r4   r6   r7   r(   \  s    
zMixtralRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtrl|jjdkrl|jjnd}t	j
|ddV | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 s0    Y  |j|jd
|	j|jd
fS )Nr   rO   r    ZmpscpuF)device_typeZenabledrV   rS   )rR   )r   r^   r   rX   ra   rU   r   r   strrZ   Zautocastr   rz   r   r   r   rR   )
r3   r{   r   Zinv_freq_expandedZposition_ids_expandedr   ZfreqsZembr   r   r6   r6   r7   r:   m  s    0&,zMixtralRotaryEmbedding.forward)N)r;   r<   r=   rZ   rn   __annotations__r!   r(   Zno_gradr   r:   r>   r6   r6   r4   r7   r   Y  s
   

r   c                   @   sR   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deed	Zd
S )MixtralPreTrainedModelr$   modelTr   r   Fr    )index)rh   r8   
attentionsN)r;   r<   r=   r!   r   Zbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attnZ_supports_sdpaZ_supports_flex_attnZ_can_compile_fullgraphZ_supports_attention_backendr   r?   r   r   Z_can_record_outputsr6   r6   r6   r7   r   }  s   

r   c                       st   e Zd Zed fddZee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  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 r6   )r   )r@   r   r#   r6   r7   rB     rC   z)MixtralModel.__init__.<locals>.<listcomp>r   r#   F)r'   r(   Zpad_token_idZpadding_idx
vocab_sizer   Z	Embeddingr+   embed_tokensrI   rJ   num_hidden_layerslayersro   r   normr   
rotary_embZgradient_checkpointing	post_initr2   r4   r#   r7   r(     s    zMixtralModel.__init__N)		input_idsr   r   r   inputs_embeds	use_cacher   r   rM   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_embedsr#   r   r    )rU   )r$   Zinput_embedsr   r   r   r   )r   r   r   r   r   r   )last_hidden_stater   )
ValueErrorr
   r$   r   Zget_seq_lengthrZ   ZarangerX   rU   r~   r   r   r   r   r   r   r   r   )r3   r   r   r   r   r   r   r   r   Zpast_seen_tokensZmask_functionr   r8   r   Zdecoder_layerr6   r6   r7   r:     sT    

	
zMixtralModel.forward)NNNNNNN)r;   r<   r=   r!   r(   r   r   r   rZ   r   rn   r	   r   boolr   r   r   r:   r>   r6   r6   r4   r7   r     s*          r   rV   )gate_logitsrE   r   rM   c                    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 r6   )ra   )r@   Z
layer_gateZcompute_devicer6   r7   rB     rC   z,load_balancing_loss_func.<locals>.<listcomp>rS   rO   )r   rx   rU   rZ   rz   r   rb   r]   r_   rc   rw   r^   rX   r   re   ra   r`   r~   )r   rE   rG   r   Zconcatenated_gate_logitsri   rA   rj   rk   Ztokens_per_expertZrouter_prob_per_expertrf   rg   r   Zexpert_attention_maskZ router_per_expert_attention_maskZoverall_lossr6   r   r7   load_balancing_loss_func  sJ    



r   c                       s   e Zd ZdgZddiZddgdgfiZ fddZee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.weightlm_headZcolwise_repr8   logitsc                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _|j| _|   d S r%   )r'   r(   r   r   r   r   r-   r+   r   router_aux_loss_coefrD   rE   rF   r   r2   r4   r6   r7   r(   ;  s    
zMixtralForCausalLM.__init__Nr   )r   r   r   r   r   labelsr   output_router_logitsr   logits_to_keepr   rM   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_lossr   r   r8   r   rh   )r$   r   r   r   r   r   slicer   Zloss_functionr   r   rh   rE   rF   r   ra   rU   r   r   r8   r   )r3   r   r   r   r   r   r   r   r   r   r   r   outputsr8   Zslice_indicesr   r   r   r6   r6   r7   r:   G  sN    (	zMixtralForCausalLM.forward)
NNNNNNNNNr   )r;   r<   r=   Z_tied_weights_keysZ_tp_planZ_pp_planr(   r   r   r   rZ   r   rn   r	   r   r   r   r   r   r   r   r:   r>   r6   r6   r4   r7   r   5  s<             r   c                   @   s   e Zd ZdS ) MixtralForSequenceClassificationNr;   r<   r=   r6   r6   r6   r7   r     s   r   c                   @   s   e Zd ZdS )MixtralForTokenClassificationNr   r6   r6   r6   r7   r     s   r   c                   @   s   e Zd ZdS )MixtralForQuestionAnsweringNr   r6   r6   r6   r7   r     s   r   )r   r   r   r   r   r   )Nr    )r   )NrV   N)Jtypingr   r   r   rZ   Ztorch.nn.functionalr   rb   r\   Ztransformers.utils.genericr   Zactivationsr   Zcache_utilsr	   r
   Z
generationr   Zintegrationsr   Zmasking_utilsr   r   Zmodeling_flash_attention_utilsr   Zmodeling_layersr   r   r   r   Zmodeling_outputsr   r   Zmodeling_rope_utilsr   r   Zmodeling_utilsr   r   Zprocessing_utilsr   utilsr   r   r   Zutils.deprecationr   Zutils.genericr   Zconfiguration_mixtralr!   Moduler"   r?   ro   r}   r   rn   r   r   r^   r   r   r   r   r   r   rx   r   r   r   r   r   __all__r6   r6   r6   r7   <module>   sv   C
 ?/$T   Rh