
    UhG                        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 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, ddl-m.Z.  e+       rd dl/m0Z0 ddl1m2Z2  e,jf                  e4      Z5 G d dejl                        Z7d Z8d?dZ9dejt                  de;dejt                  fdZ<	 d@d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? ed'       G d( d)ejl                               Z@ G d* d+e      ZAe) G d, d-e$             ZB G d. d/ejl                        ZCe) G d0 d1eB             ZD G d2 d3ee(      ZEe) G d4 d5eBe             ZFe) G d6 d7eB             ZG e)d89       G d: d;eB             ZHe) G d< d=eB             ZIg d>ZJy)A    )CallableListOptionalTupleUnionN)nn   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPastQuestionAnsweringModelOutput SequenceClassifierOutputWithPastTokenClassifierOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )MistralConfig)	BlockMask)make_flex_block_causal_maskc                   $     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/catia.catastroantioquia-mas.com/valormas/lib/python3.12/site-packages/transformers/models/mistral/modeling_mistral.pyr.   zMistralMLP.__init__+   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.forward5   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[   A   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   \   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   h   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d       xs |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__   s2   "
D9mV=O=OSYSmSm=m$*$>$>&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   RMSNormc                   ,     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                   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 t        |t              r&|j
                  j                  j                  d       y y )Nr   )r   stdg      ?)r/   initializer_range
isinstancer   r2   r   datanormal_r,   zero_	Embeddingpadding_idxr   fill_)r9   rg   r   s      r;   _init_weightsz$MistralPreTrainedModel._init_weights  s    kk++fbii(MM&&CS&9{{&  &&( '-MM&&CS&9!!-""6#5#56<<> ./MM$$S) 0r<   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     sS     L&*#./#4"5!N  $!"&*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   r   r   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   c                        e Zd Zdef fdZd Zd Z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e
j                  df   de
j                  de
j                  dedef
dZede
j                  dedede
j0                  de
j                  dededefd       Z xZS )MistralModelr/   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__O  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_embeddingsb  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||fz  } ||f||||||	|d	|
}|d   }|s$||d   fz  }. | j1                  |      }|r||fz  }t3        ||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  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.forwarde  sT    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!)
*)."3#-$7
 $
M *!,M =#3"55'	6* 		-0  -!11&+/8Od+%	
 	
r<   r%   input_tensorc           
      l   | 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                   j                  dk(  r't        |t        j                        rt        |      }|S ||j                         nd}t        |t              }t        |t              }	| j                   j                  dk(  r?|s=|	s;|s9t        j                  |||| j                   j                  | j                         ry |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.                  j0                  dv r|st        j2                  ||      }|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   flex_attentionr   )r  past_key_values_lengthr   is_trainingr#   )sequence_lengthtarget_lengthrp   r   
batch_sizer/   r   )cudaxpunpu)r/   r   sumitemsizer"  r   rL   r   r&   r#  r   r   r   _ignore_causal_mask_sdpar   rr   rp   finfominrK   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr   r   _unmask_unattended)r9   rk   r+  r   r   r   is_padding_rightr&  using_static_cacheusing_sliding_window_cacherp   	min_dtyper1  r2  r   s                  r;   r%  z MistralModel._update_causal_mask  s:    ;;++/BB)o.I#1!R%#8#<#<#>#C#C#EIZIZI\]^I_#_ #$a 
 )c^.C%%;;++/??.%,,7!<^!L!!
 @O?Z?99;`a'E%/AS%T" KK,,6'+E%%>>*'7#{{99 MM ""KK&**	&,,Q/%);+??AM
 nell; $$R(%7!;  PP+')#))!,;;+ Q 	
 KK,,6*%%**.DD%
 1CCKQZ[Kr<   r1  r2  rp   r3  c                    | | j                         dk(  r| }|S t        j                  |      j                  }	t        j                  ||f|	||j
                        }t        j                  ||j
                        |j                  dd      kD  }
|j                         }t        |dd      rs|j                  gt        |t              r||kD  rRt        j                  ||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 )
a  
        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.
            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#   use_sliding_windowTr   )rJ   rL   r;  r<  fullr   r$  ra   get_text_configr   r   r   r   bitwise_or_r`   clonerK   ry   masked_fill)rk   r1  r2  rp   r   r3  r/   r   r   rC  diagonal_attend_masktext_configsliding_attend_maskmask_lengthpadding_masks                  r;   r>  zBMistralModel._prepare_4d_causal_attention_mask_with_cache_position  s%   B %.*<*<*>!*C(K@ = E*..I** -0Ye\j\q\qK $)<<nF[F[#\_m_u_uA` $  !002K{$8$?KD^D^Dj "/3EF/\iJi*/,,}^MbMb*c&..r158R8RR+' )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   rL   r   r   r   r   r   r   r   r   r@   r   r%  staticmethodr   rp   r>  rD   rE   s   @r;   r  r  M  s   }  !"  151537+/59$(,0/359\
E,,-\
 !.\
 u//0	\

 "%\
   1 12\
 D>\
 $D>\
 'tn\
 !!1!12\
 $$89\
 
!\
  \
H #(TellK78T llT 	T
 T  Tl 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;   rU  rU  a  s    r<   rU  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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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   rX  r  r8   s     r;   r.   zMistralForCausalLM.__init__j  sU     !&)
 ++yy!3!3V5F5FUS 	r<   c                 .    | j                   j                  S r>   r   r  r   s    r;   r  z'MistralForCausalLM.get_input_embeddingss      zz&&&r<   c                 &    || j                   _        y r>   r]  r  s     r;   r  z'MistralForCausalLM.set_input_embeddingsv      "'

r<   c                     | j                   S r>   rX  r   s    r;   get_output_embeddingsz(MistralForCausalLM.get_output_embeddingsy  s    ||r<   c                     || _         y r>   rb  )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>   rh  r   s    r;   get_decoderzMistralForCausalLM.get_decoder  s    zzr<   r  rk   rW   r   r  labelsr   r   r  r   logits_to_keepr{   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 )a  
        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]`.

        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   )rZ  rm  r
  lossrZ  r   r\   r!  r   )r/   r   r  r   r   r   r   slicerX  loss_functionr
  r   r   r\   r!  )r9   r  rk   rW   r   r  rm  r   r   r  r   rn  r{   r   r\   slice_indicesrZ  rq  s                     r;   r@   zMistralForCausalLM.forward  s   N 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  rc  rf  rj  rl  r    r   r   rL   r   r   r   r   r   r   r   r   rU  r   r@   rD   rE   s   @r;   rW  rW  d  s   *+=)H_-z:;H'(&  151537+/59-1$(,0/35934G
E,,-G
 !.G
 u//0	G

 "%G
   1 12G
 ))*G
 D>G
 $D>G
 'tnG
 !!1!12G
 c5<</0G
 *+G
 
 G
  G
r<   rW  c                       e Zd Z fdZd Zd Z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__  s      ++!&)
6/6B!'!:!:V-t4@!'!6!6!$zz"45YYv1163D3DE
 	r<   c                 .    | j                   j                  S r>   r]  r   s    r;   r  z2MistralForTokenClassification.get_input_embeddings  r^  r<   c                 &    || j                   _        y r>   r]  r  s     r;   r  z2MistralForTokenClassification.set_input_embeddings  r`  r<   r  rk   rW   r   r  rm  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  rZ  r\   r!  )	r   r   rm   r  rs  r/   r   r\   r!  )r9   r  rk   rW   r   r  rm  r   r   r  r   sequence_outputrZ  rq  s                 r;   r@   z%MistralForTokenClassification.forward  s    * ,0::)%+'/!5 ,6 	,
 "33,,7O,%%ffdkkBD$!//))	
 	
