o
    h                     @   s  d Z ddlZddlZddlZddlmZmZ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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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( ddl)m*Z* ddl+m,Z, e% rddl-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3 de4e5e.j6v Z7e* re!sddl8Z	e	j9:eZe';e<Z=dZ>d@de	j?de	j?de@fddZAdd ZBG dd dejCZDG dd  d ejCZEd!d" ZFdAd#d$ZGd%e	j?d&eHde	j?fd'd(ZIG d)d* d*ejCZJG d+d, d,eJZKG d-d. d.ejCZLeJeKd/ZMG d0d1 d1ejCZNG d2d3 d3ejCZOd4ZPe#d5ePG d6d7 d7eZQd8ZRe#d5ePG d9d: d:eQZSG d;d< d<eQZTe#d=ePG d>d? d?eQZUdS )Bz PyTorch Mixtral model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)!_prepare_4d_causal_attention_mask)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)#is_torch_greater_or_equal_than_1_13)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings)is_torch_fx_available   )MixtralConfig)flash_attn_funcflash_attn_varlen_func)index_first_axis	pad_inputunpad_inputwindow_sizer      gate_logitsnum_expertsreturnc                 C   s   | du rdS t | trtj| dd} tj| |dd\}}|jdd}|jtjkr.|tj}t	|j
dkr:|d}tjj||}tj|ddj}|tj}tj|dd}tj|dd}t||d |d  S )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    See Switch Transformer (https://arxiv.org/abs/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 (Union[`torch.Tensor`, Tuple[torch.Tensor]):
            Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_experts].
        num_experts (`int`, *optional*):
            Number of experts

    Returns:
        The auxiliary loss.
    Nr   dimr#   )axis)
isinstancetupletorchcattopksoftmaxdtypeint64tolenshape	unsqueezer   
functionalone_hotmaxvaluesfloat32mean)r$   r%   top_krouting_weightsselected_expertsexpert_masktokens_per_group_and_expert router_prob_per_group_and_expert rD   b/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/mixtral/modeling_mixtral.pyload_balancing_loss_funcL   s    

rF   c                 C   sX   | j dtjd}tj|  dd }|  }ttj	|dtjjdd}|||fS )Nr)   r(   r2   F)as_tupler   )r   r   )
sumr.   int32nonzeroflattenr:   itemFpadcumsum)attention_maskseqlens_in_batchindicesmax_seqlen_in_batch
cu_seqlensrD   rD   rE   _get_unpad_data|   s   rV   c                       s&   e Zd Zd fdd	Zdd Z  ZS )MixtralRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        MixtralRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr.   onesweightvariance_epsilon)selfhidden_sizeeps	__class__rD   rE   rZ      s   

zMixtralRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr#   r)   T)keepdim)	r2   r4   r.   r<   powr=   rsqrtr^   r]   )r_   hidden_statesinput_dtypevariancerD   rD   rE   forward   s
   zMixtralRMSNorm.forward)rX   )__name__
__module____qualname__rZ   rj   __classcell__rD   rD   rb   rE   rW      s    rW   c                       s0   e Zd Zd
 fdd	Zdd Zddd	Z  ZS )MixtralRotaryEmbedding   '  Nc                    sr   t    || _|| _|| _d| jtd| jd || j   }| j	d|dd | j
|| jjt d d S )Ng      ?r   r#   inv_freqF
persistentseq_lendevicer2   )rY   rZ   r(   max_position_embeddingsbaser.   arangefloatr4   register_buffer_set_cos_sin_cacherr   rw   get_default_dtype)r_   r(   rx   ry   rw   rr   rb   rD   rE   rZ      s   
*
zMixtralRotaryEmbedding.__init__c                 C   st   || _ tj| j || jjd}t|| j}tj||fdd}| jd| 	|dd | jd|
 	|dd d S )N)rw   r2   r)   r'   
