
    sgа                     T   d Z ddlZddlZddlmZmZmZmZ ddlZ	ddl
mZmZmZ ddlmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZmZ d	d
lm Z   ejB                  e"      Z#dZ$d,dZ%d-dZ& G d dejN                  jP                        Z) G d dejN                  jP                        Z*d Z+d.dZ, G d dejN                  jP                        Z-de	j\                  de/de	j\                  fdZ0 G d dejN                  jP                        Z1 G d dejN                  jP                        Z2e G d dejN                  jP                               Z3d Z4 ed!e4       G d" d#e             Z5d$Z6 ed!e4       G d% d&e5             Z7 G d' d(e5e      Z8 ed)e4       G d* d+e5e             Z9y)/zTF 2.0  Mistral model.    N)ListOptionalTupleUnion   )TFBaseModelOutputWithPastTFCausalLMOutputWithPast"TFSequenceClassifierOutputWithPast)TFCausalLanguageModelingLossTFPreTrainedModelTFSequenceClassificationLossget_initializerget_tf_activationkeraskeras_serializableunpack_inputs)check_embeddings_within_bounds
shape_liststable_softmax)add_start_docstrings%add_start_docstrings_to_model_forwardlogging   )MistralConfigr   c                 V   | \  }}t        j                  ||ft         j                  j                  |      j                        }t        j
                  |      }t        j                  |dddf   |dddf   k\  d|      }|dkD  r0t        j                  t        j                  ||f|      |gd      }|Ht        j                  |d      }t        j                  |d      }t        j                  ||dddg      }|S t        j                  |ddddddf   |d|||z   f      }|S )zm
    Make causal mask used for bi-directional self-attention, supporting both static and dynamic shapes.
    Ng        r   dtypeaxisr   )tffilldtypesas_dtypeminrangewhereconcatzerosexpand_dimstilebroadcast_to)input_ids_shaper   past_key_values_lengthbsztgt_lenmask	mask_conds          b/var/www/html/venv/lib/python3.12/site-packages/transformers/models/mistral/modeling_tf_mistral.py_make_causal_maskr4   9   s    #LC 77GW%ryy'9'9%'@'D'DED!I88Iag&)D!G*<<c4HD!yy"((G-C#DERTXY`bc
{ ~~dA&~~dA&wwtc1a^,
 K tD$1$45QSiIi7jkK    c                    t        |       \  }}||n|}t        j                  t        j                  | d      d      }t        j                  ||d||g      }dt        j                  ||      z
  }t        j
                  t        j                  |t              t        j                  t        |      t        j                  j                        |      S )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    r         ?)dimsvalue)
r   r!   r*   r,   castr'   boolr"   float32r%   )r1   r   r0   r/   src_lenexpanded_maskinverted_masks          r3   _expand_maskr@   T   s     d#LC ,g'GNN2>>$#:A>MOOMCGW3MNM"''-77M88
t$bgg:m3LTVT^T^TbTb&cer r5   c                   .     e Zd Zd fd	ZddZd Z xZS )TFMistralRMSNormc                 @    t        |   di | || _        || _        y)z?
        TFMistralRMSNorm is equivalent to T5LayerNorm
        N )super__init__hidden_sizevariance_epsilon)selfrG   epskwargs	__class__s       r3   rF   zTFMistralRMSNorm.__init__f   s%     	"6"& #r5   c                 r    | j                  d| j                  d      | _        | j                  ry d| _        y )Nweightones)nameshapeinitializerT)
add_weightrG   rN   builtrI   input_shapes     r3   buildzTFMistralRMSNorm.buildn   s9    oo"" & 

 ::
r5   c                 j   |j                   }t        j                  |t        j                        }t        j                  t        j
                  |      dd      }t        j                  |t        j                  || j                  z               }| j                  t        j                  ||      z  S )Nr   T)r    keepdims)
