U
    5AfI                     @   s&  d Z ddlZddlmZmZmZmZ ddl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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 ddlmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& e! rddl'm(Z( e#)e*Z+dZ,G dd de	j-Z.G dd de	j-Z/dd Z0d6ddZ1G dd de	j-Z2ej3e4ej3dddZ5G dd de	j-Z6G d d! d!e6Z7G d"d# d#e6Z8e6e7e8d$Z9G d%d& d&e	j-Z:d'Z;ed(e;G d)d* d*eZ<d+Z=ed(e;G d,d- d-e<Z>G d.d/ d/e<Z?ed0e;G d1d2 d2e<Z@ed3e;G d4d5 d5e<ZAdS )7zPyTorch Mistral model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPastTokenClassifierOutput)PreTrainedModel)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   )MistralConfig)_flash_attention_forwardr   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	MistralRMSNormư>c                    s&   t    tt|| _|| _dS )z=
        MistralRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	ParametertorchZonesweightvariance_epsilon)selfhidden_sizeeps	__class__ P/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/mistral/modeling_mistral.pyr"   =   s    
zMistralRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)Zkeepdim)	dtypetor$   float32powmeanZrsqrtr&   r%   )r'   hidden_statesinput_dtypeZvariancer,   r,   r-   forwardE   s
    zMistralRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler%   shaper&   r'   r,   r,   r-   
extra_reprL   s    zMistralRMSNorm.extra_repr)r    )__name__
__module____qualname__r"   r7   r;   __classcell__r,   r,   r*   r-   r   <   s   r   c                       s.   e Zd Zd fdd	Ze dd Z  ZS )	MistralRotaryEmbedding   '  Nc                    s`   t    || _|| _|| _d| jtjd| jdtjd 	|| j   }| j
d|dd d S )Ng      ?r   r.   r0   inv_freqF)
persistent)r!   r"   dimmax_position_embeddingsbaser$   arangeZint64floatr1   Zregister_buffer)r'   rF   rG   rH   devicerD   r*   r,   r-   r"   Q   s    
0zMistralRotaryEmbedding.__init__c           
   	   C   s   | j d d d d f  |jd dd}|d d d d d f  }|jj}t|tr`|dkr`|nd}tj	|dd@ | |  
dd}tj||fdd	}| }| }	W 5 Q R X |j|jd
|	j|jd
fS )Nr   r/   r   ZmpscpuF)device_typeZenabledr.   rF   rC   )rD   rJ   expandr9   rK   type
isinstancestrr$   Zautocast	transposecatcossinr1   r0   )
r'   xposition_idsZinv_freq_expandedZposition_ids_expandedrM   ZfreqsZembrU   rV   r,   r,   r-   r7   Z   s    (zMistralRotaryEmbedding.forward)rA   rB   N)r<   r=   r>   r"   r$   Zno_gradr7   r?   r,   r,   r*   r-   r@   P   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..Nr/   r.   rN   )r9   r$   rT   )rW   x1Zx2r,   r,   r-   rotate_halfn   s    rZ   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.
    )	unsqueezerZ   )qkrU   rV   rX   Zunsqueeze_dimZq_embedZk_embedr,   r,   r-   apply_rotary_pos_embv   s
    

r^   c                       s$   e Zd Z fddZdd Z  ZS )
MistralMLPc                    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bias)r!   r"   r(   Zintermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnr'   configr*   r,   r-   r"      s    
zMistralMLP.__init__c                 C   s    |  | | || | S N)rf   rg   rd   re   )r'   Zhidden_stater,   r,   r-   r7      s    zMistralMLP.forward)r<   r=   r>   r"   r7   r?   r,   r,   r*   r-   r_      s   	r_   )r5   n_repreturnc                 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)r9   rO   reshape)r5   rk   batchnum_key_value_headsslenhead_dimr,   r,   r-   	repeat_kv   s
    0rr   c                       s   e Zd ZdZd
eee d fddZdej	eej	 eej
 ee eeeej
 eej	eej	 eeej	  f ddd	Z  ZS )MistralAttentionz
    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ri   	layer_idxc                    s
  t    || _|| _|d kr4td| jj d |j| _|j	| _	|j
