
    %	&hv                        d dl mZ d dlmZmZmZmZmZ d dlZd dl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 dd
lmZ ddlmZmZmZmZmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z. ddl/m0Z0  e+jb                  e2      Z3dZ4dZ5 G d de	jl                        Z7d Z8dAdZ9dejt                  de;dejt                  fdZ<	 dBde	jl                  dejt                  dejt                  d ejt                  d!eejt                     d"e=d#e=fd$Z> G d% d&e	jl                        Z? G d' d(e	jl                        Z@ G d) d*e	jl                        ZA G d+ d,e	jl                        ZBd-ZC e(d.eC       G d/ d0e"             ZDd1ZE e(d.eC       G d2 d3eD             ZF G d4 d5ee&      ZG G d6 d7eDe      ZH e(d8eC       G d9 d:eD             ZI e(d;eC       G d< d=eD             ZJ e(d>eC       G d? d@eD             ZKy)C    )partial)CallableListOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsadd_code_sample_docstringsadd_start_docstrings%add_start_docstrings_to_model_forwardcan_return_tupleloggingreplace_return_docstrings)deprecate_kwarg   )MistralConfigzmistralai/Mistral-7B-v0.1r&   c                   $     e Zd Z fdZd Z xZS )
MistralMLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _	        t        |j                     | _        y NFbias)super__init__confighidden_sizeintermediate_sizer	   Linear	gate_projup_proj	down_projr   
hidden_actact_fnselfr/   	__class__s     /var/www/pru.catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/mistral/modeling_mistral.pyr.   zMistralMLP.__init__0   s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../    c                     | j                  | j                  | j                  |            | j                  |      z        }|S N)r5   r7   r3   r4   )r9   xr5   s      r;   forwardzMistralMLP.forward:   s6    NN4;;t~~a/@#ADLLQRO#ST	r<   )__name__
__module____qualname__r.   r@   __classcell__r:   s   @r;   r(   r(   /   s    0r<   r(   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..N   dim)shapetorchcat)r?   x1x2s      r;   rotate_halfrP   ?   sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r<   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||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.
    )	unsqueezerP   )qkcossinposition_idsunsqueeze_dimq_embedk_embeds           r;   apply_rotary_pos_embr[   F   sY    ( --
&C
--
&C3w;q>C/0G3w;q>C/0GGr<   hidden_statesn_repreturnc                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      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)rK   expandreshape)r\   r]   batchnum_key_value_headsslenhead_dims         r;   	repeat_kvrf   a   so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr<   modulequerykeyvalueattention_maskscalingdropoutc                 T   t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
|#|d d d d d d d |j
                  d   f   }|
|z   }
t        j                  j                  |
dt        j                        j                  |j                        }
t        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )NrH   r
   rG   )rJ   dtype)ptrainingr%   )rf   num_key_value_groupsrL   matmul	transposerK   r	   
functionalsoftmaxfloat32torp   rm   rr   
contiguous)rg   rh   ri   rj   rk   rl   rm   kwargs
key_statesvalue_statesattn_weightscausal_maskattn_outputs                r;   eager_attention_forwardr   m   s    3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#k1==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r<   c                   6    e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   de
ej                     de
e   d	e
ej                     d
ee   de	ej                  e
ej                     e
e	ej                        f   fdZ xZS )MistralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr/   	layer_idxc                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |j                  | _        d| _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j                  |j                  | j                  z  |j
                  d      | _        y )Nre   g      TFr+   )r-   r.   r/   r   getattrr0   num_attention_headsre   rc   rs   rl   attention_dropout	is_causalr	   r2   q_projk_projv_projo_projr9   r/   r   r:   s      r;   r.   zMistralAttention.__init__   s,   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii 2 2F4N4NQUQ^Q^4^ejkii 2 2F4N4NQUQ^Q^4^ejkii 2 2F4N4NQUQ^Q^4^ejkii : :T]] JFL^L^ejkr<   r\   position_embeddingsrk   past_key_valuecache_positionr{   r^   c           
         |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }|\  }}t        |	|