r   r!   r:   r<   reduce_meansquaredividesqrtrH   rN   )rI   hidden_statesinput_dtypevariances       r3   callzTFMistralRMSNorm.callx   sz    #))rzz:>>"))M":dS		-DDYDY9Y1Z[{{RWW]K@@@r5   )gư>N)__name__
__module____qualname__rF   rW   ra   __classcell__rL   s   @r3   rB   rB   e   s    $Ar5   rB   c                   (     e Zd Zd fd	ZddZ xZS )TFMistralRotaryEmbeddingc                     t        |   di | || _        || _        || _        d| j                  t        j                  d| j                  dt
        j                        | j                  z  z  z  | _        y )Nr7   r      )startlimitdeltar   rD   )	rE   rF   dimmax_position_embeddingsbaser!   r&   r<   inv_freq)rI   ro   rp   rq   rK   rL   s        r3   rF   z!TFMistralRotaryEmbedding.__init__   se    "6"'>$	tyyRXXATXXUV^`^h^h-ilpltlt-tuvr5   c                 |   t        j                  t        j                  |t         j                        | j                  j
                        }t        j                  d|| j                        }t        j                  ||gd      }t        j                  t        j                  |      |j
                        }t        j                  t        j                  |      |j
                        }|d | }t        j                  ||j
                        }|d | }t        j                  ||j
                        }||fS )Nr   zi,j->ijr   r   )
r!   r:   r&   int64rr   r   einsumr(   cossin)rI   xseq_lentfreqsemb
cos_values
sin_valuess           r3   ra   zTFMistralRotaryEmbedding.call   s    GGBHHWBHH5t}}7J7JK		)Q6iiR0WWRVVC[!''2
WWRVVC[!''2
)
WWZqww7
)
WWZqww7
J''r5   )i   i'  rb   )rc   rd   re   rF   ra   rf   rg   s   @r3   ri   ri      s    w(r5   ri   c                 |    t        |       d   dz  }| dd|f   }| d|df   }t        j                  | |gd      S )z*Rotates half the hidden dims of the input.r   rk   .Nr   )r   r!   r(   )rx   
mid_lengthx1x2s       r3   rotate_halfr      sP    Ar"a'J	
3	B	
3
	B99rc2YR((r5   c                    t        j                  t        j                  ||      |      }t        j                  t        j                  ||      |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a\  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`tf.Tensor`): The query tensor.
        k (`tf.Tensor`): The key tensor.
        cos (`tf.Tensor`): The cosine part of the rotary embedding.
        sin (`tf.Tensor`): The sine part of the rotary embedding.
        position_ids (`tf.Tensor`):
            The position indices of the tokens corresponding to the query and key tensors. For example, this can be
            used to pass offsetted position ids when working with a KV-cache.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(tf.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )r!   r*   gatherr   )qkrv   rw   position_idsunsqueeze_dimq_embedk_embeds           r3   apply_rotary_pos_embr      ss    * ..35}
EC
..35}
EC3w;q>C/0G3w;q>C/0GGr5   c                   ,     e Zd Z fdZd ZddZ xZS )TFMistralMLPc                    t        |   di | || _        |j                  | _        |j                  | _        t
        j                  j                  | j                  dd      | _        t
        j                  j                  | j                  dd      | _	        t
        j                  j                  | j                  dd      | _
        t        |j                        | _        y )NF	gate_projuse_biasrP   up_proj	down_projrD   )rE   rF   configrG   intermediate_sizer   layersDenser   r   r   r   
hidden_actact_fn)rI   r   rK   rL   s      r3   rF   zTFMistralMLP.__init__   s    "6"!--!'!9!9++D,B,BUYd+e||))$*@*@5W`)a++D,<,<uS^+_'(9(9:r5   c                     | j                  | j                  | j                  |            | j                  |      z        S rb   )r   r   r   r   )rI   rx   s     r3   ra   zTFMistralMLP.call   s0    ~~dkk$..*;<t||ANOOr5   c                    | j                   ry d| _         t        | dd       Xt        j                  | j                  j
                        5  | j                  j                  | j                  f       d d d        t        | dd       Xt        j                  | j                  j
                        5  | j                  j                  | j                  f       d d d        t        | dd       Yt        j                  | j                  j
                        5  | j                  j                  | j                  f       d d d        y y # 1 sw Y   xY w# 1 sw Y   |xY w# 1 sw Y   y xY w)NTr   r   r   )rT   getattrr!   