| _|j| _|j| _| j| j | _|j| _|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 a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.TFra   )rG   rH   )r!   r"   ri   ru   loggerwarning_oncer+   r<   attention_dropoutr(   Znum_attention_heads	num_headsrq   ro   num_key_value_groupsrG   Z
rope_theta	is_causalr   rc   q_projk_projv_projo_projr@   
rotary_embr'   ri   ru   r*   r,   r-   r"      s2    
zMistralAttention.__init__Fr5   attention_maskrX   past_key_valueoutput_attentions	use_cachecache_positionrl   c                 C   s  |  \}}	}
| |}| |}| |}|||	| j| jdd}|||	| j| jdd}|||	| j| jdd}| 	||\}}t
||||\}}|d k	r|||d}|||| j|\}}t|| j}t|| j}t||ddt| j }|d k	r<|d d d d d d d |jd f }|| }tjj|dtjd|j}tjj|| j| jd}t||}|  || j|	| jfkrtd	|| j|	| jf d
|   |dd }|||	d}| |}|sd }|||fS )Nr   r.   rV   rU   r   r
   r/   )rF   r0   )ptrainingz `attn_output` should be of size z	, but is ) sizer|   r}   r~   viewry   rq   rS   ro   r   r^   updateru   rr   rz   r$   matmulmathsqrtr9   r   
functionalZsoftmaxr2   r1   r0   dropoutrx   r   
ValueError
contiguousr   )r'   r5   r   rX   r   r   r   r   bszq_len_query_states
key_statesvalue_statesrU   rV   cache_kwargsattn_weightscausal_maskattn_outputr,   r,   r-   r7      s>    



 
&
zMistralAttention.forward)N)NNNFFN)r<   r=   r>   __doc__r   r   intr"   r$   Tensor
LongTensorr   boolr   r7   r?   r,   r,   r*   r-   rs      s$   #      rs   c                	       sT   e Zd ZdZ fddZd	ejeej eej ee	 e
e
eej dddZ  ZS )
MistralFlashAttention2aJ  
    Mistral flash attention module. This module inherits from `MistralAttention` 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|| t  | _d S rj   )r!   r"   r   _flash_attn_uses_top_left_mask)r'   argskwargsr*   r,   r-   r"     s    zMistralFlashAttention2.__init__NFr5   r   rX   r   r   r   r   c                 C   s>  t |trtdd}| \}}	}
| |}| |}| |}|||	| j| j	
dd}|||	| j| j	
dd}|||	| j| j	
dd}|jd }|d k	r||d 7 }| ||\}}t||||\}}|d k	r|| jdk}t| jdd d k	r|| jjkr|rd| jj }|| j d }|| j 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 |d k	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rt rft  }n"t!| jdr~| jj"}n
| jj#j}t$%d| d |&|}|&|}|&|}|
dd}|
dd}|
dd}t'|||||	||t| jdd | j(| j)d
}|*||	| j| j	  }| +|}|s4d }|||fS )Nz`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformersFr   r.   r   r   sliding_windowzepast key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got r/   rN   )rV   rU           _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 .)rX   r   r   Zuse_top_left_maskr{   ),rQ   r   r   r   r|   r}   r~   r   ry   rq   rS   ro   r9   r   r^   get_seq_lengthru   getattrri   r   r   r$   rT   Z	ones_liker   rr   rz   r   rx   r0   r2   Zis_autocast_enabledZget_autocast_gpu_dtypehasattrr   r%   rv   rw   r1   r   r   r{   rm   r   )r'   r5   r   rX   r   r   r   r   r   r   r   r   r   r   Z
kv_seq_lenrU   rV   Zcache_has_contentsZslicing_tokensZpast_keyZ
past_valuer   Zdropout_rater6   Ztarget_dtyper   r   r,   r,   r-   r7     s    







$$

(









zMistralFlashAttention2.forward)NNNFFN)r<   r=   r>   r   r"   r$   r   r   r   r   r   r7   r?   r,   r,   r*   r-   r     s"         r   c                       sj   e Zd ZdZdejeej eej ee e	e	eej e
ejeej ee
ej  f d fddZ  ZS )MistralSdpaAttentionz
    Mistral attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `MistralAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFr   c              	      s  |r(t d t j|||||||dS | \}	}
}| |}| |}| |}||	|
| j	| j
dd}||	|
| j| j
dd}||	|
| j| j
dd}| ||\}}t||||\}}|d k	r|||d}|||| j|\}}t|| j}t|| j}|}|d k	r@|d d d d d d d |jd f }|jjdkrp|d k	rp| }| }| }|d kr|
dkrdnd	}tjjj||||| jr| jnd
|d}|dd }||	|
d}| |}|d |fS )Na  MistralModel is using MistralSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   r   r.   r   r   cudaTFr   )Z	attn_maskZ	dropout_pr{   r/   )rv   rw   r!   r7   r   r|   r}   r~   r   ry   rq   rS   ro   r   r^   r   ru   rr   rz   r9   rK   rP   r   r$   r   r   Zscaled_dot_product_attentionr   rx   r   )r'   r5   r   rX   r   r   r   r   r   r   r   r   r   r   r   rU   rV   r   r   r{   r   r*   r,   r-   r7     s^    