||      \  }	}
|'|||d}|j                  |
|| j                  |      \  }
}t        }| j                  j                  dk7  r^| j                  j                  dk(  r(|j                  dd      rt        j                  d	       nt         | j                  j                     } || |	|
||f| j"                  sd
n| j$                  | j&                  t)        | j                  dd       d|\  }} |j*                  g |d j-                         }| j/                  |      }||fS )NrG   r%   rH   )rV   rU   r   eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        sliding_window)rm   rl   r   )rK   re   r   viewru   r   r   r[   updater   r   r/   _attn_implementationgetloggerwarning_oncer   rr   r   rl   r   ra   rz   r   )r9   r\   r   rk   r   r   r{   input_shapehidden_shapequery_statesr|   r}   rU   rV   cache_kwargsattention_interfacer   r~   s                     r;   r@   zMistralAttention.forward   s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j%#&snUL'5'<'<ZW[WeWegs't$J(?;;++w6{{//69fjjI\^c>d##L
 '>dkk>^>^&_#$7
%
  $}}C$2H2HLL"4;;0@$G
%
 
%
!\ *k));;;;FFHkk+.L((r<   )NN)rA   rB   rC   __doc__r&   intr.   rL   Tensorr   r   r   
LongTensorr   r   r@   rD   rE   s   @r;   r   r      s    Gl} l l& +/590)||0) #5<<#=>0) !.	0)
 !0) !!1!120) -.0) 
u||Xell3XeELL>Q5RR	S0)r<   r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )MistralRMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        MistralRMSNorm is equivalent to T5LayerNorm
        N)r-   r.   r	   	ParameterrL   onesweightvariance_epsilon)r9   r0   epsr:   s      r;   r.   zMistralRMSNorm.__init__   s1     	ll5::k#:; #r<   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )NrH   rG   T)keepdim)	rp   ry   rL   rx   powmeanrsqrtr   r   )r9   r\   input_dtypevariances       r;   r@   zMistralRMSNorm.forward   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r<   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler   rK   r   r9   s    r;   
extra_reprzMistralRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr<   )gư>)rA   rB   rC   r.   r@   r   rD   rE   s   @r;   r   r      s    $;Jr<   r   c                   p    e Zd Zdedef fdZ	 	 	 	 	 	 	 ddej                  deej                     deej                     dee
   dee   d	ee   d
eej                     deeej                  ej                  f      dee   deej                  eeej                  ej                  f      f   fdZ xZS )MistralDecoderLayerr/   r   c                     t         |           |j                  | _        t        ||      | _        t        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y )N)r/   r   r   )r-   r.   r0   r   	self_attnr(   mlpr   rms_norm_epsinput_layernormpost_attention_layernormr   s      r;   r.   zMistralDecoderLayer.__init__   sl    !--)9Mf%-f.@.@fFYFYZ(6v7I7IvObOb(c%r<   r\   rk   rW   r   r   	use_cacher   r   r{   r^   c	                     |}
| j                  |      } | j                  d||||||||d|	\  }}|
|z   }|}
| j                  |      }| j                  |      }|
|z   }|f}|r||fz  }|S )N)r\   rk   rW   r   r   r   r   r    )r   r   r   r   )r9   r\   rk   rW   r   r   r   r   r   r{   residualself_attn_weightsoutputss                r;   r@   zMistralDecoderLayer.forward   s     !,,]; ,:4>> 
,
')%)/) 3
,
 
