U
    ,-e                     @   sL  d 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mZ dd	lmZ dd
lmZmZmZmZmZ ddl m!Z! e rddl"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z( de)e*e#j+kZ,e-e.Z/dZ0dd Z1d9ej2ej3ej4e5e5dddZ6d:ej7ej3ee5 dddZ8G dd de
j9Z:G dd de
j9Z;dd Z<d d! Z=G d"d# d#e
j9Z>ej7e5ej7d$d%d&Z?G d'd( d(e
j9Z@G d)d* d*e@ZAG d+d, d,e
j9ZBd-ZCed.eCG d/d0 d0eZDd1ZEed.eCG d2d3 d3eDZFG d4d5 d5eDZGed6eCG d7d8 d8eDZHdS );z PyTorch Mistral model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_availableloggingreplace_return_docstrings   )MistralConfig)flash_attn_funcflash_attn_varlen_func)index_first_axis	pad_inputunpad_inputwindow_sizer   c                 C   sX   | j dtjd}tj|  dd }|  }ttj	|dtjjdd}|||fS )NdimdtypeF)as_tupler   )r   r   )
sumtorchint32ZnonzeroflattenmaxitemFpadcumsum)padding_maskZseqlens_in_batchindicesZmax_seqlen_in_batchZ
cu_seqlens r-   m/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/mistral/modeling_mistral.py_get_unpad_data9   s    r/      )input_ids_shaper    devicepast_key_values_lengthsliding_windowc           	      C   s   | \}}t j||fd|d}t j|dd}t j|| d}t ||}|dkrrt jt j||||d|gdd}|ddddddf |d||| S )	z<
    Make causal mask used for sliding window attention
    r   )Z
fill_valuer2   r   )Zdiagonalr    r2   r   r   N)	r#   fullZtrilZtriulogtocatZzerosexpand)	r1   r    r2   r3   r4   bsztgt_lentensormaskr-   r-   r.    _make_sliding_window_causal_maskE   s    
 r@   )r?   r    r=   c                 C   sj   |   \}}|dk	r|n|}| ddddddf |d|||}d| }||tjt|jS )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)sizer;   r9   Zmasked_fillr#   boolZfinfomin)r?   r    r=   r<   Zsrc_lenZexpanded_maskZinverted_maskr-   r-   r.   _expand_maska   s
    *rE   c                       s&   e Zd Zd f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   	Parameterr#   onesweightvariance_epsilon)selfhidden_sizeeps	__class__r-   r.   rI   q   s    
zMistralRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   r   T)Zkeepdim)	r    r9   r#   float32powmeanZrsqrtrM   rL   )rN   hidden_statesinput_dtypeZvariancer-   r-   r.   forwardy   s
    zMistralRMSNorm.forward)rG   __name__
__module____qualname__rI   rY   __classcell__r-   r-   rQ   r.   rF   p   s   rF   c                       s0   e Zd Zd
 fdd	Zdd Zddd	Z  ZS )MistralRotaryEmbedding   '  Nc                    sr   t    || _|| _|| _d| jtd| jd || j   }| j	d|dd | j
|| jjt d d S )NrA   r   rS   inv_freqF
persistentseq_lenr2   r    )rH   rI   r   max_position_embeddingsbaser#   arangefloatr9   register_buffer_set_cos_sin_cacherb   r2   Zget_default_dtype)rN   r   rg   rh   r2   rb   rQ   r-   r.   rI      s    
*  zMistralRotaryEmbedding.__init__c                 C   s   || _ tj| j || jjd}td|| j}tj||fdd}| jd| d d d d d d f 	|dd | jd|
 d d d d d d f 	|dd d S )	N)r2   r    zi,j->ijr   r6   
cos_cachedFrc   
sin_cached)max_seq_len_cachedr#   ri   rb   r    Zeinsumr:   rk   cosr9   sin)rN   rf   r2   r    tZfreqsZembr-   r-   r.   rl      s    .z)MistralRotaryEmbedding._set_cos_sin_cachec                 C   sn   || j kr| j||j|jd | jd d d d d |df j|jd| jd d d d d |df j|jdfS )Nre   .)r    )ro   rl   r2   r    rm   r9   rn   )rN   xrf   r-   r-   r.   rY      s
    
