o
    h                     @   sH  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!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( e# rddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/ de0e1e*j2v Z3e%4e5Z6dZ7dd Z8G dd dej9Z:G dd dej9Z;dd Z<d7ddZ=G dd dej9Z>de	j?d e@d!e	j?fd"d#ZAG d$d% d%ej9ZBG d&d' d'eBZCeBeCd(ZDG d)d* d*ej9ZEd+ZFe!d,eFG d-d. d.eZGd/ZHe!d,eFG d0d1 d1eGZIG d2d3 d3eGZJe!d4eFG d5d6 d6eGZKdS )8z PyTorch Mistral model.    N)ListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)!_prepare_4d_causal_attention_mask)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)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_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int32nonzeroflattenmaxitemFpadcumsum)attention_maskseqlens_in_batchindicesmax_seqlen_in_batch
cu_seqlens r5   b/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/mistral/modeling_mistral.py_get_unpad_data=   s   r7   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__r5   r6   r;   K   s   

zMistralRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   r!   T)keepdim)	r$   tor'   float32powmeanrsqrtr?   r>   )r@   hidden_statesinput_dtypevariancer5   r5   r6   forwardS   s
   zMistralRMSNorm.forward)r9   __name__
__module____qualname__r;   rO   __classcell__r5   r5   rC   r6   r8   J   s    r8   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 )Ng      ?r   rE   inv_freqF
persistentseq_lendevicer$   )r:   r;   r#   max_position_embeddingsbaser'   arangefloatrG   register_buffer_set_cos_sin_cacherX   r]   get_default_dtype)r@   r#   r^   r_   r]   rX   rC   r5   r6   r;   ]   s   
*
zMistralRotaryEmbedding.__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)r]   r$   r!   r#   
cos_cachedFrY   
sin_cached)max_seq_len_cachedr'   r`   rX   r$   outercatrb   cosrG   sin)r@   r\   r]   r$   tfreqsembr5   r5   r6   rc   k   s   z)MistralRotaryEmbedding._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 )Nr[   )r$   )rh   rc   r]   r$   rf   rG   rg   )r@   xr\   r5   r5   r6   rO   u   s
   
zMistralRotaryEmbedding.forward)rV   rW   NN)rQ   rR   rS   r;   rc   rO   rT   r5   r5   rC   r6   rU   \   s    
rU   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!   rE   re   )shaper'   rj   )rp   x1x2r5   r5   r6   rotate_half   s   ru   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.
    )	unsqueezeru   )qkrk   rl   position_idsunsqueeze_dimq_embedk_embedr5   r5   r6   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)r:   r;   configrA   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fnr@   r   rC   r5   r6   r;      s   
zMistralMLP.__init__c                 C   s    |  | | || | S rq   )r   r   r   r   )r@   rp   r5   r5   r6   rO          zMistralMLP.forwardrP   r5   r5   rC   r6   r~      s    
r~   rL   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)rr   expandreshape)rL   r   batchnum_key_value_headsslenhead_dimr5   r5   r6   	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 )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".
    Nr   	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).Fr   )r^   r_   )r:   r;   r   r   loggerwarning_oncerD   rQ   rA   num_attention_heads	num_headsr   r   num_key_value_groupsr^   
rope_theta	is_causalattention_dropout
ValueErrorr   r   q_projk_projv_projo_projrU   
rotary_embr@   r   r   rC   r5   r6   r;      s>   

zMistralAttention.__init__tensorr\   bszc                 C   s    | ||| j| jdd S )Nr   rE   )viewr   r   	transpose
contiguous)r@   r   r\   r   r5   r5   r6   _shape   r   zMistralAttention._shapeFrL   r0   ry   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   rE   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.r\   rl   rk   r
   z$Attention weights should be of size z	, but is z!Attention mask should be of size r!   r"   )ptrainingz `attn_output` should be of size )'warningswarnsizer   r   r   r   r   r   r   r   rr   r   r   rD   rQ   get_usable_lengthr   r}   updater   r   r'   matmulmathsqrtr   
functionalsoftmaxrH   rG   r$   dropoutr   r   r   r   rA   r   )r@   rL   r0   ry   r   r   r   kwargsr   q_len_query_states
key_statesvalue_states
kv_seq_lenrk   rl   cache_kwargsattn_weightsattn_outputr5   r5   r6   rO      sj   






 

zMistralAttention.forwardrq   NNNFF)rQ   rR   rS   __doc__r   r   intr;   r'   Tensorr   
LongTensorr   boolr   rO   rT   r5   r5   rC   r6   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 )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|i | t  | _d S rq   )r:   r;   r   _flash_attn_uses_top_left_mask)r@   argsr   rC   r5   r6   r;   I  s   zMistralFlashAttention2.__init__NFrL   r0   ry   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   rE   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 re   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   rr   r   r   r+   r,   r   r}   _flash_supports_window_sizegetattrr   r   r   r   r   r   r'   rj   	ones_liker   r   r   r   r   r$   rH   hasattrr   r>   rG   _flash_attention_forwardr   rA   r   )r@   rL   r0   ry   r   r   r   r   r   r   r   r   r   r   r   rotary_seq_lenrk   rl   r   slicing_tokenspast_key
past_valuer   dropout_raterM   target_dtyper   r   r5   r5   r6   rO   Q  s   