,
(( !=0 !55mD/ =0 ")++Gr<   )NNNFFNN)rA   rB   rC   r&   r   r.   rL   r   r   r   r   boolr   r   r   FloatTensorr@   rD   rE   s   @r;   r   r      s   d} d d 2637*.,1$)59KO(||( !.( u//0	(
 !( $D>( D>( !!1!12( &eELL%,,,F&GH( -.( 
u  (51B1BEDUDU1U+V"WW	X(r<   r   c                   ^     e Zd Zddef fdZ ej                         ed               Z xZ	S )MistralRotaryEmbeddingr/   c                    t         |           t        |d      rG|j                  ;|j                  j	                  d|j                  j	                  d            | _        nd| _        |j                  | _        |j                  | _        || _	        t        | j
                     | _        | j                  | j                  |      \  }| _        | j                  d|d       | j                  | _        y )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)r-   r.   hasattrr   r   r   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr/   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r9   r/   devicer   r:   s       r;   r.   zMistralRotaryEmbedding.__init__  s    6>*v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q($(ZeD!%r<   c                 b   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        j                  |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   rG   r%   mpscpuF)device_typeenabledrH   rI   )rp   )r   floatr`   rK   ry   r   
isinstancer   strrL   autocastru   rM   rU   r   rV   rp   )
r9   r?   rW   inv_freq_expandedposition_ids_expandedr   freqsembrU   rV   s
             r;   r@   zMistralRotaryEmbedding.forward%  sV    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfk^^UC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s    BF%%F.r>   )
rA   rB   rC   r&   r.   rL   no_gradr   r@   rD   rE   s   @r;   r   r     s3    /} /" U]]_<  <r<   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                   F    e Zd ZeZdZdZdgZdgZdZ	dZ
dZdZdZdZdZd Zy)MistralPreTrainedModelmodelTr   past_key_valuesc                    | j                   j                  }t        |t        j                        rY|j
                  j                  j                  d|       |j                  %|j                  j                  j                          y y t        |t        j                        rf|j
                  j                  j                  d|       |j                  2|j
                  j                  |j                     j                          y y y )Nr   )r   std)r/   initializer_ranger   r	   r2   r   datanormal_r,   zero_	Embeddingpadding_idx)r9   rg   r   s      r;   _init_weightsz$MistralPreTrainedModel._init_weightsX  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> . .r<   N)rA   rB   rC   r&   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_flex_attn_supports_cache_class_supports_quantized_cache_supports_static_cache_supports_attention_backendr   r   r<   r;   r   r   F  sU    
 !L&*#./#4"5!N  $!"&	?r<   r   a$  
    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 `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`, *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`.

            It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

            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.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
c                       e Zd ZdZdef fdZd Zd Ze e	e
      	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     d	ee   d
eej                      dee   dee   dee   deej                     dee   defd              Z	 ddej                  dej                  dej                  d	edef
dZedej                  dededej2                  dej4                  dej                  deded	efd       Z xZS )MistralModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]

    Args:
        config: MistralConfig
    r/   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nr   )r/   F)r-   r.   pad_token_idr   
vocab_sizer	   r   r0   embed_tokens
ModuleListrangenum_hidden_layersr   layersr   r   normr   
rotary_embgradient_checkpointing	post_initr   s      r;   r.   zMistralModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammEJ6KcKcEde	 3e
 #6#5#56;N;NO	0?&+# 	 fs   Dc                     | j                   S r>   r	  r   s    r;   get_input_embeddingsz!MistralModel.get_input_embeddings  s       r<   c                     || _         y r>   r  r9   rj   s     r;   set_input_embeddingsz!MistralModel.set_input_embeddings  s
    !r<   	input_idsrk   rW   r   inputs_embedsr   r   output_hidden_statesr   flash_attn_kwargsr^   c
                 ^   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|d u |d uz  rt	        d      | j
                  r%| j                  r|rt        j                  d       d}t        |t        d       t        f      st	        d      || j                  |      }|r|
t               }|	F||j                         nd}t        j                   |||j"                  d   z   |j$                        }	||	j'                  d      }| j)                  |||	||      }|}| j+                  ||      }|rdnd }|rdnd }| j,                  d | j                   j.                   D ]r  }|r||fz  }| j
                  r:| j                  r.| j1                  t3        |j4                  fi |
|||||||	|	      }n ||f||||||	|d	|
}|d   }|sj||d   fz  }t | j7                  |      }|r||fz  }t9        ||r|nd ||
      S )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBThe `past_key_values` should be either a `Cache` object or `None`.r   r%   r   r   )rk   rW   r   r   r   r   r   )last_hidden_stater   r\   