name_scoper   rP   rW   rG   r   r   r   rU   s     r3   rW   zTFMistralMLP.build   s!   ::
4d+7t~~223 :$$d&6&6%89:4D)5t||001 8""D$4$4#6784d+7t~~223 @$$d&<&<%>?@ @ 8: :8 8@ @s$   'E0'E'EEEE'rb   )rc   rd   re   rF   ra   rW   rf   rg   s   @r3   r   r      s    ;P@r5   r   r^   n_repreturnc                     t        |       \  }}}}|dk(  r| S t        j                  | d      } t        j                  | |d      } t        j                  | |||z  ||f      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   rk   )repeatsr    )r   r!   r*   repeatreshape)r^   r   batchnum_key_value_headsslenhead_dims         r3   	repeat_kvr      sh    
 2<M1J.EhzNN=!4MIImUCM::me-@5-H$PX%YZZr5   c                   d    e Zd ZdZddedee   f fdZdej                  dedefdZ
	 	 	 	 	 	 dd	ej                  d
eej                     deej                     deeej                        dee   dee   deej                  eej                     eeej                        f   fdZddZ xZS )TFMistralAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".
    r   	layer_idxc                     t        |   di | || _        || _        |-t        j                  d| j                  j                   d       |j                  | _        |j                  | _
        | j                  | j                  z  | _        |j                  | _        | j                  | j                  z  | _        |j                  | _        |j                  | _        d| _        |j"                  | _        | j                  | j                  z  | j                  k7  r&t%        d| j                   d| j                   d      t&        j(                  j+                  | j                  | j                  z  dd	      | _        t&        j(                  j+                  | j                  | j                  z  dd
	      | _        t&        j(                  j+                  | j                  | j                  z  dd	      | _        t&        j(                  j+                  | j                  dd	      | _        t5        | j                  | j                  | j                  d      | _        t&        j(                  j9                  | j"                        | _        y )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fq_projr   k_projv_projo_proj
rotary_emb)rp   rq   rP   )raterD   )rE   rF   r   r   loggerwarning_oncerL   rc   rG   num_attention_heads	num_headsr   r   num_key_value_groupsrp   
rope_theta	is_causalattention_dropout
ValueErrorr   r   r   r   r   r   r   ri   r   DropoutdropoutrI   r   r   rK   rL   s       r3   rF   zTFMistralAttention.__init__   s   "6"" !8!8 9 :, , "--33((DNN:#)#=#= $(NNd6N6N$N!'-'E'E$ ++!'!9!9MMDNN*t/?/??QRVRbRbQc$T^^$4B8  ll(($--)GRW^f(gll(()A)ADMM)Q\ahp(qll(()A)ADMM)Q\ahp(qll(()9)9EPX(Y2MM$($@$@	
 ||++1G1G+Hr5   tensorry   r/   c                     t        j                  |||| j                  | j                  f      }t        j                  |d      }|S )Nr   rk   r   r   perm)r!   r   r   r   	transpose)rI   r   ry   r/   s       r3   _shapezTFMistralAttention._shape  s8    FS'4>>4==$QRf<8r5   r^   attention_maskr   past_key_valueoutput_attentions	use_cacher   c           	         d|v rt        j                  d       t        |      \  }	}
}| j                  |      }| j	                  |      }| j                  |      }t        j                  t        j                  ||	|
| j                  | j                  f      d      }t        j                  t        j                  ||	|
| j                  | j                  f      d      }t        j                  t        j                  ||	|
| j                  | j                  f      d      }t        |      d   }|||d   j                  d   z  }| j                  ||      \  }}t        |||||      \  }}|8t        j                  |d   |gd	
      }t        j                  |d   |gd	
      }|r||fnd }t!        || j"                        }t!        || j"                        }t        j$                  ||d      t'        j(                  | j                        z  }|||z   }t+        |d
      }t        j,                  ||j.                        }| j1                  ||      }t        j$                  ||      }t        j                  |d      }t        j                  ||	|