cos_cachedFrs   
sin_cached)max_seq_len_cachedr.   rz   rr   r2   outerr/   r|   cosr4   sin)r_   rv   rw   r2   tfreqsembrD   rD   rE   r}      s   z)MixtralRotaryEmbedding._set_cos_sin_cachec                 C   sN   || j kr| j||j|jd | jd | j|jd| jd | j|jdfS )Nru   )r2   )r   r}   rw   r2   r   r4   r   )r_   xrv   rD   rD   rE   rj      s
   
zMixtralRotaryEmbedding.forward)rp   rq   NN)rk   rl   rm   rZ   r}   rj   rn   rD   rD   rb   rE   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..Nr)   r#   r'   )r6   r.   r/   )r   x1x2rD   rD   rE   rotate_half   s   r   c                 C   sL   ||  |}||  |}| | t| |  }|| t||  }||fS )an  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`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        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.
    )r7   r   )qkr   r   position_idsunsqueeze_dimq_embedk_embedrD   rD   rE   apply_rotary_pos_emb   s
   r   rg   n_repc                 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)r6   expandreshape)rg   r   batchnum_key_value_headsslenhead_dimrD   rD   rE   	repeat_kv   s
   0r   c                       s   e Zd ZdZddedee f fddZdej	ded	efd
dZ
					ddej	deej	 deej dee dededeej	eej	 eeej	  f fddZ  ZS )MixtralAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".
    Nconfig	layer_idxc                    s<  t    || _|| _|d u rtd| jj d |j| _|j	| _
| j| j
 | _|j| _| j
| j | _|j| _|j| _d| _|j| _| j| j
 | jkrYtd| 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| _t| j| j| jd	| _d S )
NzInstantiating z without passing `layer_idx` is not recommended and will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fbias)rx   ry   )rY   rZ   r   r   loggerwarning_oncerc   rk   r`   num_attention_heads	num_headsr   r   num_key_value_groupsrx   
rope_theta	is_causalattention_dropout
ValueErrorr   Linearq_projk_projv_projo_projro   
rotary_embr_   r   r   rb   rD   rE   rZ      s>   

zMixtralAttention.__init__tensorrv   bszc                 C   s    | ||| j| jdd S )Nr   r#   )viewr   r   	transpose
contiguous)r_   r   rv   r   rD   rD   rE   _shape  s    zMixtralAttention._shapeFrg   rQ   r   past_key_valueoutput_attentions	use_cacher&   c                 K   s  d|v r	t d | \}}	}
| |}| |}| |}|||	| j| j	dd}|||	| j
| j	dd}|||	| j
| j	dd}|jd }|d urj| jd u ratd| jj d|||| j7 }| j||d\}}t|||||\}}|d ur||d	}|||| j|\}}t|| j}t|| j}t||	dd
t| j }| || j|	|fkrtd|| j|	|f d|  |d ur| |d|	|fkrtd|d|	|f d|  || }tjj|dtjd|j}tjj || j!| j"d}t||}| || j|	| jfkr)td|| j|	| jf d|  |	dd# }|$||	| j%}| &|}|sCd }|||fS )Npadding_maskrPassing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`r   r#   r*   zFThe cache structure has changed since version v4.36. If you are using zv for auto-regressive decoding with k/v caching, please make sure to initialize the attention class with a layer index.rv   r   r   r
   z$Attention weights should be of size z	, but is z!Attention mask should be of size r)   rG   )ptrainingz `attn_output` should be of size )'warningswarnsizer   r   r   r   r   r   r   r   r6   r   r   rc   rk   get_usable_lengthr   r   updater   r   r.   matmulmathsqrtr   r8   r1   r<   r4   r2   dropoutr   r   r   r   r`   r   )r_   rg   rQ   r   r   r   r   kwargsr   q_len_query_states
key_statesvalue_states
kv_seq_lenr   r   cache_kwargsattn_weightsattn_outputrD   rD   rE   rj      sj   






 