"

"$$
(








zMistralFlashAttention2.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   rr   _upad_inputr   r   r   r   r   )r@   r   r   r   r0   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   r5   r5   r6   r     st    


z/MistralFlashAttention2._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   r$   r]   )
rr   r7   r   r   r'   r`   r(   r]   squeezer   )r@   query_layer	key_layervalue_layerr0   r   r   r   r   r   attention_mask_num_tokens	indices_kr   r   r   r   r   r5   r5   r6   r   1  s<   
z"MistralFlashAttention2._upad_inputr   )r   NF)rQ   rR   rS   r   r;   r'   r   r   r   r   r   rO   r   r   rT   r5   r5   rC   r6   r   A  s6    
 
dr   )eagerflash_attention_2c                       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jee
ejejf  f fddZ  ZS )MistralDecoderLayerr   r   c                    sV   t    |j| _t|j ||| _t|| _t|j|j	d| _
t|j|j	d| _d S )NrB   )r:   r;   rA   MISTRAL_ATTENTION_CLASSES_attn_implementation	self_attnr~   mlpr8   rms_norm_epsinput_layernormpost_attention_layernormr   rC   r5   r6   r;   c  s   

zMistralDecoderLayer.__init__NFrL   r0   ry   r   r   r   r   c                 K   s   d|v r	t d 	 |}| |}| j||||||d\}}	}
|| }|}| |}| |}|| }|f}|r=||	f7 }|rD||
f7 }|S )Nr   r   )rL   r0   ry   r   r   r   )r   r   r  r  r  r  )r@   rL   r0   ry   r   r   r   r   residualself_attn_weightspresent_key_valueoutputsr5   r5   r6   rO   m  s4   





zMistralDecoderLayer.forwardr   )rQ   rR   rS   r   r   r;   r'   r   r   r   r   r   FloatTensorrO   rT   r5   r5   rC   r6   r   b  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                   @   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 )MistralPreTrainedModel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   )rJ   std)r   initializer_range
isinstancer   r   r>   datanormal_r   zero_	Embeddingpadding_idx)r@   moduler  r5   r5   r6   _init_weights  s   

z$MistralPreTrainedModel._init_weightsN)rQ   rR   rS   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_cache_classr  r5   r5   r5   r6   r    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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ef fddZ  ZS )MistralModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]

    Args:
        config: MistralConfig
    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 r5   )r   ).0r   r   r5   r6   
<listcomp>,  s    z)MistralModel.__init__.<locals>.<listcomp>r   r   F)r:   r;   pad_token_idr  
vocab_sizer   r  rA   embed_tokens
ModuleListrangenum_hidden_layerslayersr  _use_flash_attention_2r8   r  normgradient_checkpointing	post_initr   rC   r"  r6   r;   %  s   zMistralModel.__init__c                 C      | j S rq   r&  r@   r5   r5   r6   get_input_embeddings5     z!MistralModel.get_input_embeddingsc                 C   
   || _ d S rq   r0  r@   valuer5   r5   r6   set_input_embeddings8     
z!MistralModel.set_input_embeddingsN	input_idsr0   ry   r  inputs_embedsr   r   output_hidden_states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r4|d ur4td|d ur>|j\}
}n|d urI|j\}
}}ntdd}|rct|t }|r^t	
|}||}|d u r|d urn|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 }d }| jD ]B}|r||f7 }| jr| jr| |j||||||}n
|||||||d}|d }|r,||r)dnd }|r6||d f7 }q| |}|rD||f7 }d }|rR|rP|  n|}|	sbt!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 Mistral. 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`...Fr5   )r0   ry   r   r   r   rE   r   c                 s   s    | ]	}|d ur|V  qd S rq   r5   )r!  vr5   r5   r6   	<genexpr>  s    z'MistralModel.forward.<locals>.<genexpr>)last_hidden_stater  rL   
attentions)#r   r   r;  r   use_return_dictr   rr   r  r   r   from_legacy_cacher   r]   r'   r`   longrv   r   r&  r+  r&   r,   r   r   r-  r   r   r   r*  _gradient_checkpointing_func__call__r,  to_legacy_cachetupler   )r@   r9  r0   ry   r  r:  r   r   r;  r<  r   
seq_lengthr   past_key_values_lengthuse_legacy_cacher]   is_padding_rightrL   all_hidden_statesall_self_attnsnext_decoder_cachedecoder_layerlayer_outputs
next_cacher5   r5   r6   rO   ;  s   





	

zMistralModel.forward)	NNNNNNNNN)rQ   rR   rS   r   r   r;   r2  r7  r   MISTRAL_INPUTS_DOCSTRINGr'   r   r   r   r   r  r   r   r   r   rO   rT   r5   r5   rC   r6   r     sH    	

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#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	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   )
r:   r;   r   r  r%  r   r   rA   lm_headr.  r   rC   r5   r6   r;     s
   