&&zMistralRotaryEmbedding.forward)r`   ra   N)N)r[   r\   r]   rI   rl   rY   r^   r-   r-   rQ   r.   r_      s   
r_   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr   rS   r6   )shaper#   r:   )rs   x1Zx2r-   r-   r.   rotate_half   s    rv   c                 C   sl   | d d}| d d}|| d}|| d}| | t| |  }|| t||  }||fS )Nr   r   )squeeze	unsqueezerv   )qkrp   rq   position_idsZq_embedZk_embedr-   r-   r.   apply_rotary_pos_emb   s    r|   c                       s$   e Zd Z fddZdd Z  ZS )
MistralMLPc                    sr   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)rH   rI   configrO   Zintermediate_sizer   Linear	gate_projup_proj	down_projr   Z
hidden_actact_fnrN   r   rQ   r-   r.   rI      s    
zMistralMLP.__init__c                 C   s    |  | | || | S N)r   r   r   r   )rN   rs   r-   r-   r.   rY      s    zMistralMLP.forwardrZ   r-   r-   rQ   r.   r}      s   
r}   )rW   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)rt   r;   reshape)rW   r   batchnum_key_value_headsslenhead_dimr-   r-   r.   	repeat_kv   s
    0r   c                       s   e Zd ZdZed fddZejeedddZ	deje
ej e
ej e
eej  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".
    r   c                    s
  t    || _|j| _|j| _| j| j | _|j| _| j| j | _|j	| _	|j
| _
| j| j | jkrt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?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fr   )rg   rh   )rH   rI   r   rO   Znum_attention_heads	num_headsr   r   num_key_value_groupsrg   Z
rope_theta
ValueErrorr   r   q_projk_projv_projo_projr_   
rotary_embr   rQ   r-   r.   rI      s,    
zMistralAttention.__init__)r>   rf   r<   c                 C   s    | ||| j| jdd S )Nr   rS   )viewr   r   	transpose
contiguous)rN   r>   rf   r<   r-   r-   r.   _shape   s    zMistralAttention._shapeNFrW   attention_maskr{   past_key_valueoutput_attentions	use_cacher+   r   c                 C   sn  |  \}}	}
| |}| |}| |}|||	| j| jdd}|||	| j| jdd}|||	| j| jdd}|j	d }|d k	r||d j	d 7 }| j
||d\}}t|||||\}}|d k	rtj|d |gdd}tj|d |gdd}|r||fnd }t|| j}t|| j}t||ddt| j }|  || j|	|fkrtd|| j|	|f d	|   |d k	r|  |d|	|fkrtd
|d|	|f d	|   || }tjj|dtjd|j}t||}|  || j|	| jfkr0td|| j|	| jf d	|   |dd }|||	| j}| |}|sdd }|||fS )Nr   rS   r   rf   r6   r
   z$Attention weights should be of size z	, but is z!Attention mask should be of size r   r   z `attn_output` should be of size )rB   r   r   r   r   r   r   r   r   rt   r   r|   r#   r:   r   r   matmulmathsqrtr   r   
functionalZsoftmaxrT   r9   r    r   r   rO   r   )rN   rW   r   r{   r   r   r   r+   r<   q_len_query_states
key_statesvalue_states
kv_seq_lenrp   rq   attn_weightsattn_outputr-   r-   r.   rY      sR    




 

zMistralAttention.forward)NNNFFN)r[   r\   r]   __doc__r   rI   r#   Tensorintr   r   
LongTensorr   rC   rY   r^   r-   r-   rQ   r.   r      s&         r   c                	   @   s\   e Zd ZdZdejeej eej eeej  e	e	eej dddZ
ddd	Zd
d Zd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.
    NFrW   r   r{   r   r   r   r+   c              	   C   s(  |  \}}	}
| |}| |}| |}|||	| j| jdd}|||	| j| jdd}|||	| j| jdd}|j	d }|d k	r||d j	d 7 }t
||d d df 
  d }| j||d\}}t|||||\}}tot| jdd k	o|| jjk}ts td |d k	rLt| jdr || jjkr || 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 k	r |d d |d f }tj|t|d d dd f gdd
}tj|d |gdd
}tj|d |gdd
}|rZ||fnd }t|| j}t|| j}d}|j}|tjkrtd |tj}|tj}|tj}|dd}|dd}|dd}| j|||||	||d}| ||	| j! }| "|}|sd }|||fS )Nr   rS   r   r   r   r   r4   zThe current flash attention version does not support sliding window attention, for a more memory efficient implementation make sure to upgrade flash-attn library.zepast key much have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got r6           zThe 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 float16.)dropoutuse_sliding_windows)#rB   r   r   r   r   r   r   r   r   rt   r&   r'   r   r|   _flash_supports_window_sizehasattrr   r4   loggerwarning_oncer   r   r#   r:   Z	ones_liker   r   r    rT   r9   Zfloat16_flash_attention_forwardr   rO   r   )rN   rW   r   r{   r   r   r   r+   r<   r   r   r   r   r   r   Zrotary_seq_lenrp   rq   r   Zslicing_tokensZpast_keyZ
past_valueZdropout_raterX   r   r   r-   r-   r.   rY   J  s    




"

$$

(

zMistralFlashAttention2.forwardr   c	                 C   s   |dk	r|j d }	| |||||\}}}}
}}|\}}|\}}|sbt|||||||||dd
}n*t|||||||||d| jj| jjfd}t||
|	|}n<|st|||||dd}n"t|||||d| 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
            padding_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.
        Nr   T)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   )rt   _upad_inputr   r   r4   r   r   )rN   r   r   r   r+   query_lengthr   r   r   
batch_size	indices_qZcu_seq_lensZmax_seq_lensr   r   max_seqlen_in_batch_qmax_seqlen_in_batch_kZattn_output_unpadr   r-   r-   r.   r     sr    !
         
z/MistralFlashAttention2._flash_attention_forwardc                 C   s&  |j \}}}}	||j d kr>|j d }
|d d |
| d f }t|\}}}t||| ||	|}t||| ||	|}||krt||| ||	|}|}|}|}nd|dkrd}tj|d tj|jd}|d d }|d}n(|d d | d f }t	||\}}}}||||||f||ffS )Nr   r   r5   )
rt   r/   r   r   r#   ri   r$   r2   rw   r   )rN   Zquery_layerZ	key_layerZvalue_layerr+   r   r   r   r   r   Zpadding_mask_num_tokensZ	indices_kr   r   r   r   r   r-   r-   r.   r     sB    
   z"MistralFlashAttention2._upad_input)NNNFFN)r   NF)r[   r\   r]   r   r#   r   r   r   r   rC   rY   r   r   r-   r-   r-   r.   r   C  s*   	      |   
Yr   c                       s   e Zd Zed fddZd	ejeej eej ee	ej  ee
 ee
 eej e	ejee	ejejf  f dddZ  ZS )
MistralDecoderLayerr   c                    sd   t    |j| _t|dds(t|dnt|| _t|| _t	|j|j
d| _t	|j|j
d| _d S )N_flash_attn_2_enabledFr   rP   )rH   rI   rO   getattrr   r   	self_attnr}   mlprF   rms_norm_epsinput_layernormpost_attention_layernormr   rQ   r-   r.   rI   D  s    


zMistralDecoderLayer.__init__NFr   c              	   C   sz   |}|  |}| j|||||||d\}}	}
|| }|}| |}| |}|| }|f}|rh||	f7 }|rv||
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, 1, tgt_len, src_len)` where padding elements are indicated by very large negative 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.
            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
        r   )r   r   r   r   )rN   rW   r   r{   r   r   r   r+   ZresidualZself_attn_weightsZpresent_key_valueoutputsr-   r-   r.   rY   P  s,    
	



zMistralDecoderLayer.forward)NNNFFN)r[   r\   r]   r   rI   r#   r   r   r   r   rC   FloatTensorrY   r^   r-   r-   rQ   r.   r   C  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                   @   s8   e Zd ZeZdZdZdgZdZdZ	dd Z
d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   )rV   std)r   Zinitializer_range
isinstancer   r   rL   dataZnormal_r   Zzero_	Embeddingpadding_idx)rN   moduler   r-   r-   r.   _init_weights  s    