&	
zMistralSdpaAttention.forward)NNNFFN)r<   r=   r>   r   r$   r   r   r   r   r   r   r7   r?   r,   r,   r*   r-   r     s"   
      r   )eagerflash_attention_2sdpac                       s|   e Zd Zeed fddZd	ejeej eej	 ee
 ee ee eej	 eejeeejejf  f dddZ  ZS )
MistralDecoderLayerrt   c                    sX   t    |j| _t|j ||d| _t|| _t|j|j	d| _
t|j|j	d| _d S )Nrt   r)   )r!   r"   r(   MISTRAL_ATTENTION_CLASSES_attn_implementation	self_attnr_   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr   r*   r,   r-   r"     s    

zMistralDecoderLayer.__init__NFr   c              
   K   s   |}	|  |}| jf |||||||d|\}}
}|	| }|}	| |}| |}|	| }|f}|rp||
f7 }|r~||f7 }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*):
                attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
                query_sequence_length, key_sequence_length)` if default attention is used.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            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`).
            past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence
            kwargs (`dict`, *optional*):
                Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
                into the model
        r   )r   r   r   r   )r'   r5   r   rX   r   r   r   r   r   ZresidualZself_attn_weightsZpresent_key_valueoutputsr,   r,   r-   r7     s0    





zMistralDecoderLayer.forward)NNNFFN)r<   r=   r>   r   r   r"   r$   r   r   r   r   r   r   FloatTensorr7   r?   r,   r,   r*   r-   r     s"         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 ([`MistralConfig`]):
            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 Mistral Model outputting raw hidden-states without any specific head on top.c                   @   s:   e Zd ZeZdZdZdgZdZdZ	dZ
dZdZdd ZdS )MistralPreTrainedModelmodelTr   past_key_valuesc                 C   s|   | j j}t|tjr>|jjjd|d |jd k	rx|jj	  n:t|tj
rx|jjjd|d |jd k	rx|jj|j 	  d S )Nr   )r4   std)ri   Zinitializer_rangerQ   r   rc   r%   dataZnormal_rb   Zzero_	Embeddingpadding_idx)r'   moduler   r,   r,   r-   _init_weightsb  s    

z$MistralPreTrainedModel._init_weightsN)r<   r=   r>   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_supports_static_cacher   r,   r,   r,   r-   r   S  s   r   aL  
    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 (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
            returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - 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)`). This is also known as the legacy
            cache format.

            The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
            legacy cache format will be returned.

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `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.
        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ed fddZdd Zdd Zee	de
jee
j ee
j eeeee
j f  ee
j ee ee ee ee ee
j eeef d
ddZe
je
je
jeeedddZ  ZS )MistralModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]

    Args:
        config: MistralConfig
    ri   c                    s~   t     j| _ j| _t j j| j| _t	 fddt
 jD | _ j| _t j jd| _d| _|   d S )Nc                    s   g | ]}t  |qS r,   )r   ).0ru   r   r,   r-   