| j2                  f      }| j5                  |      }|sd }|||fS )Npadding_maskrPassing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`r   r   r   )rx   ry   )r   r   rv   rw   r   rk   r   r   T)transpose_br   )training)warningswarnr   r   r   r   r!   r   r   r   r   r   rQ   r   r   r(   r   r   matmulmathr]   r   r:   r   r   rG   r   )rI   r^   r   r   r   r   r   r   rK   r/   q_len_query_states
key_statesvalue_states
kv_seq_lenrv   rw   attn_weightsattn_outputs                       r3   ra   zTFMistralAttention.call  s    V#MM E #=1UA{{=1[[/
{{=1||JJ|c5$..$--%PQXd
 \\JJzC0H0H$--#XY`l

 ||JJ|c5$2J2JDMM%Z[bn
  
+B/
%.+11"55J?? # 
S $8%$
 j %N1$5z#BKJ99nQ&7%FQOL7@*l3d z4+D+DE
 t/H/HIyyztLtyyY]YfYfOgg%'.8L &l<ww|\-?-?@|| $ 
 iil;ll;\BjjsE4;K;K.LMkk+. LL.88r5   c                    | j                   ry d| _         t        | dd       Xt        j                  | j                  j
                        5  | j                  j                  | j                  f       d d d        t        | dd       Xt        j                  | j                  j
                        5  | j                  j                  | j                  f       d d d        t        | dd       Xt        j                  | j                  j
                        5  | j                  j                  | j                  f       d d d        t        | dd       ft        j                  | j                  j
                        5  | j                  j                  | j                  | j                  z  f       d d d        y y # 1 sw Y   HxY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   y xY w)NTr   r   r   r   )rT   r   r!   r   r   rP   rW   rG   r   r   r   r   r   rU   s     r3   rW   zTFMistralAttention.buildk  s}   ::
44(4t{{//0 7!!4#3#3"56744(4t{{//0 7!!4#3#3"56744(4t{{//0 7!!4#3#3"56744(4t{{//0 E!!4>>DMM#A"CDE E 57 77 77 7E Es0   'F80'G'G:4G8GGGG&rb   )NNNFFN)rc   rd   re   __doc__r   r   intrF   r!   Tensorr   r   r;   ra   rW   rf   rg   s   @r3   r   r      s    
%I} %I# %INRYY  3  /3,059,1$)O9yyO9 !+O9 ryy)	O9
 !ryy!12O9 $D>O9 D>O9 
ryy(299-xbii8H/II	JO9bEr5   r   c                   *    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	ej                        dee
   d	ee
   d
e	ej                  ee	ej                  ej                  f      f   fdZddZ xZS )TFMistralDecoderLayerr   r   c                 ,   t        |   di | |j                  | _        t        ||d      | _        t        |d      | _        t        |j                  |j                  d      | _	        t        |j                  |j                  d      | _
        y )N	self_attnrP   mlpinput_layernormrJ   rP   post_attention_layernormrD   )rE   rF   rG   r   r   r   r   rB   rms_norm_epsr   r   r   s       r3   rF   zTFMistralDecoderLayer.__init__~  s~    "6"!--+FIKPU3/0B0BH[H[bst(8F$7$7>X)
%r5   r^   r   r   r   r   r   r   c                    d|v rt        j                  d       |}| j                  |      }| j                  ||||||      \  }}	}
||z   }|}| j	                  |      }| j                  |      }||z   }|f}|r||	fz  }|r||
fz  }|S )a(  
        Args:
            hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`tf.Tensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).
            past_key_value (`Tuple(tf.Tensor)`, *optional*): cached past key and value projection states
        r   r   )r^   r   r   r   r   r   )r   r   r   r   r   r   )rI   r^   r   r   r   r   r   rK   residualself_attn_weightspresent_key_valueoutputss               r3   ra   zTFMistralDecoderLayer.call  s    . V#MM E !,,]; ?Cnn')%)/ ?M ?
;(*; !=0 !55mD/ =0 ")++G)++Gr5   c                 `   | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   ~xY w# 1 sw Y   y xY w)NTr   r   r   r   )
rT   r   r!   r   r   rP   rW   r   r   r   rU   s     r3   rW   zTFMistralDecoderLayer.build  sT   ::
4d+7t~~223 +$$T*+4%1txx}}- %t$%4*D1=t33889 1$$**40143T:Ft<<AAB :--33D9: : G+ +% %1 1: :s0   E?%F?FF$?F	FF!$F-)NNNFFrb   )rc   rd   re   r   r   rF   r!   r   r   r   r;   ra   rW   rf   rg   s   @r3   r   r   }  s    

} 

 

 /3,059,1$)9yy9 !+9 ryy)	9
 !ryy!129 $D>9 D>9 