zMistralForCausalLM.__init__c                 C      | j jS rq   r  r&  r1  r5   r5   r6   r2       z'MistralForCausalLM.get_input_embeddingsc                 C      || j _d S rq   rV  r5  r5   r5   r6   r7       z'MistralForCausalLM.set_input_embeddingsc                 C   r/  rq   rT  r1  r5   r5   r6   get_output_embeddings  r3  z(MistralForCausalLM.get_output_embeddingsc                 C   r4  rq   rZ  )r@   new_embeddingsr5   r5   r6   set_output_embeddings  r8  z(MistralForCausalLM.set_output_embeddingsc                 C   r4  rq   r  )r@   decoderr5   r5   r6   set_decoder  r8  zMistralForCausalLM.set_decoderc                 C   r/  rq   r^  r1  r5   r5   r6   get_decoder  r3  zMistralForCausalLM.get_decoder)output_typer  Nr9  r0   ry   r  r:  labelsr   r   r;  r<  r   c                 C   s&  |dur|n| j j}|	dur|	n| j j}	|
dur|
n| j j}
| j||||||||	|
d	}|d }| |}| }d}|durq|dddddf  }|dddf  }t }|	d| j j
}|	d}||j}|||}|
s|f|dd  }|du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)	r9  r0   ry   r  r:  r   r   r;  r<  r   .r!   r   losslogitsr  rL   r@  )r   r   r;  rA  r  rT  ra   r   r   r   r%  rG   r]   r   r  rL   r@  )r@   r9  r0   ry   r  r:  rc  r   r   r;  r<  r
  rL   rf  re  shift_logitsshift_labelsloss_fctoutputr5   r5   r6   rO     sJ   )


zMistralForCausalLM.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   rE   r   ry   r!   r:  r9  r   )ry   r  r   r0   )r  r   get_seq_lengthseen_tokensget_max_lengthrr   getrC  r/   masked_fill_r   )r@   r9  r  r0   r:  r   cache_lengthpast_lengthmax_cache_lengthry   model_inputsr5   r5   r6   prepare_inputs_for_generation=  s@   

"
z0MistralForCausalLM.prepare_inputs_for_generationc                    s.   d}| D ]}|t  fdd|D f7 }q|S )Nr5   c                 3   s$    | ]}| d  |jV  qdS )r   N)index_selectrG   r]   )r!  
past_statebeam_idxr5   r6   r>  {  s   " z4MistralForCausalLM._reorder_cache.<locals>.<genexpr>)rG  )r  rx  reordered_past
layer_pastr5   rw  r6   _reorder_cachev  s   z!MistralForCausalLM._reorder_cache
NNNNNNNNNN)NNN)rQ   rR   rS   _tied_weights_keysr;   r2  r7  r[  r]  r`  ra  r   rR  r   r   _CONFIG_FOR_DOCr'   r   r   r   r   r  r   r   r   rO   rt  staticmethodr{  rT   r5   r5   rC   r6   rS    s`    	
	

X
9rS  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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 ) MistralForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r   )
r:   r;   
num_labelsr   r  r   r   rA   scorer.  r   rC   r5   r6   r;     s
   
z)MistralForSequenceClassification.__init__c                 C   rU  rq   rV  r1  r5   r5   r6   r2    rW  z5MistralForSequenceClassification.get_input_embeddingsc                 C   rX  rq   rV  r5  r5   r5   r6   r7    rY  z5MistralForSequenceClassification.set_input_embeddingsNr9  r0   ry   r  r:  rc  r   r   r;  r<  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)r0   ry   r  r:  r   r   r;  r<  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r!   )r]   
regressionsingle_label_classificationmulti_label_classificationrd  )r   rA  r  r  rr   r$  r   r'   eqr   argmaxrG   r]   r`   problem_typer  r$   rC  r	   r   r   r   r   r   r  rL   r@  )r@   r9  r0   ry   r  r:  rc  r   r   r;  r<  transformer_outputsrL   rf  r   sequence_lengthspooled_logitsre  ri  rj  r5   r5   r6   rO     sr   



"


z(MistralForSequenceClassification.forwardr|  )rQ   rR   rS   r;   r2  r7  r   rR  r'   r   r   r   r   r  r   r   r   r   rO   rT   r5   r5   rC   r6   r    sL    		

r  )r   )Lr   inspectr   r   typingr   r   r   r   r'   torch.nn.functionalr   r   r-   torch.utils.checkpointtorch.nnr   r   r	   activationsr   cache_utilsr   r   modeling_attn_mask_utilsr   modeling_outputsr   r   r   modeling_utilsr   utilsr   r   r   r   r   r   configuration_mistralr   
flash_attnr   r   flash_attn.bert_paddingr   r   r   list	signature
parametersr   
get_loggerrQ   r   r~  r7   Moduler8   rU   ru   r}   r~   r   r   r   r   r   r   r   MISTRAL_START_DOCSTRINGr  rR  r   rS  r  r5   r5   r5   r6   <module>   sv    
%
   GF * ;