<listcomp>  s     z)MistralModel.__init__.<locals>.<listcomp>r   F)r!   r"   pad_token_idr   
vocab_sizer   r   r(   embed_tokensZ
ModuleListrangeZnum_hidden_layerslayersr   r   r   normgradient_checkpointing	post_initrh   r*   r   r-   r"     s    zMistralModel.__init__c                 C   s   | j S rj   r   r:   r,   r,   r-   get_input_embeddings  s    z!MistralModel.get_input_embeddingsc                 C   s
   || _ d S rj   r   r'   valuer,   r,   r-   set_input_embeddings  s    z!MistralModel.set_input_embeddingsN)	input_idsr   rX   r   inputs_embedsr   r   output_hidden_statesreturn_dictr   rl   c                 C   sH  |d k	r|n| j j}|d k	r |n| j j}|d k	r4|n| j j}|	d k	rH|	n| j j}	|d k|d k	A rhtd| jr| jr|rt	d d}|d kr| 
|}d}|rt|ts| jst|}d}t	d |
d kr|d k	r| nd}tj|||jd  |jd}
|d kr|
d}| |||
|||}|}|r8d	nd }|rFd	nd }d }| jD ]}|rh||f7 }| jr| jr| |j|||||||
}n||||||||
d
}|d }|r||rdnd }|rT||d f7 }qT| |}|r||f7 }|r|nd }|r| }|	s8tdd ||||fD S t||||dS )NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...FTzWe detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)r   r   rK   r,   )r   rX   r   r   r   r   r.   c                 s   s   | ]}|d k	r|V  qd S rj   r,   )r   vr,   r,   r-   	<genexpr>E  s      z'MistralModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   r5   
attentions)ri   r   r   r   use_return_dictr   r   r   rv   rw   r   rQ   r   r   Zfrom_legacy_cacher   r$   rI   r9   rK   r[   _update_causal_maskr   Z_gradient_checkpointing_func__call__r   Zto_legacy_cacher8   r   )r'   r   r   rX   r   r   r   r   r   r   r   Zreturn_legacy_cachepast_seen_tokensr   r5   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheZdecoder_layerZlayer_outputsZ
next_cacher,   r,   r-   r7     s    


  

     




zMistralModel.forward)r   input_tensorr   r   r   r   c                 C   s  | j dkr^|d k	rF|rF|d d df   | d k}|rFtd|d k	rZd|krZ|S d S |d k	rn|d nd}t|t}	t|t}
| jj dkr|	s|
s|st	j
|||| jj| jdrd S |j|j }}t|j}|jd }|
rt|| jj}n4|	r| }n$t|tjr|jd n
|| d }|d k	r^| d	kr^| dkrVtd
|}nZtj||f|||d}tj||d|ddk}| jjd k	r|
r|| jjkr|tj||d|dd| jj k ||9 }|d d d d d d f |jd ddd}|d k	r| }| dkr|jd }|d d d d d d d |f |d d d d d d f  }|dk}|d d d d d d d |f |||d d d d d d d |f< | jj dkr|d k	r|jjdkr|st	||}|S )Nr   r/   r   zYou are attempting to perform batched generation with padding_side='right' this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to  call `tokenizer.padding_side  = 'left'` before tokenizing the input. r   r   )r   Zpast_key_values_lengthr   Zis_trainingr      zGCustom 4D attention mask should be passed in inverted form with max==0`)Z
fill_valuer0   rK   r   r.   r   ) r   sumitemr   r   rQ   r   r   ri   r   Z_ignore_causal_mask_sdpar   r   r0   rK   r$   Zfinfominr9   maxZget_max_lengthr   rF   fullrI   rm   Zbitwise_or_rO   cloneZmasked_fillrP   Z_unmask_unattended)r'   r   r   r   r   r   r   Zis_padding_rightr   Zusing_static_cacheZusing_sliding_window_cacher0   rK   Z	min_dtypeZsequence_lengthZtarget_lengthr   Zexclude_maskZmask_lengthZpadding_maskr,   r,   r-   r   M  s    
$






   *

8   

	z MistralModel._update_causal_mask)
NNNNNNNNNN)r<   r=   r>   r   r   r"   r   r   r   MISTRAL_INPUTS_DOCSTRINGr$   r   r   r   r   r   r   r   r   r   r   r7   r   r?   r,   r,   r*   r-   r     sF             
xr   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ejeej eej eeeeej f  eej eej ee ee ee ee eej eeef dddZdddZ  ZS )MistralForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r`   )
r!   r"   r   r   r   r   rc   r(   lm_headr   rh   r*   r,   r-   r"     s
    