z$MistralPreTrainedModel._init_weightsFc                 C   s   t |tr||_d S r   )r   MistralModelgradient_checkpointing)rN   r   valuer-   r-   r.   _set_gradient_checkpointing  s    
z2MistralPreTrainedModel._set_gradient_checkpointingN)F)r[   r\   r]   r   config_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2r   r   r-   r-   r-   r.   r     s   r   aV  
    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.
        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d	d
 Ze	e
dejeej eej eeej  eej ee ee ee ee eeef d
ddZ  ZS )r   z
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]

    Args:
        config: MistralConfig
    r   c                    sv   t     j| _ j| _t j j| j| _t	 fddt
 jD | _t j jd| _d| _|   d S )Nc                    s   g | ]}t  qS r-   )r   ).0r   r   r-   r.   
<listcomp>  s     z)MistralModel.__init__.<locals>.<listcomp>r   F)rH   rI   pad_token_idr   
vocab_sizer   r   rO   embed_tokensZ
ModuleListrangeZnum_hidden_layerslayersrF   r   normr   	post_initr   rQ   r   r.   rI     s     zMistralModel.__init__c                 C   s   | j S r   r   rN   r-   r-   r.   get_input_embeddings  s    z!MistralModel.get_input_embeddingsc                 C   s
   || _ d S r   r   rN   r   r-   r-   r.   set_input_embeddings  s    z!MistralModel.set_input_embeddingsc                 C   sb   d }|d dkr&t ||j|j||d}|d k	r^t||j|d d|j}|d krV|n|| }|S )Nr   r   )r2   r3   r4   )r=   )r@   r    r2   rE   r9   )rN   r   Zinput_shapeinputs_embedsr3   r4   Zcombined_attention_maskZexpanded_attn_maskr-   r-   r.   _prepare_decoder_attention_mask  s     z,MistralModel._prepare_decoder_attention_maskN)
	input_idsr   r{   r   r   r   r   output_hidden_statesreturn_dictr   c
              
      sB   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	rj|d k	rjtdn2|d k	r~|j\}
}n|d k	r|j\}
}}ntd|}d}|d k	r|d d jd }|| }|d kr|d k	r|jn|j}tj	||| tj
|d}|dd|}n|d|
 }|d kr4| |}d |d kr\tj|