attentions)r/   r   r  r   
ValueErrorr  rr   r   r   r   r   r   r	  r   get_seq_lengthrL   arangerK   r   rR   _update_causal_maskr  r  r  _gradient_checkpointing_funcr   __call__r  r   )r9   r  rk   rW   r   r  r   r   r  r   r  past_seen_tokensr   r\   r   all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                      r;   r@   zMistralModel.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I /DJ+>?abb  --i8M0*nO!CRC^==?de"\\ "2]5H5H5K"KTaThThN )33A6L..M>?L]
 & #oom\J #7BD0d![[)H4;;+H+HI  	6M#!m%55!**t}} $ A AM22H6GH! #%"'
! !.!
!#.!-#2&7'#1(;
! (
! *!,M =#3"55A 	6D 		-0  -!11&+/8Od+%	
 	
r<   input_tensorc                    | j                   j                  dk(  rS|H|F|d d df   j                         j                         |j	                         d   k7  }|rt        d      |d|v r|S y ||j                         nd}t        |t              }t        |t              }	| j                   j                  dk(  r?|s=|	s;|s9t        j                  |||| j                   j                  | j                        ry |j                  |j                  }}
t!        j"                  |
      j$                  }|j&                  d   }|	s|r|j)                         }n1t        |t         j*                        r|j&                  d   n||z   dz   }| j-                  ||||
|||j&                  d   | j                   |		      }| j                   j                  dk(  r2|0|j                  j.                  d
v r|st        j0                  ||      }|S )Nflash_attention_2rG   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  past_key_values_lengthr   is_trainingr%   )sequence_lengthtarget_lengthrp   r   r   
batch_sizer/   r   )cudaxpu)r/   r   sumitemsizer   r!  r   r   r   r   _ignore_causal_mask_sdpar   rr   rp   r   rL   finfominrK   get_max_cache_shaper   5_prepare_4d_causal_attention_mask_with_cache_positionr   _unmask_unattended)r9   rk   r+  r   r   r   is_padding_rightr&  using_static_cacheusing_sliding_window_cacherp   r   	min_dtyper0  r1  r   s                   r;   r#  z MistralModel._update_causal_mask6  s    ;;++/BB)o.I#1!R%#8#<#<#>#C#C#EIZIZI\]^I_#_ #$a 
 )c^.C%%
 @O?Z?99;`a'E%/AS%T" KK,,6'+E%%>>*'7#{{99 MM $**L,?,?vKK&**	&,,Q/%);+??AM
 nell; $$R(%7!;  PP+')#))!,;;+ Q 

 KK,,6*%%**o=%
 1CCKQZ[Kr<   r0  r1  rp   r   r2  c	                 p   | | j                         dk(  r| }	|	S t        j                  |      j                  }
t        j                  ||f|
||      }	t        j
                  ||      |j                  dd      kD  }|j                  ]t        |t              r||kD  rHt        j
                  ||      |j                  dd      |j                  z
  k  }|j                  |       |	|z  }	|	ddddddf   j                  |ddd      }	| |	j                         }	| j                  d   |kD  r| ddd|f   } | j                  d   }|	ddddddd|f   | ddddddf   j                  |	j                        z   }|dk(  }|	ddddddd|f   j!                  ||
      |	ddddddd|f<   |	S )aV  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            device (`torch.device`):
                The device to place the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
            config (`MistralConfig`):
                The model's configuration class
            past_key_values (`Cache`):
                The cache class that is being used currently to generate
        N   )
fill_valuerp   r   r  rG   r%   r   )rJ   rL   r9  r:  fullr"  ra   r   r   r   bitwise_or_r`   clonerK   ry   r   masked_fill)rk   r0  r1  rp   r   r   r2  r/   r   r   rA  diagonal_attend_masksliding_attend_maskmask_lengthpadding_masks                  r;   r<  zBMistralModel._prepare_4d_causal_attention_mask_with_cache_position  s   H %.*<*<*>!*C(K: 7 E*..I** -0Ye\bK $)<<f#MP^PfPfgiklPm#m $$0 "/3EF/\iJi*/,,}V*T&..r158M8MM+' )445HI//K%dD!Q&67>>z1bRTUK))//1!''+m;%3A~~4E%FN,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c )6Aq!\k\12 r<   	NNNNNNNNN)F)rA   rB   rC   r   r&   r.   r  r  r!   r    MISTRAL_INPUTS_DOCSTRINGr   rL   r   r   r   r   r   r   r   r   r@   r#  staticmethodr   rp   r   r<  rD   rE   s   @r;   r  r    s   
}  !" *+CD 151537+/59$(,0/359i
E,,-i
 !.i
 u//0	i

 "%i
   1 12i
 D>i
 $D>i
 'tni
 !!1!12i
 $$89i
 