zMistralForCausalLM.__init__c                 C   s   | j jS rj   r   r   r:   r,   r,   r-   r     s    z'MistralForCausalLM.get_input_embeddingsc                 C   s   || j _d S rj   r   r   r,   r,   r-   r     s    z'MistralForCausalLM.set_input_embeddingsc                 C   s   | j S rj   r   r:   r,   r,   r-   get_output_embeddings  s    z(MistralForCausalLM.get_output_embeddingsc                 C   s
   || _ d S rj   r   )r'   Znew_embeddingsr,   r,   r-   set_output_embeddings  s    z(MistralForCausalLM.set_output_embeddingsc                 C   s
   || _ d S rj   r   )r'   decoderr,   r,   r-   set_decoder  s    zMistralForCausalLM.set_decoderc                 C   s   | j S rj   r   r:   r,   r,   r-   get_decoder  s    zMistralForCausalLM.get_decoder)output_typer   N)r   r   rX   r   r   labelsr   r   r   r   r   rl   c                 C   s,  |dk	r|n| j j}|	dk	r |	n| j j}	|
dk	r4|
n| j j}
| j||||||||	|
|d
}|d }| |}| }d}|dk	r|dddddf  }|dddf  }|d| j j	}|d}|
|j}t }|||}|
s|f|dd  }|dk	r|f| S |S t|||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, MistralForCausalLM

        >>> model = MistralForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1")
        >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-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   rX   r   r   r   r   r   r   r   r   .r/   r   losslogitsr   r5   r   )ri   r   r   r   r   r   rJ   r   r   r   r1   rK   r   r   r   r5   r   )r'   r   r   rX   r   r   r   r   r   r   r   r   r   r5   r   r   Zshift_logitsZshift_labelsloss_fctoutputr,   r,   r-   r7     sL    *


zMistralForCausalLM.forwardTc           
      K   s   |d k	rR|d k	r.|d d |j d  d f }n$|j d |j d krR|d d |f }|d k	r|d kr| dd }||dkd |r|d d |j d  d f }|jtjd}|d k	r|d dkrd|i}	nd| i}	|	|||||d |	S )Nr   r   r/   )Zmemory_formatr   r   )rX   r   r   r   r   )	r9   longZcumsumZmasked_fill_r   r$   Zcontiguous_formatr   r   )
r'   r   r   r   r   r   rX   r   r   Zmodel_inputsr,   r,   r-   prepare_inputs_for_generation3  s.    
	z0MistralForCausalLM.prepare_inputs_for_generation)NNNNNNNNNNN)NNNNNT)r<   r=   r>   Z_tied_weights_keysr"   r   r   r   r   r   r   r   r   r   r   _CONFIG_FOR_DOCr$   r   r   r   r   r   r   r   r   r   r7   r  r?   r,   r,   r*   r-   r     sT   	
           
\      r   a  
    The Mistral Model transformer with a sequence classification head on top (linear layer).

    [`MistralForSequenceClassification`] 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ee	j
 ee	j ee	j
 eeeee	j f  ee	j ee	j
 ee ee ee ee eeef dd	d