zMixtralAttention.forwardr   NNNFF)rk   rl   rm   __doc__r   r   intrZ   r.   Tensorr   
LongTensorr   boolr   rj   rn   rD   rD   rb   rE   r      s0    %	r   c                       sx   e Zd ZdZ fddZ					ddejdeej deej d	ee	 d
e
de
fddZ			dddZdd Z  ZS )MixtralFlashAttention2aJ  
    Mixtral flash attention module. This module inherits from `MixtralAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s    t  j|i | t  | _d S r   )rY   rZ   r   _flash_attn_uses_top_left_mask)r_   argsr   rb   rD   rE   rZ   {  s   zMixtralFlashAttention2.__init__NFrg   rQ   r   r   r   r   c              	   K   sX  d|v rt d |d}| \}}	}
| |}| |}| |}|||	| j| j	
dd}|||	| j| j	
dd}|||	| j| j	
dd}|jd }|d ur`|||| j7 }t||d d df   d }| j||d\}}t|||||\}}tot| jdd d uo|| jjk}tstd	 |d ur.t| jdd d ur|| jjkrd| jj }|d
 }|d }|d d d d |d d d f  }|d d d d |d d d f  }|jd | jjd krtd|j ||f}|d ur|d d |d f }tj|t|d d dd f gdd}||d}|||| j|\}}t|| j }t|| j }| j!s@dn| j"}|j#}|tj$krut%| jdrX| jj&}n| jj'j#}td| d |(|}|(|}|(|}|
dd}|
dd}|
dd}| j)|||||	||d}|*||	| j+ }| ,|}|sd }|||fS )Nr   r   r   r#   r*   r)   r   sliding_windowzThe current flash attention version does not support sliding window attention, for a more memory efficient implementation make sure to upgrade flash-attn library.r   zepast key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got r'   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r   use_sliding_windows)-r   r   popr   r   r   r   r   r   r   r   r   r6   r   r   r:   rM   r   r   _flash_supports_window_sizegetattrr   r   r   r   r   r   r.   r/   	ones_liker   r   r   r   r   r2   r<   hasattrr   r]   r4   _flash_attention_forwardr   r`   r   )r_   rg   rQ   r   r   r   r   r   r   r   r   r   r   r   r   rotary_seq_lenr   r   r   slicing_tokenspast_key
past_valuer   dropout_raterh   target_dtyper   r   rD   rD   rE   rj     s   





"

"$$
(








zMixtralFlashAttention2.forwardr   c	                 C   s   | j s| j}	n| jo|dk}	|dur]|jd }
| |||||\}}}}}}|\}}|\}}|s?t||||||||||	d
}nt||||||||||	| jj| jjfd}t|||
|}|S |skt||||||	d}|S t||||||	| jj| jjfd}|S )a  
        Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
        first unpad the input, then computes the attention scores and pad the final attention scores.

        Args:
            query_states (`torch.Tensor`):
                Input query states to be passed to Flash Attention API
            key_states (`torch.Tensor`):
                Input key states to be passed to Flash Attention API
            value_states (`torch.Tensor`):
                Input value states to be passed to Flash Attention API
            attention_mask (`torch.Tensor`):
                The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
                position of padding tokens and 1 for the position of non-padding tokens.
            dropout (`int`, *optional*):
                Attention dropout
            softmax_scale (`float`, *optional*):
                The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
            use_sliding_windows (`bool`, *optional*):
                Whether to activate sliding window attention.
        r   Nr   )cu_seqlens_qcu_seqlens_kmax_seqlen_qmax_seqlen_k	dropout_psoftmax_scalecausal)r   r   r   r   r   r   r   r"   )r   r   )r   r   r"   )	r   r   r6   _upad_inputr   r   r   r    r   )r_   r   r   r   rQ   query_lengthr   r   r   r   
batch_size	indices_qcu_seq_lensmax_seq_lensr   r   max_seqlen_in_batch_qmax_seqlen_in_batch_kattn_output_unpadr   rD   rD   rE   r     st    