!i
 E i
b #(QQ llQ 	Q
 Q  Qf BBB B {{	B
 B B B B B Br<   r  c                       e Zd Zy)KwargsForCausalLMN)rA   rB   rC   r   r<   r;   rQ  rQ    s    r<   rQ  c                       e Zd ZdgZddiZddgdgfiZ fdZd Zd Zd	 Z	d
 Z
d Zd Ze eddd       ee       eee      	 	 	 	 	 	 	 	 	 	 	 ddeej,                     deej.                     deej,                     dee   deej2                     deej,                     dee   dee   dee   deej,                     deeej.                  f   dee   defd                            Z xZ S ) MistralForCausalLMzlm_head.weightlm_headcolwise_repr\   logitsc                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r*   )
r-   r.   r  r   r  r	   r2   r0   rT  r  r8   s     r;   r.   zMistralForCausalLM.__init__  sU     !&)
 ++yy!3!3V5F5FUS 	r<   c                 .    | j                   j                  S r>   r   r	  r   s    r;   r  z'MistralForCausalLM.get_input_embeddings      zz&&&r<   c                 &    || j                   _        y r>   rY  r  s     r;   r  z'MistralForCausalLM.set_input_embeddings      "'

r<   c                     | j                   S r>   rT  r   s    r;   get_output_embeddingsz(MistralForCausalLM.get_output_embeddings  s    ||r<   c                     || _         y r>   r^  )r9   new_embeddingss     r;   set_output_embeddingsz(MistralForCausalLM.set_output_embeddings  s	    %r<   c                     || _         y r>   r   )r9   decoders     r;   set_decoderzMistralForCausalLM.set_decoder  s	    
r<   c                     | j                   S r>   rd  r   s    r;   get_decoderzMistralForCausalLM.get_decoder  s    zzr<   num_logits_to_keepz4.50logits_to_keep)versionnew_name)output_typer   r  rk   rW   r   r  labelsr   r   r  r   r{   r^   c                    ||n| j                   j                  }|	|	n| j                   j                  }	 | j                  d||||||||	|
d	|}|j                  }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}|* | j                  d||| j                   j                  d|}t        |||j                  |j                  |j                        S )a6  
            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]`.

            logits_to_keep (`int` or `torch.Tensor`, *optional*):
                If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
                If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
                This is useful when using packed tensor format (single dimension for batch and sequence length).

        Returns:

        Example:

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

        >>> model = MistralForCausalLM.from_pretrained("meta-mistral/Mistral-2-7b-hf")
        >>> tokenizer = AutoTokenizer.from_pretrained("meta-mistral/Mistral-2-7b-hf")

        >>> 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  rk   rW   r   r  r   r   r  r   )rV  rn  r  lossrV  r   r\   r  r   )r/   r   r  r   r  r   r   slicerT  loss_functionr  r   r   r\   r  )r9   r  rk   rW   r   r  rn  r   r   r  r   rj  r{   r   r\   slice_indicesrV  rq  s                     r;   r@   zMistralForCausalLM.forward  s   d 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,64:: ,
)%+'/!5),
 ,
  118B>SV8W~ot4]kmA}a,?@A%4%%pVFt{{OeOepiopD%#33!//))
 	
r<   )NNNNNNNNNNr   )!rA   rB   rC   _tied_weights_keys_tp_plan_pp_planr.   r  r  r_  rb  rf  rh  r!   r$   r    rN  r#   r   _CONFIG_FOR_DOCr   rL   r   r   r   r   r   r   r   r   rQ  r@   rD   rE   s   @r;   rS  rS    s   *+=)H_-z:;H'(& )6DTU*+CD+AP_` 151537+/59-1$(,0/35934P
E,,-P
 !.P
 u//0	P

 "%P
   1 12P
 ))*P
 D>P
 $D>P
 'tnP
 !!1!12P
 c5<</0P
 *+P
 
 P
 a E V P