Z  ZS ) MistralForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r`   )
r!   r"   
num_labelsr   r   r   rc   r(   scorer   rh   r*   r,   r-   r"   t  s
    
z)MistralForSequenceClassification.__init__c                 C   s   | j jS rj   r   r:   r,   r,   r-   r   }  s    z5MistralForSequenceClassification.get_input_embeddingsc                 C   s   || j _d S rj   r   r   r,   r,   r-   r     s    z5MistralForSequenceClassification.set_input_embeddingsNr   r   rX   r   r   r   r   r   r   r   rl   c                 C   s:  |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}|dk	rV|jd }n
|jd }| j jdkr||dkr|td| j jdkrd}nF|dk	rt|| j j	 
dd }||jd  }||j}nd}|tj||jd|f }d}|dk	r||j}| j jdkrd| jdkr*d| j _n:| jdkr\|jtjksR|jtj	kr\d	| j _nd
| j _| j jdkrt }| jdkr|| | }n
|||}nN| j jd	krt }||d| j|d}n| j jd
krt }|||}|
s"|f|dd  }|dk	r|f| S |S t|||j|j|jdS )  
        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r   rX   r   r   r   r   r   r   r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r/   r   Z
regressionZsingle_label_classificationZmulti_label_classificationr   )ri   r   r   r  r9   r   r   r$   eqr   Zargmaxr1   rK   rI   Zproblem_typer  r0   r  r	   Zsqueezer   r   r   r   r   r5   r   )r'   r   r   rX   r   r   r   r   r   r   r   Ztransformer_outputsr5   r   Z
batch_sizeZsequence_lengthsZpooled_logitsr   r   r  r,   r,   r-   r7     sr    



(

z(MistralForSequenceClassification.forward)
NNNNNNNNNN)r<   r=   r>   r"   r   r   r   r   r   r$   r   r   r   r   r   r   r   r   r   r7   r?   r,   r,   r*   r-   r  c  s6   	          
r  z
    The Mistral Model transformer with a token classification head on top (a linear layer on top of the hidden-states
    output) e.g. for Named-Entity-Recognition (NER) tasks.
    c                       s   e Zd Z fddZdd Zdd Zeedee	j
 ee	j ee	j
 eee	j  ee	j ee	j
 ee ee ee ee eeef dd	d
Z  ZS )MistralForTokenClassificationc                    s|   t  | |j| _t|| _t|dd d k	r6|j}nt|dd d k	rN|j}nd}t	|| _
t|j|j| _|   d S )Nclassifier_dropouthidden_dropoutg?)r!   r"   r  r   r   r   r  r  r   ZDropoutr   rc   r(   r  r   )r'   ri   r  r*   r,   r-   r"     s    
z&MistralForTokenClassification.__init__c                 C   s   | j jS rj   r   r:   r,   r,   r-   r     s    z2MistralForTokenClassification.get_input_embeddingsc                 C   s   || j _d S rj   r   r   r,   r,   r-   r     s    z2MistralForTokenClassification.set_input_embeddingsNr  c                 C   s   |
dk	r|
n| j j}
| j||||||||	|
d	}|d }| |}| |}d}|dk	rxt }||d| j|d}|
s|f|dd  }|dk	r|f| S |S t|||j	|j
dS )r	  Nr
  r   r/   r.   )r   r   r5   r   )ri   r   r   r   r  r   r   r  r   r5   r   )r'   r   r   rX   r   r   r   r   r   r   r   r   Zsequence_outputr   r   r   r  r,   r,   r-   r7     s8    

z%MistralForTokenClassification.forward)
NNNNNNNNNN)r<   r=   r>   r"   r   r   r   r   r   r$   r   r   r   r   r   r   r   r   r7   r?   r,   r,   r*   r-   r    s6   	          
r  )Nr   )Br   r   typingr   r   r   r   r$   Ztorch.utils.checkpointr   Ztorch.nnr   r   r	   Zactivationsr   Zcache_utilsr   r   r   r   Zmodeling_attn_mask_utilsr   Zmodeling_outputsr   r   r   r   Zmodeling_utilsr   utilsr   r   r   r   r   r   Zconfiguration_mistralr   Zmodeling_flash_attention_utilsr   Z
get_loggerr<   rv   r  Moduler   r@   rZ   r^   r_   r   r   rr   rs   r   r   r   r   ZMISTRAL_START_DOCSTRINGr   r   r   r   r  r  r,   r,   r,   r-   <module>   st    

a 
Y	KF   *l