z/MixtralFlashAttention2._flash_attention_forwardc                 C   s&  |j \}}}}	||j d kr|j d }
|d d |
| d f }t|\}}}t||| ||	|}t||| ||	|}||krUt||| ||	|}|}|}|}n2|dkrsd}tj|d tj|jd}|d d }|d}n|d d | d f }t	||\}}}}||||||f||ffS )Nr)   r   r2   rw   )
r6   rV   r   r   r.   rz   rJ   rw   squeezer!   )r_   query_layer	key_layervalue_layerrQ   r   r   r   r   r   attention_mask_num_tokens	indices_kr   r   r   r   r   rD   rD   rE   r   c  s<   
z"MixtralFlashAttention2._upad_inputr   )r   NF)rk   rl   rm   r   rZ   r.   r   r   r   r   r   rj   r   r   rn   rD   rD   rb   rE   r   s  s6    
 
dr   c                       s*   e Zd Zdef fddZdd Z  ZS )MixtralBLockSparseTop2MLPr   c                    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 NFr   )rY   rZ   intermediate_sizeffn_dimr`   
hidden_dimr   r   w1w2w3r   
hidden_actact_fnr_   r   rb   rD   rE   rZ     s   
z"MixtralBLockSparseTop2MLP.__init__c                 C   s,   |  | || | }| |}|| S r   )r  r	  r  r
  )r_   rg   r?   current_hidden_statesrD   rD   rE   rj     s   
z!MixtralBLockSparseTop2MLP.forward)rk   rl   rm   r   rZ   rj   rn   rD   rD   rb   rE   r    s    r  )eagerflash_attention_2c                       s6   e Zd ZdZ fddZdejdejf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 accomodate 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                    sd   t     j| _ j| _ j| _ j| _	t
j| j| jdd| _t
 fddt| jD | _d S )NFr   c                    s   g | ]}t  qS rD   )r  ).0r   r   rD   rE   
<listcomp>  s    z2MixtralSparseMoeBlock.__init__.<locals>.<listcomp>)rY   rZ   r`   r  r  r  num_local_expertsr%   num_experts_per_tokr>   r   r   gate
ModuleListrangeexpertsr  rb   r  rE   rZ     s   
$zMixtralSparseMoeBlock.__init__rg   r&   c                 C   sB  |j \}}}|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 ]?}
| j|
 }t|	|
 \}}|j d
 d
krnqV| }| }|d|f d|}|||||df }|d
||
|j qV||||}||fS ) r)   r   rG   r'   T)r(   rd   r   )num_classesr#   r   N)r6   r   r  rN   r1   r.   r{   r0   r>   rI   r4   r2   zerosrw   r   r8   r9   r%   permuter  r  wheretolistr   
index_add_)r_   rg   r   sequence_lengthr  router_logitsr?   r@   final_hidden_statesrA   
expert_idxexpert_layeridxtop_x
top_x_listidx_listcurrent_stater  rD   rD   rE   rj     s.   