r<   rS  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                   D    e Zd Z fdZd Zd Ze ee       e	e
ee      	 	 	 	 	 	 	 	 	 ddeej                     deej                      deej                     dee   d	eej$                     d
eej                     dee   dee   dee   defd                     Z xZS )MistralForTokenClassificationc                    t         |   |       |j                  | _        t        |      | _        t        |dd       |j                  }nt        |dd       |j                  }nd}t        j                  |      | _
        t        j                  |j                  |j                        | _        | j                          y )Nclassifier_dropouthidden_dropoutg?)r-   r.   
num_labelsr  r   r   r|  r}  r	   Dropoutrm   r2   r0   scorer  )r9   r/   r|  r:   s      r;   r.   z&MistralForTokenClassification.__init__Q  s      ++!&)
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	r<   c                 .    | j                   j                  S r>   rY  r   s    r;   r  z2MistralForTokenClassification.get_input_embeddingsa  rZ  r<   c                 &    || j                   _        y r>   rY  r  s     r;   r  z2MistralForTokenClassification.set_input_embeddingsd  r\  r<   )
checkpointrm  r   r  rk   rW   r   r  rn  r   r   r  r^   c
           
         | j                  ||||||||	      }
|
j                  }| j                  |      }| j                  |      }d}|| j	                  ||| j
                        }t        |||
j                  |
j                        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).
        rk   rW   r   r  r   r   r  N)rq  rV  r\   r  )	r   r  rm   r  rs  r/   r   r\   r  )r9   r  rk   rW   r   r  rn  r   r   r  r   sequence_outputrV  rq  s                 r;   r@   z%MistralForTokenClassification.forwardg  s    4 ,0::)%+'/!5 ,6 	,
 "33,,7O,%%ffdkkBD$!//))	
 	
r<   rM  )rA   rB   rC   r.   r  r  r!   r    rN  r   _CHECKPOINT_FOR_DOCr   rx  r   rL   r   r   r   r   r   r@   rD   rE   s   @r;   rz  rz  I  s    '( *+CD&)$ 151537+/59-1$(,0/3*
E,,-*
 !.*
 u//0	*

 "%*
   1 12*
 ))**
 D>*
 $D>*
 'tn*
 
*
 E *
r<   rz  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                   (    e Zd Z fdZd Zd Ze ee      	 	 	 	 	 	 	 	 	 dde	e
j                     de	e
j                     de	e
j                     de	e   de	e
j                     d	e	e
j                     d
e	e   de	e   de	e   defd              Z xZS ) MistralForSequenceClassificationc                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y r*   )
r-   r.   r~  r  r   r	   r2   r0   r  r  r8   s     r;   r.   z)MistralForSequenceClassification.__init__  sS      ++!&)
YYv114??O
 	r<   c                 .    | j                   j                  S r>   rY  r   s    r;   r  z5MistralForSequenceClassification.get_input_embeddings  rZ  r<   c                 &    || j                   _        y r>   rY  r  s     r;   r  z5MistralForSequenceClassification.set_input_embeddings  r\  r<   r  rk   rW   r   r  rn  r   r   r  r^   c
           
         | j                  ||||||||	      }
|
j                  }| j                  |      }||j                  d   }n|j                  d   }| j                  j
                  |dk7  rt        d      | j                  j
                  d}n||| j                  j
                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                    d       |t        j                  ||j                  	      |f   }d}|| j#                  |||| j                  
      }t%        |||