ryy(5BII)=#>??	@9v:r5   r   c                   8    e Zd ZdZeZdef fdZd Zd Zd Z	e
	 	 	 	 	 	 	 	 	 ddej                  deej                     d	eej                     d
eeej                        deej                     dee   dee   dee   dee   deeef   fd       ZddZ xZS )TFMistralMainLayerz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]

    Args:
        config: MistralConfig
    r   c           	         t        |   di | |j                  | _        |j                  | _        |j
                  | _        t        j                  j                  |j                  |j
                  d      | _	        t        |j                        D cg c]  }t        ||d|        c}| _        |j                  | _        t        |j
                  |j                  d      | _        || _        y c c}w )Nembed_tokens)	input_dim
output_dimrP   zlayers.r   normr   rD   )rE   rF   pad_token_idpadding_idx
vocab_sizerG   r   r   	Embeddingr   r&   num_hidden_layersr   _attn_implementationrB   r   r   r   )rI   r   rK   r   rL   s       r3   rF   zTFMistralMainLayer.__init__  s    "6"!.. ++!-- "LL22'')) 3 
 #6#;#;<
 "&)GI;:OP
 %+$?$?!$V%7%7V=P=PW]^	
s   C6c                     | j                   S rb   r   rI   s    r3   get_input_embeddingsz'TFMistralMainLayer.get_input_embeddings  s       r5   c                     || _         y rb   r   rI   r9   s     r3   set_input_embeddingsz'TFMistralMainLayer.set_input_embeddings  s
    !r5   c                     d }t        ||j                  |      }|$t        ||j                  |d         }||n||z   }|S )N)r.   r   )r0   )r4   r   r@   )rI   r   rV   inputs_embedsr.   combined_attention_maskexpanded_attn_masks          r3   _prepare_decoder_attention_maskz2TFMistralMainLayer._prepare_decoder_attention_mask  sg     #'"3#9#
 %!-nm>Q>Q[fgi[j!k&=&E"K]`wKw $ '&r5   	input_idsr   r   past_key_valuesr  r   r   output_hidden_statesreturn_dictr   c
           	      .   ||t        d      |t        |      \  }
}n|t        |      \  }
}}nt        d      |}d}|t        |d   d         d   }||z   }|Vt        j                  |||z   t        j                        }t        j
                  t        j                  |d      d|f      }n:t        j                  t        j
                  |d|f      t        j                        }|1t        || j                  j                         | j                  |      }|'t        j                  |
|ft        j                        }| j                  ||
|f||      }|}|rdnd }|rdnd }|rdnd }t        | j                         D ]D  \  }}|r||fz  }|||   nd } |||||||	      }|d   }|r|||rdnd
   fz  }|s<||d
   fz  }F | j#                  |      }|r||fz  }|r|nd }|	st%        d ||||fD              S t'        ||||      S )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timezEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   rk   )rl   rm   r   r   r   rD   )r   r   r   r   r   r   c              3   &   K   | ]	  }||  y wrb   rD   ).0vs     r3   	<genexpr>z*TFMistralMainLayer.call.<locals>.<genexpr>g  s     tqfgfsts   )last_hidden_stater  r^   
attentions)r   r   r!   r&   rt   r   r*   r:   r   r   r   r   rO   r;   r	  	enumerater   r   tupler   )rI   r
  r   r   r  r  r   r   r  r  
batch_size
seq_lengthr   seq_length_with_pastr.   r^   all_hidden_statesall_self_attnsnext_decoder_cacheidxdecoder_layerr   layer_outputs
next_caches                           r3   ra   zTFMistralMainLayer.call  s     ]%>stt"%/	%:"J
&(2=(A%J
Adee)!"&%/0B10E%Fq%I"#7:P#P 88,JAW4W_a_g_gL ::bnn\1&EJGWXL 772::lR<L#MrxxXL *9dkk6L6LM --i8M!WWj2F%GrwwWN==Z4mE[
 & #7BD0d#,R$"+DKK"8 	6C#!m%55!5D5P_S1VZN)-)-"3#M *!,M"}:KQQR'S&UU" =#3"55+	6. 		-0  -!11+4'$
t]J@QSa$bttt(+&+%	
 	
r5   c                    | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       K| j                  D ];  }t        j                  |j
                        5  |j                  d        d d d        = y y # 1 sw Y   xY w# 1 sw Y   nxY w# 1 sw Y   axY w)NTr   r   r   )	rT   r   r!   r   r   rP   rW   r   r   )rI   rV   layers      r3   rW   zTFMistralMainLayer.buildo  s   ::