zMixtralSparseMoeBlock.forward)	rk   rl   rm   r   rZ   r.   r   rj   rn   rD   rD   rb   rE   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 d	eej	 d
ee
ej  dee dee dee de
ejee
ejejf  f fddZ  ZS )MixtralDecoderLayerr   r   c                    sV   t    |j| _t|j ||| _t|| _t|j|j	d| _
t|j|j	d| _d S )Nra   )rY   rZ   r`   MISTRAL_ATTENTION_CLASSES_attn_implementation	self_attnr  block_sparse_moerW   rms_norm_epsinput_layernormpost_attention_layernormr   rb   rD   rE   rZ     s   

zMixtralDecoderLayer.__init__NFrg   rQ   r   r   r   output_router_logitsr   r&   c                 K   s   d|v r	t d 	 |}	| |}| j||||||d\}}
}|	| }|}	| |}| |\}}|	| }|f}|r?||
f7 }|rF||f7 }|rM||f7 }|S )Nr   r   )rg   rQ   r   r   r   r   )r   r   r4  r1  r5  r2  )r_   rg   rQ   r   r   r   r6  r   r   residualself_attn_weightspresent_key_valuer$  outputsrD   rD   rE   rj     s8   




zMixtralDecoderLayer.forward)NNNFFF)rk   rl   rm   r   r   rZ   r.   r   r   r   r   r   FloatTensorrj   rn   rD   rD   rb   rE   r-    s2    
r-  aL  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`MixtralConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~PreTrainedModel.from_pretrained`] method to load the model weights.
zUThe bare Mixtral Model outputting raw hidden-states without any specific head on top.c                   @   s2   e Zd ZeZdZdZdgZdZdZ	dZ
dd ZdS )MixtralPreTrainedModelmodelTr-  past_key_valuesc                 C   s   | j j}t|tjr"|jjjd|d |jd ur |jj	  d S d S t|tj
rA|jjjd|d |jd urC|jj|j 	  d S d S d S )Nr   )r=   std)r   initializer_ranger,   r   r   r]   datanormal_r   zero_	Embeddingpadding_idx)r_   moduler?  rD   rD   rE   _init_weightsY  s   

z$MixtralPreTrainedModel._init_weightsN)rk   rl   rm   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_cache_classrG  rD   rD   rD   rE   r<  K  s    r<  a5  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        output_router_logits (`bool`, *optional*):
            Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
            should not be returned during inference.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                       s   e Zd ZdZdef fddZdd Zdd Zee																					dd
e
jdee
j dee
j deee
j  dee
j dee dee dee dee dee deeef fddZ  ZS )MixtralModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MixtralDecoderLayer`]

    Args:
        config: MixtralConfig
    r   c                    s   t     j| _ j| _t j j| j| _t	 fddt
 jD | _ jdk| _t j jd| _d| _|   d S )Nc                    s   g | ]}t  |qS rD   )r-  )r  r   r  rD   rE   r    s    z)MixtralModel.__init__.<locals>.<listcomp>r  r.  F)rY   rZ   pad_token_idrE  