j&                  |
j(                  |
j*                        S )r  r  Nr   r%   z=Cannot handle batch sizes > 1 if no padding token is defined.rG   )r   rp   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r  )rV  rn  pooled_logitsr/   rp  )r   r  r  rK   r/   r  r   ry   r   rL   int32r"  argmaxr   r   r:   rA   rs  r   r   r\   r  )r9   r  rk   rW   r   r  rn  r   r   r  transformer_outputsr\   rV  r2  last_non_pad_tokennon_pad_masktoken_indicesr  rq  s                      r;   r@   z(MistralForSequenceClassification.forward  s   * 8<zz)%+'/!5 8B 	8
 ,==M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaab%%VFR_hlhshs%tD/ /??-;;*55
 	
r<   rM  )rA   rB   rC   r.   r  r  r!   r    rN  r   rL   r   r   r   r   r   r   r@   rD   rE   s   @r;   r  r    s    '( *+CD 151537+/59-1$(,0/3A
E,,-A
 !.A
 u//0	A

 "%A
   1 12A
 ))*A
 D>A
 $D>A
 'tnA
 
*A
 E A
r<   r  z
The Mistral Model transformer with a span classification head on top for extractive question-answering tasks like
SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                   d    e Zd ZdZ fdZd Zd Ze ee	      	 	 	 	 	 	 	 	 	 dde
ej                     de
ej                     de
ej                     de
eeeej                     f      d	e
ej                     d
e
ej                     de
ej                     de
e   de
e   defd              Z xZS )MistralForQuestionAnsweringr   c                     t         |   |       t        j                  |j                  d      | _        t        |      | _        | j                          y )NrH   )	r-   r.   r	   r2   r0   
qa_outputsr  r   r  r8   s     r;   r.   z$MistralForQuestionAnswering.__init__
  s@     ))F$6$6:!&)
 	r<   c                 .    | j                   j                  S r>   rY  r   s    r;   r  z0MistralForQuestionAnswering.get_input_embeddings  rZ  r<   c                 &    || j                   _        y r>   rY  r  s     r;   r  z0MistralForQuestionAnswering.set_input_embeddings  r\  r<   r  rk   rW   r   r  start_positionsend_positionsr   r  r^   c
           	         | j                  |||||||	      }|j                  }| j                  |      }|j                  dd      \  }}|j	                  d      j                         }|j	                  d      j                         }d}|| | j                  ||||fi |
}t        ||||j                  |j                        S )a  
        start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the start of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for position (index) of the end of the labelled span for computing the token classification loss.
            Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
            are not taken into account for computing the loss.
        )rk   rW   r   r  r   r  r%   rG   rI   N)rq  start_logits
end_logitsr\   r  )
r   r  r  splitsqueezerz   rs  r   r\   r  )r9   r  rk   rW   r   r  r  r  r   r  r{   r   r  rV  r  r  rq  s                    r;   r@   z#MistralForQuestionAnswering.forward  s    4 ,0::)%+'/!5 ,6 ,
 "331#)<<r<#: j#++B/::<''+668
&=+D%4%%lJQ^ibhiD+%!!//))
 	
r<   rM  )rA   rB   rC   r   r.   r  r  r!   r    rN  r   rL   r   r   r   r   r   r   r   r@   rD   rE   s   @r;   r  r     s      '( *+CD 156:37KO596:48,0/33
E,,-3
 !!2!233
 u//0	3

 "%tE4E4E/F(F"GH3
   1 123
 "%"2"233
   0 013
 $D>3
 'tn3
 
&3
 E 3
r<   r  )Nr%   )r   )L	functoolsr   typingr   r   r   r   r   rL   r	   activationsr   cache_utilsr   r   r   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r    r!   r"   r#   utils.deprecationr$   configuration_mistralr&   
get_loggerrA   r   r  rx  Moduler(   rP   r[   r   r   rf   r   r   r   r   r   r   MISTRAL_START_DOCSTRINGr   rN  r  rQ  rS  rz  r  r  r   r<   r;   <module>r     sn    9 9   ! O O ) > B  L F &   1 0 
		H	%1 !  (6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4A)ryy A)HJRYY J(1")) 1h<RYY <D " [?_ ?	?4@ F [a) a	aH	 ?,j >t
/ t
n  H
$: H
H
V  S
'= S
S
l  F
"8 F
F
r<   