4.:t00556 .!!''-.4&2tyy~~. &		%&44(4 &]]5::. &KK%& && 5. .& && &s$   D"%D.D:"D+.D7:E		NNNNNNNNNrb   )rc   rd   re   r   r   config_classrF   r  r  r	  r   r!   r   r   r   r;   r   r   r   ra   rW   rf   rg   s   @r3   r   r     s    !L} (!"'(   $.2,059-1$(,0/3&*\
99\
 !+\
 ryy)	\

 "$ryy/2\
  		*\
 D>\
 $D>\
 'tn\
 d^\
 
u//	0\
 \
|&r5   r   ax	  

    This model inherits from [`TFPreTrainedModel`]. 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 [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
    as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
    behavior.

    <Tip>

    TensorFlow models and layers in `model` accept two formats as input:

    - having all inputs as keyword arguments (like PyTorch models), or
    - having all inputs as a list, tuple or dict in the first positional argument.

    The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
    and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
    pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
    format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
    the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
    positional argument:

    - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
    - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
    `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
    - a dictionary with one or several input Tensors associated to the input names given in the docstring:
    `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`

    Note that when creating models and layers with
    [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
    about any of this, as you can just pass inputs like you would to any other Python function!

    </Tip>

    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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
zUThe bare Mistral Model outputting raw hidden-states without any specific head on top.c                       e Zd ZeZdZy)TFMistralPreTrainedModelmodelN)rc   rd   re   r   r$  base_model_prefixrD   r5   r3   r&  r&    s    
 !Lr5   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 (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        past_key_values (`Cache` or `tuple(tuple(tf.Tensor))`, *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`.

            One formats is allowed:
            - Tuple of `tuple(tf.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
            cache format.

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

            If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
            have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
            of shape `(batch_size, sequence_length)`.
        inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
            model's internal embedding lookup matrix.
        use_cache (`bool`, *optional*):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                   4    e Zd Zdef fdZe ee      	 	 	 	 	 	 	 	 	 ddej                  de
ej                     de
ej                     de
eej                        de
ej                     de
e   d	e
e   d
e
e   de
e   deeef   fd              ZddZ xZS )TFMistralModelr   c                 P    t        |   |g|i | t        |d      | _        y )Nr'  r   )rE   rF   r   r'  rI   r   inputsrK   rL   s       r3   rF   zTFMistralModel.__init__  s(    3&3F3'W=
r5   r
  r   r   r  r  r   r   r  r  r   c
                 :    | j                  |||||||||		      }
|
S )N	r
  r   r   r  r  r   r   r  r  r'  )rI   r
  r   r   r  r  r   r   r  r  r   s              r3   ra   zTFMistralModel.call  s9     **)%+'/!5#  

 r5   c                     | j                   ry d| _         t        | dd       Nt        j                  | j                  j
                        5  | j                  j                  d        d d d        y y # 1 sw Y   y xY w)NTr'  )rT   r   r!   r   r'  rP   rW   rU   s     r3   rW   zTFMistralModel.build  sg    ::
4$'3tzz/ '

  &' ' 4' 's   A11A:r#  rb   )rc   rd   re   r   rF   r   r   MISTRAL_INPUTS_DOCSTRINGr!   r   r   r   r;   r   r   r   ra   rW   rf   rg   s   @r3   r*  r*    s    
>} > *+CD  $.2,059-1$(,0/3&*99 !+ ryy)	
 "$ryy/2  		* D> $D> 'tn d^ 
u//	0 E 2'r5   r*  c                       e Zd Z fdZd Zd Zd Zd Zd Zd Z	e
 eej                  d            	 	 	 	 	 	 	 	 	 	 dd	ej                  d
eej                     deej                     deeej                        deej                     deej                     dee   dee   dee   dee   deeef   fd              Z	 ddZddZ xZS )TFMistralForCausalLMc                 
   t        |   |g|i | t        |d      | _        |j                  | _        t
        j                  j                  |j                  dt        |j                        d      | _
        || _        y )Nr'  r   Flm_headr   kernel_initializerrP   )rE   rF   r   r'  r   r   r   r   r   initializer_ranger6  r   r,  s       r3   rF   zTFMistralForCausalLM.__init__&  sv    3&3F3'W=
 ++||)).v/G/GH	 * 
 r5   c                 .    | j                   j                  S rb   r'  r   r   s    r3   r  z)TFMistralForCausalLM.get_input_embeddings2      zz&&&r5   c                 &    || j                   _        y rb   r;  r  s     r3   r  z)TFMistralForCausalLM.set_input_embeddings5      "'

r5   c                     | j                   S rb   r6  r   s    r3   get_output_embeddingsz*TFMistralForCausalLM.get_output_embeddings8  s    ||r5   c                     || _         y rb   r@  )rI   new_embeddingss     r3   set_output_embeddingsz*TFMistralForCausalLM.set_output_embeddings;  s	    %r5   c                     || _         y rb   r0  )rI   decoders     r3   set_decoderz TFMistralForCausalLM.set_decoder>  s	    
r5   c                     | j                   S rb   r0  r   s    r3   get_decoderz TFMistralForCausalLM.get_decoderA  s    zzr5   batch_size, sequence_lengthr
  r   r   r  r  labelsr   r   r  r  r   c                    | j                  ||||||||	|
	      }|d   }| j                  |      }t        j                  |t        j                        }d}|(|ddddf   }|ddddf   }| j                  ||      }|
s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )a  
        Args:
            labels (`tf.Tensor` 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]`.
        r/  r   Nr   r   losslogitsr  r^   r  )
r'  r6  r!   r:   r<   hf_compute_lossr	   r  r^   r  )rI   r
  r   r   r  r  rK  r   r   r  r  r   r^   rO  rN  shifted_logitsoutputs                    r3   ra   zTFMistralForCausalLM.callD  s    0 **)%+'/!5#  

  