r<   rR  )rA   rB   rC   r.   r  r  r    r   r   rL   r   r   r   r   r   r   r@   rD   rE   s   @r;   ry  ry    s     '(  151537+/59-1$(,0/3*
E,,-*
 !.*
 u//0	*

 "%*
   1 12*
 ))**
 D>*
 $D>*
 'tn*
 
*
  *
r<   ry  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).
    )custom_introc                       e Zd Z fdZd Zd Z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>   r]  r   s    r;   r  z5MistralForSequenceClassification.get_input_embeddings0  r^  r<   c                 &    || j                   _        y r>   r]  r  s     r;   r  z5MistralForSequenceClassification.set_input_embeddings3  r`  r<   r  rk   rW   r   r  rm  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  )rZ  rm  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  rm  r   r   r  transformer_outputsr\   rZ  r3  last_non_pad_tokennon_pad_masktoken_indicesr  rq  s                      r;   r@   z(MistralForSequenceClassification.forward6  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<   rR  )rA   rB   rC   r.   r  r  r    r   r   rL   r   r   r   r   r   r   r@   rD   rE   s   @r;   r  r    s    '(  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
  A
r<   r  c                   X    e Zd ZdZ fdZd Zd Z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>   r]  r   s    r;   r  z0MistralForQuestionAnswering.get_input_embeddings  r^  r<   c                 &    || j                   _        y r>   r]  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  rZ  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<   rR  )rA   rB   rC   r   r.   r  r  r    r   r   rL   r   r   r   r   r   r   r   r   r@   rD   rE   s   @r;   r  r  |  s   '(  151537KO596:48,0/33
E,,-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
  3
r<   r  )rW  r  r  r   r  ry  )Nr#   )r   )Ktypingr   r   r   r   r   rL   r   activationsr
   cache_utilsr   r   r   r   
generationr   integrationsr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r    r!   r"   configuration_mistralr$   !torch.nn.attention.flex_attentionr%   integrations.flex_attentionr&   
get_loggerrA   r   Moduler(   rP   r[   r   r   rf   r   r   r   r   r   r   r   r  rU  rW  ry  r  r  __all__r   r<   r;   <module>r     sE   : 9   ! O O ) 7 > B 9  L F & h h 0  !;J 
		H	%  (6	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %4A)ryy A)H Y'JRYY J (J(04 0f *_ * *8<RYY <D P) P Pf ?,j > i
/ i
 i
X C
$: C
 C
L S
'= S
S
l F
"8 F
 F
Rr<   