|ftj|jd}nd|krj|d k	rt| j dr| j jrd d df   |
k}|rtd| j||
|f||| j jd	}|}| jr| jr|rtd
 d}|rdnd } rdnd }|r dnd }t| jD ]\}}|rF||f7 }|d k	rX|| nd | jr| jr fdd}tjj|||||}n|||| |d}|d }|r|| rdnd f7 } r.||d f7 }q.| |}|r||f7 }|r|nd }|	s2t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   rS   r5   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. )r4   zZ`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...Fr-   c                    s    fdd}|S )Nc                     s    | fdiS )Nr+   r-   )inputs)r   r   r+   r   r-   r.   custom_forward  s    zKMistralModel.forward.<locals>.create_custom_forward.<locals>.custom_forwardr-   )r   r   r   r+   r   )r   r.   create_custom_forward  s    z3MistralModel.forward.<locals>.create_custom_forward)r   r{   r   r   r   r+   r   c                 s   s   | ]}|d k	r|V  qd S r   r-   )r   vr-   r-   r.   	<genexpr>  s      z'MistralModel.forward.<locals>.<genexpr>)Zlast_hidden_stater   rW   
attentions)!r   r   r   r   use_return_dictr   rt   r2   r#   ri   longrx   r   r   rK   rC   r   r   r"   r'   r   r4   r   Ztrainingr   r   	enumerater   utils
checkpointr   tupler   )rN   r   r   r{   r   r   r   r   r   r   r   Z
seq_lengthr   Zseq_length_with_pastr3   r2   Zis_padding_rightrW   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheidxZdecoder_layerr   Zlayer_outputsZ
next_cacher-   r   r.   rY   /  s    

   


  





zMistralModel.forward)	NNNNNNNNN)r[   r\   r]   r   r   rI   r   r   r   r   MISTRAL_INPUTS_DOCSTRINGr#   r   r   r   r   r   rC   r   r   r   rY   r^   r-   r-   rQ   r.   r     s6            
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j  eej eej ee ee ee ee eeef dddZdddZedd Z  ZS )MistralForCausalLMzlm_head.weightc                    s@   t  | t|| _|j| _tj|j|jdd| _| 	  d S r~   )
rH   rI   r   r   r   r   r   rO   lm_headr   r   rQ   r-   r.   rI     s
    
zMistralForCausalLM.__init__c                 C   s   | j jS r   r   r   r   r-   r-   r.   r     s    z'MistralForCausalLM.get_input_embeddingsc                 C   s   || j _d S r   r  r   r-   r-   r.   r     s    z'MistralForCausalLM.set_input_embeddingsc                 C   s   | j S r   r
  r   r-   r-   r.   get_output_embeddings  s    z(MistralForCausalLM.get_output_embeddingsc                 C   s
   || _ d S r   r  )rN   Znew_embeddingsr-   r-   r.   set_output_embeddings  s    z(MistralForCausalLM.set_output_embeddingsc                 C   s
   || _ d S r   r   )rN   decoderr-   r-   r.   set_decoder  s    zMistralForCausalLM.set_decoderc                 C   s   | j S r   r  r   r-   r-   r.   get_decoder  s    zMistralForCausalLM.get_decoder)output_typer   Nr   r   r{   r   r   labelsr   r   r   r   r   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  }t }|	d| j j
}|	d}||j}|||}|
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(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)	r   r   r{   r   r   r   r   r   r   r   .r   r   losslogitsr   rW   r   )r   r   r   r  r   r
  rj   r   r   r   r   r9   r2   r   r   rW   r   )rN   r   r   r{   r   r   r  r   r   r   r   r   rW   r  r  Zshift_logitsZshift_labelsloss_fctoutputr-   r-   r.   rY     sJ    )


zMistralForCausalLM.forwardc                 K   s   |r|d d dd f }| dd }|d k	rp|d krp| dd }||dkd |rp|d d df d}|d k	r|d krd|i}nd|i}|||| d|d |S )	Nr   r{   r   r   r   r   r   )r{   r   r   r   )getr  r*   Zmasked_fill_rx   update)rN   r   r   r   r   kwargsr{   Zmodel_inputsr-   r-   r.   prepare_inputs_for_generation>  s&    
z0MistralForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ] }|t  fdd|D f7 }q|S )Nr-   c                 3   s"   | ]}| d  |jV  qdS )r   N)Zindex_selectr9   r2   )r   Z
past_statebeam_idxr-   r.   r   a  s     z4MistralForCausalLM._reorder_cache.<locals>.<genexpr>)r  )r   r   Zreordered_pastZ
layer_pastr-   r  r.   _reorder_cache\  s    z!MistralForCausalLM._reorder_cache)
NNNNNNNNNN)NNN)r[   r\   r]   Z_tied_weights_keysrI   r   r   r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr#   r   r   r   r   r   rC   r   r   rY   r  staticmethodr!  r^   r-   r-   rQ   r.   r	    sN   	
          
X     
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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 ) MistralForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r~   )
rH   rI   
num_labelsr   r   r   r   rO   scorer   r   rQ   r-   r.   rI   w  s
    
z)MistralForSequenceClassification.__init__c                 C   s   | j jS r   r  r   r-   r-   r.   r     s    z5MistralForSequenceClassification.get_input_embeddingsc                 C   s   || j _d S r   r  r   r-   r-   r.   r     s    z5MistralForSequenceClassification.set_input_embeddingsNr  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}n4|dk	rt|| j j	 
dd |j}nd}|tj||jd|f }d}|dk	r||j}| j jdkrR| jdkrd| j _n:| jdkrJ|jtj	ks@|jtjkrJd	| 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 )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)r   r{   r   r   r   r   r   r   r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r   )r2   Z
regressionZsingle_label_classificationZmulti_label_classificationr  )r   r  r   r&  rt   r   r   r#   eqr  Zargmaxr9   r2   ri   Zproblem_typer%  r    r   r	   rw   r   r   r   r   r   rW   r   )rN   r   r   r{   r   r   r  r   r   r   r   Ztransformer_outputsrW   r  r   Zsequence_lengthsZpooled_logitsr  r  r  r-   r-   r.   rY     sr    



(

z(MistralForSequenceClassification.forward)
NNNNNNNNNN)r[   r\   r]   rI   r   r   r   r  r#   r   r   r   r   r   rC   r   r   r   rY   r^   r-   r-   rQ   r.   r$  f  s6   	          
r$  )r   r0   )N)Ir   inspectr   typingr   r   r   r   r#   Ztorch.nn.functionalr   r   r(   Ztorch.utils.checkpointZtorch.nnr   r   r	   Zactivationsr   Zmodeling_outputsr   r   r   Zmodeling_utilsr   r  r   r   r   r   r   Zconfiguration_mistralr   Z
flash_attnr   r   Zflash_attn.bert_paddingr   r   r   list	signature
parametersr   Z
get_loggerr[   r   r"  r/   Sizer    r2   r   r@   r   rE   ModulerF   r_   rv   r|   r}   r   r   r   r   ZMISTRAL_START_DOCSTRINGr   r  r   r	  r$  r-   r-   r-   r.   <module>   sz   
  %n  F@ N  