m,,#AssF^NAqrE]F''?DY,F)-)9TGf$EvE'#33!//))
 	
r5   c                    |rt        j                  |d d df   d      }|j                  dd       }|C|At         j                  j	                  |dd      }|rt        j                  |d d df   d      }|||||j                  d      dS )Nr   r   T)r    	exclusiver   )r
  r   r   r  r   )r!   r*   getr   cumsum)rI   r
  r  r   r  rK   r   s          r3   prepare_inputs_for_generationz2TFMistralForCausalLM.prepare_inputs_for_generation  s     yB'7<Izz.$7%,*>77>>.rT>RL!~~l1b5.A2F #,(.K0
 	
r5   c                    | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       ct        j                  | j                  j
                        5  | j                  j                  | j                  j                  f       d d d        y y # 1 sw Y   zxY w# 1 sw Y   y xY w)NTr'  r6  )
rT   r   r!   r   r'  rP   rW   r6  r   rG   rU   s     r3   rW   zTFMistralForCausalLM.build  s    ::
4$'3tzz/ '

  &'4D)5t||001 ?""DKK$;$;#=>? ? 6' '? ?   C %1C, C),C5
NNNNNNNNNN)NNNrb   )rc   rd   re   rF   r  r  rA  rD  rG  rI  r   r   r2  formatr!   r   r   r   r;   r   r   r	   ra   rW  rW   rf   rg   s   @r3   r4  r4  %  sC   
'(& *+C+J+JKh+ij  $.2,059-1&*$(,0/3&*7
997
 !+7
 ryy)	7

 "$ryy/27
  		*7
 #7
 D>7
 $D>7
 'tn7
 d^7
 
u..	/7
 k 7
t SW
*	?r5   r4  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                   x    e Zd Z fdZd Zd Ze eej                  d            	 	 	 	 	 	 	 	 	 	 dde
j                  dee
j                     dee
j                     deee
j                        d	ee
j                     d
ee
j                     dee   dee   dee   dee   deeef   fd              ZddZ xZS )"TFMistralForSequenceClassificationc                 
   t        |   |g|i | |j                  | _        t        |d      | _        t
        j                  j                  | j                  dt        |j                        d      | _
        || _        y )Nr'  r   Fscorer7  )rE   rF   