vocab_sizer   rD  r`   embed_tokensr  r  num_hidden_layerslayersr0  _use_flash_attention_2rW   r3  normgradient_checkpointing	post_initr  rb   r  rE   rZ     s   zMixtralModel.__init__c                 C      | j S r   rR  r_   rD   rD   rE   get_input_embeddings     z!MixtralModel.get_input_embeddingsc                 C   
   || _ d S r   rZ  r_   valuerD   rD   rE   set_input_embeddings     
z!MixtralModel.set_input_embeddingsN	input_idsrQ   r   r>  inputs_embedsr   r   output_hidden_statesr6  return_dictr&   c                 C   s  |d ur|n| j j}|	d ur|	n| j j}	|d ur|n| j j}|d ur$|n| j j}|
d ur.|
n| j j}
|d ur>|d ur>td|d urH|j\}}n|d urS|j\}}}ntdd}|rmt|t	 }|rht
|}||}|d u r|d urx|jn|j}tj||| tj|d}|dd|}n|d| }|d u r| |}|d ur| jr|r|d d df   |k}|rtd| jr|d urd|v r|nd }nt|||f||| j jd}|}| jr| jr|rtd d	}|rd
nd }|rd
nd }|	rd
nd }d }| jD ]P}|r||f7 }| jr$| jr$| |j||||||	|}n|||||||	|d}|d }|r?||r<dnd }|rI||d f7 }|	rS||d f7 }q|  |}|rb||f7 }d }|rp|rn|! n|}|
st"dd |||||fD S t#|||||dS )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timezEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   r   r)   zYou are attempting to perform batched generation with padding_side='right' this may lead to unexpected behaviour for Flash Attention version of Mixtral. Make sure to  call `tokenizer.padding_side  = 'left'` before tokenizing the input. )r   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FrD   )rQ   r   r   r   r6  r   r#   r   c                 s   s    | ]	}|d ur|V  qd S r   rD   )r  vrD   rD   rE   	<genexpr>X  s    z'MixtralModel.forward.<locals>.<genexpr>)last_hidden_stater>  rg   
attentionsr$  )$r   r   r6  re  r   use_return_dictr   r6   r,   r   r   from_legacy_cacher   rw   r.   rz   longr7   r   rR  rU  rI   rM   r   r   rW  r   r   r   rT  _gradient_checkpointing_func__call__rV  to_legacy_cacher-   r   )r_   rc  rQ   r   r>  rd  r   r   re  r6  rf  r   
seq_lengthr   past_key_values_lengthuse_legacy_cacherw   is_padding_rightrg   all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_cacherD   rD   rE   rj     s   







zMixtralModel.forward
NNNNNNNNNN)rk   rl   rm   r   r   rZ   r\  ra  r   MIXTRAL_INPUTS_DOCSTRINGr.   r   r   r   r   r;  r   r   r   r   rj   rn   rD   rD   rb   rE   rO    sN    	

rO  c                       s  e Zd ZdgZ fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
eeeeed											d$dejdeej deej deeej  deej deej dee dee dee dee dee deeef fddZ	d%d d!Zed"d# Z  ZS )&MixtralForCausalLMzlm_head.weightc                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _|j| _|   d S r  )rY   rZ   rO  r=  rQ  r   r   r`   lm_headrouter_aux_loss_coefr  r%   r  rX  r  rb   rD   rE   rZ   i  s   
zMixtralForCausalLM.__init__c                 C      | j jS r   r=  rR  r[  rD   rD   rE   r\  t     z'MixtralForCausalLM.get_input_embeddingsc                 C      || j _d S r   r  r_  rD   rD   rE   ra  w     z'MixtralForCausalLM.set_input_embeddingsc                 C   rY  r   r  r[  rD   rD   rE   get_output_embeddingsz  r]  z(MixtralForCausalLM.get_output_embeddingsc                 C   r^  r   r  )r_   new_embeddingsrD   rD   rE   set_output_embeddings}  rb  z(MixtralForCausalLM.set_output_embeddingsc                 C   r^  r   r=  )r_   decoderrD   rD   rE   set_decoder  rb  zMixtralForCausalLM.set_decoderc                 C   rY  r   r  r[  rD   rD   rE   get_decoder  r]  zMixtralForCausalLM.get_decoder)output_typerH  Nrc  rQ   r   r>  rd  labelsr   r   re  r6  rf  r&   c                 C   s  |dur|n| j j}|
dur|
n| j j}
|	dur|	n| j j}	|dur$|n| j j}| j||||||||	|
|d
}|d }| |}| }d}|dur||dddddf  }|dddf  }t	 }|
d| j j}|
d}||j}|||}d}|
rt|r|jn|d | j| j}|dur|| j| 7 }|s|f|dd  }|
r|f| }|dur|f| S |S t||||j|j|j|jdS )a  
        Args:
            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]`.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, MixtralForCausalLM

        >>> model = MixtralForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
        >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)

        >>> 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)
rc  rQ   r   r>  rd  r   r   re  r6  rf  r   .r)   r   )lossaux_losslogitsr>  rg   rj  r$  )r   r   r6  re  rk  r=  r  r{   r   r   r   rQ  r4   rw   rF   r$  r%   r  r  r   r>  rg   rj  )r_   rc  rQ   r   r>  rd  r  r   r   re  r6  rf  r:  rg   r  r  shift_logitsshift_labelsloss_fctr  outputrD   rD   rE   rj     sf   +



zMixtralForCausalLM.forwardc                 K   sz  |d urnt |tr| }|j}| }n|d d jd  }}d }|d urA|jd |jd krA|d d |jd |  d f }n||jd k rR|d d |d f }|d urn|d urn||jd  |krn|d d | d f }|dd }	|d ur|	d u r| dd }	|		|dkd |r|	d d |jd  d f }	|d ur|d u rd|i}
nd|i}
|

|	||d|d	 |
S )
Nr   r#   r   r   r)   rd  rc  r   )r   r>  r   rQ   )r,   r   get_seq_lengthseen_tokensget_max_lengthr6   getrm  rP   masked_fill_r   )r_   rc  r>  rQ   rd  r   cache_lengthpast_lengthmax_cache_lengthr   model_inputsrD   rD   rE   prepare_inputs_for_generation  s@   

"
z0MixtralForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ]}|t  fdd|D f7 }q|S )NrD   c                 3   s$    | ]}| d  |jV  qdS )r   N)index_selectr4   rw   )r  
past_statebeam_idxrD   rE   rh  0  s   " z4MixtralForCausalLM._reorder_cache.<locals>.<genexpr>)r-   )r>  r  reordered_past
layer_pastrD   r  rE   _reorder_cache+  s   z!MixtralForCausalLM._reorder_cache)NNNNNNNNNNN)NNN)rk   rl   rm   _tied_weights_keysrZ   r\  ra  r  r  r  r  r   r}  r   r   _CONFIG_FOR_DOCr.   r   r   r   r   r;  r   r   r   rj   r  staticmethodr  rn   rD   rD   rb   rE   r~  f  sf    
	

j
9r~  a  
    The Mixtral Model transformer with a sequence classification head on top (linear layer).

    [`MixtralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                       s   e Zd Z fddZdd Zdd Zee										ddej	d	e
ej d
e
ej	 de
eej  de
ej de
ej	 de
e de
e de
e de
e deeef fddZ  ZS ) MixtralForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r  )
rY   rZ   
num_labelsrO  r=  r   r   r`   scorerX  r  rb   rD   rE   rZ   F  s
   
z)MixtralForSequenceClassification.__init__c                 C   r  r   r  r[  rD   rD   rE   r\  O  r  z5MixtralForSequenceClassification.get_input_embeddingsc                 C   r  r   r  r_  rD   rD   rE   ra  R  r  z5MixtralForSequenceClassification.set_input_embeddingsNrc  rQ   r   r>  rd  r  r   r   re  rf  r&   c                 C   s  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}|dur+|jd }n|jd }| j jdu r>|dkr>td| j jdu rGd}n|dur_t|| j j	 
dd |j}nd}|tj||jd|f }d}|dur||j}| j jdu r| jdkrd| j _n| jdkr|jtjks|jtj	krd	| j _nd
| j _| j jdkrt }| jdkr|| | }n+|||}n%| j jd	krt }||d| j|d}n| j jd
krt }|||}|
s|f|dd  }|dur|f| S |S t|||j|j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N)rQ   r   r>  rd  r   r   re  rf  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r)   )rw   
regressionsingle_label_classificationmulti_label_classification)r  r  r>  rg   rj  )r   rk  r=  r  r6   rP  r   r.   eqr   argmaxr4   rw   rz   problem_typer  r2   rm  r	   r   r   r   r   r   r>  rg   rj  )r_   rc  rQ   r   r>  rd  r  r   r   re  rf  transformer_outputsrg   r  r   sequence_lengthspooled_logitsr  r  r  rD   rD   rE   rj   U  sr   



"


z(MixtralForSequenceClassification.forwardr|  )rk   rl   rm   rZ   r\  ra  r   r}  r.   r   r   r   r   r;  r   r   r   r   rj   rn   rD   rD   rb   rE   r  5  sL    		

r  )Nr#   )r   )Vr   inspectr   r   typingr   r   r   r   r.   torch.nn.functionalr   r8   rN   torch.utils.checkpointtorch.nnr   r   r	   activationsr   cache_utilsr   r   modeling_attn_mask_utilsr   modeling_outputsr   r   r   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   r   utils.import_utilsr   configuration_mixtralr   
flash_attnr   r   flash_attn.bert_paddingr   r    r!   list	signature
parametersr   torch.fxfxwrap
get_loggerrk   r   r  r   r{   rF   rV   ModulerW   ro   r   r   r   r   r   r   r  r/  r  r-  MIXTRAL_START_DOCSTRINGr<  r}  rO  r~  r  rD   rD   rD   rE   <module>   s    
0%
   FNC : P