num_labelsr   r'  r   r   r   r   r9  r_  r   r,  s       r3   rF   z+TFMistralForSequenceClassification.__init__  st    3&3F3 ++'W=
\\''OO.v/G/GH	 ( 

 r5   c                 .    | j                   j                  S rb   r;  r   s    r3   r  z7TFMistralForSequenceClassification.get_input_embeddings  r<  r5   c                 &    || j                   _        y rb   r;  r  s     r3   r  z7TFMistralForSequenceClassification.set_input_embeddings  r>  r5   rJ  r
  r   r   r  r  rK  r   r   r  r  r   c                 `   | j                  ||||||||	|
	      }|d   }| j                  |      }t        |      }d}| j                  j                  d}n|t        j                  t        j                  t
        j                  j                  || j                  j                        |j                        d      dz
  }t        j                  |dk\  |t        j                  t        |d         |j                        dz
        }t        j                  ||dd      }n.d}t        j                  | j                  j                    d       d}|| j                  j                  |d   dk7  rt#        d	      t        j$                  |      s|d|d   |f   }| j'                  t        j(                  |dg      t        j(                  |d| j*                  g            }||n|}|
s|f|dd z   }||f|z   S |S t-        |||j.                  |j0                  |j2                  
      S )a  
        Args:
            labels (`tf.Tensor` 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]`.
        r/  r   Nr   r   r   )
batch_dimsr    z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`z=Cannot handle batch sizes > 1 if no padding token is defined.rM  )r'  r_  r   r   r   r!   argmaxr:   r   equalr   r'   r   r   r   rL   rc   r   	is_tensorrP  r   r`  r
   r  r^   r  )rI   r
  r   r   r  r  rK  r   r   r  r  transformer_outputsr^   rO  logits_shape	in_logitssequence_lengthsrN  pooled_logitsrR  s                       r3   ra   z'TFMistralForSequenceClassification.call  sA   . #jj)%+'/!5# ) 

 ,A.M*!&)	;;##+!$IIbggbggmmIt{{?W?W&XZcZiZijqst ! $&88$)$GGJy}57G7M7MNQRR$ 
 IIf.>1STU	#% ##~~../ 0^ ^ {{''/LOq4H !`aa<< 01"1|A#68H#HI	''

6B4(@"**YY[]a]l]lXmBnoD%.%:	#%(;AB(??F)-)9TGf$EvE1 /??-;;*55
 	
r5   c                    | j                   ry d| _         t        | dd       Mt        j                  | j                  j
                        5  | j                  j                  d        d d d        t        | dd       ct        j                  | j                  j
                        5  | j                  j                  | j                  j                  f       d d d        y y # 1 sw Y   zxY w# 1 sw Y   y xY w)NTr'  r_  )
rT   r   r!   r   r'  rP   rW   r_  r   rG   rU   s     r3   rW   z(TFMistralForSequenceClassification.build  s    ::
4$'3tzz/ '

  &'4$'3tzz/ =

  $++"9"9!;<= = 4' '= =rY  rZ  rb   )rc   rd   re   rF   r  r  r   r   r2  r[  r!   r   r   r   r;   r   r   r
   ra   rW   rf   rg   s   @r3   r]  r]    s0    
'( *+C+J+JKh+ij  $.2,059-1&*$(,0/3&*O
99O
 !+O
 ryy)	O

 "$ryy/2O
  		*O
 #O
 D>O
 $D>O
 'tnO
 d^O
 
u88	9O
 k O
b	=r5   r]  )r   rb   )r   ):r   r   r   typingr   r   r   r   
tensorflowr!   modeling_tf_outputsr   r	   r
   modeling_tf_utilsr   r   r   r   r   r   r   r   tf_utilsr   r   r   utilsr   r   r   configuration_mistralr   
get_loggerrc   r   _CONFIG_FOR_DOCr4   r@   r   LayerrB   ri   r   r   r   r   r   r   r   r   r   MISTRAL_START_DOCSTRINGr&  r2  r*  r4  r]  rD   r5   r3   <module>ry     s  (    / /  
	 	 	 S R 
 1 
		H	%!6"Au||)) A8(u||11 (.)8@5<<%% @<
[RYY 
[s 
[ryy 
[RE++ REjW:ELL.. W:t d&++ d& d&N( V [ 0  	 
B J [&'- &'	&'Rx?35Q x?v  o=)AC_ o=o=r5   