U
    5Af                     @   s  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!e"Z#dZ$d/ddZ%d0ddZ&G dd dej'j(Z)G dd dej'j(Z*dd Z+d1ddZ,G dd dej'j(Z-e	j.e/e	j.dddZ0G dd dej'j(Z1G dd  d ej'j(Z2eG d!d" d"ej'j(Z3d#Z4ed$e4G d%d& d&eZ5d'Z6ed$e4G d(d) d)e5Z7G d*d+ d+e5eZ8ed,e4G d-d. d.e5eZ9dS )2z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                 C   s   | \}}t ||ft j|j}t |}t |dddf |dddf kd|}|dkr~t jt j||f|d|gdd}|dkrt 	|d}t 	|d}t 
||dddg}n,t |ddddddf |d||| f}|S )zm
    Make causal mask used for bi-directional self-attention, supporting both static and dynamic shapes.
    Ng        r   dtypeaxisr   )tffillZdtypesZas_dtypeminrangewhereconcatzerosexpand_dimsZtilebroadcast_to)Zinput_ids_shaper   past_key_values_lengthbsztgt_lenmaskZ	mask_cond r,   S/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/mistral/modeling_tf_mistral.py_make_causal_mask9   s    
* ,r.   c                 C   s|   t | \}}|dk	r|n|}tt| dd}t||d||g}dt|| }tt|ttjt |tjj	d|S )z_
    Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
    Nr         ?)Zdimsvalue)
r   r   r&   r'   castr#   boolr    float32r!   )r+   r   r*   r)   Zsrc_lenZexpanded_maskZinverted_maskr,   r,   r-   _expand_maskT   s    
  r4   c                       s0   e Zd Zd	 fdd	Zd
ddZdd Z  ZS )TFMistralRMSNormư>c                    s   t  jf | || _|| _dS )z?
        TFMistralRMSNorm is equivalent to T5LayerNorm
        N)super__init__hidden_sizevariance_epsilon)selfr9   epskwargs	__class__r,   r-   r8   f   s    zTFMistralRMSNorm.__init__Nc                 C   s(   | j d| jdd| _| jrd S d| _d S )Nweightones)nameshapeZinitializerT)Z
add_weightr9   r@   builtr;   input_shaper,   r,   r-   buildn   s    zTFMistralRMSNorm.buildc                 C   sT   |j }t|tj}tjt|ddd}t|t|| j }| j	t|| S )Nr   T)r   Zkeepdims)
r   r   r1   r3   Zreduce_meanZsquaredividesqrtr:   r@   )r;   hidden_statesZinput_dtypeZvariancer,   r,   r-   callx   s
    zTFMistralRMSNorm.call)r6   )N)__name__
__module____qualname__r8   rG   rK   __classcell__r,   r,   r>   r-   r5   e   s   

r5   c                       s(   e Zd Zd fdd	Zd	ddZ  ZS )
TFMistralRotaryEmbedding   '  c                    sL   t  jf | || _|| _|| _d| jtjd| jdtjd| j   | _d S )Nr/   r      )startlimitdeltar   )	r7   r8   dimmax_position_embeddingsbaser   r"   r3   inv_freq)r;   rW   rX   rY   r=   r>   r,   r-   r8      s
    z!TFMistralRotaryEmbedding.__init__Nc                 C   s   t t j|t jd| jj}t d|| j}t j||gdd}t t ||j}t t 	||j}|d | }t j||jd}|d | }t j||jd}||fS )Nr   zi,j->ijr   r   )
r   r1   r"   int64rZ   r   Zeinsumr$   cossin)r;   xseq_lentZfreqsZembZ
cos_valuesZ
sin_valuesr,   r,   r-   rK      s    zTFMistralRotaryEmbedding.call)rQ   rR   )N)rL   rM   rN   r8   rK   rO   r,   r,   r>   r-   rP      s   rP   c                 C   sD   t | d d }| dd|f }| d|df }tj| |gddS )z*Rotates half the hidden dims of the input.r   rS   .Nr   )r   r   r$   )r^   Z
mid_lengthx1Zx2r,   r,   r-   rotate_half   s    rb   c                 C   sX   t t |||}t t |||}| | t| |  }|| t||  }||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&   gatherrb   )qkr\   r]   position_idsZunsqueeze_dimZq_embedZk_embedr,   r,   r-   apply_rotary_pos_emb   s
    rg   c                       s.   e Zd Z fddZdd ZdddZ  ZS )	TFMistralMLPc                    sv   t  jf | || _|j| _|j| _tjj| jddd| _tjj| jddd| _	tjj| jddd| _
t|j| _d S )NF	gate_projuse_biasrB   up_proj	down_proj)r7   r8   configr9   intermediate_sizer   layersDenseri   rl   rm   r   Z
hidden_actact_fnr;   rn   r=   r>   r,   r-   r8      s    zTFMistralMLP.__init__c                 C   s    |  | | || | S N)rm   rr   ri   rl   )r;   r^   r,   r,   r-   rK      s    zTFMistralMLP.callNc              	   C   s   | j r
d S d| _ t| dd d k	rJt| jj | j| jf W 5 Q R X t| dd d k	rt| jj | j| jf W 5 Q R X t| dd d k	rt| j	j | j	| j
f W 5 Q R X d S )NTri   rl   rm   )rD   getattrr   
name_scoperi   rB   rG   r9   rl   rm   ro   rE   r,   r,   r-   rG      s    zTFMistralMLP.build)N)rL   rM   rN   r8   rK   rG   rO   r,   r,   r>   r-   rh      s   
rh   )rJ   n_repreturnc                 C   sP   t | \}}}}|dkr| S t| d} tj| |dd} t| ||| ||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   rS   )Zrepeatsr   )r   r   r&   repeatreshape)rJ   rw   batchnum_key_value_headsslenhead_dimr,   r,   r-   	repeat_kv   s    r   c                       s   e Zd ZdZdeee d fddZej	eedddZ
dej	eej	 eej	 eeej	  ee ee eej	eej	 eeej	  f d
ddZdddZ  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".
    Nrn   	layer_idxc                    sN  t  jf | || _|| _|d kr8td| jj d |j| _|j	| _
| j| j
 | _|j| _| j
| j | _|j| _|j| _d| _|j| _| j| j
 | jkrtd| j d| j
 dtjj| j
| j ddd	| _tjj| j| j dd
d	| _tjj| j| j ddd	| _tjj| jddd	| _t| j| j| jdd| _tjj| jd| _d S )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_projrj   k_projv_projo_proj
rotary_emb)rX   rY   rB   )Zrate)r7   r8   rn   r   loggerwarning_oncer?   rL   r9   Znum_attention_heads	num_headsr~   r|   num_key_value_groupsrX   Z
rope_thetaZ	is_causalZattention_dropout
ValueErrorr   rp   rq   r   r   r   r   rP   r   ZDropoutdropoutr;   rn   r   r=   r>   r,   r-   r8      s>    zTFMistralAttention.__init__)tensorr_   r)   c                 C   s*   t |||| j| jf}t j|dd}|S )Nr   rS   r   r   perm)r   rz   r   r~   	transpose)r;   r   r_   r)   r,   r,   r-   _shape  s    zTFMistralAttention._shapeFrJ   attention_maskrf   past_key_valueoutput_attentions	use_cacherx   c                 K   s  d|krt d t|\}	}
}| |}| |}| |}tjt||	|
| j	| j
fdd}tjt||	|
| j| j
fdd}tjt||	|
| j| j
fdd}t|d }|d k	r||d jd 7 }| j||d\}}t|||||d\}}|d k	r(tj|d |gd	d
}tj|d |gd	d
}|r6||fnd }t|| j}t|| j}tj||ddt| j
 }|d k	r|| }t|dd
}t||j}| j||d}t||}tj|dd}t||	|
| jf}| |}|sd }|||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   )r^   r_   )rd   re   r\   r]   rf   rS   r   r   T)Ztranspose_br   )training)warningswarnr   r   r   r   r   r   rz   r   r~   r|   rC   r   rg   r$   r   r   matmulmathrI   r   r1   r   r   r9   r   )r;   rJ   r   rf   r   r   r   r   r=   r)   Zq_len_Zquery_statesZ
key_statesZvalue_statesZ
kv_seq_lenr\   r]   Zattn_weightsZattn_outputr,   r,   r-   rK     sp    


   




zTFMistralAttention.callc              	   C   s  | j r
d S d| _ t| dd d k	rJt| jj | j| jf W 5 Q R X t| dd d k	rt| jj | j| jf W 5 Q R X t| dd d k	rt| j	j | j	| jf W 5 Q R X t| dd d k	rt| j
j | j
| j| j f W 5 Q R X d S )NTr   r   r   r   )rD   ru   r   rv   r   rB   rG   r9   r   r   r   r   r~   rE   r,   r,   r-   rG   k  s    zTFMistralAttention.build)N)NNNFFN)N)rL   rM   rN   __doc__r   r   intr8   r   Tensorr   r   r2   rK   rG   rO   r,   r,   r>   r-   r      s&   '      Qr   c                       s   e Zd Zeed fddZdejeej eej ee	ej  ee
 ee
 e	ejee	ejejf  f dddZdd	d
Z  ZS )TFMistralDecoderLayerr   c                    s`   t  jf | |j| _t||dd| _t|dd| _t|j|jdd| _	t|j|jdd| _
d S )N	self_attnrB   mlpinput_layernormr<   rB   post_attention_layernorm)r7   r8   r9   r   r   rh   r   r5   rms_norm_epsr   r   r   r>   r,   r-   r8   ~  s      zTFMistralDecoderLayer.__init__NFr   c                 K   s   d|krt d |}| |}| j||||||d\}}	}
|| }|}| |}| |}|| }|f}|rx||	f7 }|r||
f7 }|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   )rJ   r   rf   r   r   r   )r   r   r   r   r   r   )r;   rJ   r   rf   r   r   r   r=   ZresidualZself_attn_weightsZpresent_key_valueoutputsr,   r,   r-   rK     s2    




zTFMistralDecoderLayer.callc              	   C   s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	rt| jj | jd  W 5 Q R X t| dd d k	rt| j	j | j	d  W 5 Q R X d S )NTr   r   r   r   )
rD   ru   r   rv   r   rB   rG   r   r   r   rE   r,   r,   r-   rG     s    zTFMistralDecoderLayer.build)NNNFF)N)rL   rM   rN   r   r   r8   r   r   r   r   r2   rK   rG   rO   r,   r,   r>   r-   r   }  s         ;r   c                       s   e Zd ZdZeZed fddZdd Zdd Zd	d
 Z	e
dejeej eej eeej  eej ee ee ee ee eeef d
ddZdddZ  ZS )TFMistralMainLayerz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`]

    Args:
        config: MistralConfig
    rn   c                    s~   t  jf |  j| _ j| _ j| _tjj j jdd| _	 fddt
 jD | _ j| _t j jdd| _ | _d S )Nembed_tokens)Z	input_dimZ
output_dimrB   c                    s    g | ]}t  |d | dqS )zlayers.r   )r   ).0r   r   r,   r-   
<listcomp>  s   z/TFMistralMainLayer.__init__.<locals>.<listcomp>normr   )r7   r8   pad_token_idZpadding_idx
vocab_sizer9   r   rp   Z	Embeddingr   r"   Znum_hidden_layersZ_attn_implementationr5   r   r   rn   rs   r>   r   r-   r8     s    
zTFMistralMainLayer.__init__c                 C   s   | j S rt   r   r;   r,   r,   r-   get_input_embeddings  s    z'TFMistralMainLayer.get_input_embeddingsc                 C   s
   || _ d S rt   r   r;   r0   r,   r,   r-   set_input_embeddings  s    z'TFMistralMainLayer.set_input_embeddingsc                 C   sH   d }t ||j|d}|d k	rDt||j|d d}|d kr<|n|| }|S )N)r(   r   )r*   )r.   r   r4   )r;   r   rF   inputs_embedsr(   Zcombined_attention_maskZexpanded_attn_maskr,   r,   r-   _prepare_decoder_attention_mask  s    z2TFMistralMainLayer._prepare_decoder_attention_maskN
	input_idsr   rf   past_key_valuesr   r   r   output_hidden_statesreturn_dictrx   c
              	   C   s0  |d k	r|d k	rt dn6|d k	r0t|\}
}n |d k	rHt|\}
}}nt d|}d}|d k	r|t|d d d }|| }|d krtj||| tjd}tt|dd|f}ntt|d|ftj}|d krt|| j	j
 | |}|d krtj|
|ftjd}| ||
|f||}|}|r.dnd }|r<dnd }|rJdnd }t| jD ]~\}}|rp||f7 }|d k	r|| nd }|||||||d	}|d }|r|||rdnd
 f7 }|rX||d
 f7 }qX| |}|r||f7 }|r|nd }|	s tdd ||||fD S t||||dS )NzTYou cannot specify both decoder_input_ids and decoder_inputs_embeds at the same timezEYou have to specify either decoder_input_ids or decoder_inputs_embedsr   rS   )rT   rU   r   r   r   r,   )r   rf   r   r   r   r   c                 s   s   | ]}|d k	r|V  qd S rt   r,   )r   vr,   r,   r-   	<genexpr>g  s      z*TFMistralMainLayer.call.<locals>.<genexpr>)Zlast_hidden_stater   rJ   
attentions)r   r   r   r"   r[   rz   r&   r1   r   rn   r   r   rA   r2   r   	enumeraterp   r   tupler   )r;   r   r   rf   r   r   r   r   r   r   Z
batch_sizeZ
seq_lengthr   Zseq_length_with_pastr(   rJ   Zall_hidden_statesZall_self_attnsZnext_decoder_cacheidxZdecoder_layerr   Zlayer_outputsZ
next_cacher,   r,   r-   rK     s    
  

   
	

zTFMistralMainLayer.callc              
   C   s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	r|t| jj | jd  W 5 Q R X t| dd d k	r| jD ]&}t|j |d  W 5 Q R X qd S )NTr   r   rp   )	rD   ru   r   rv   r   rB   rG   r   rp   )r;   rF   Zlayerr,   r,   r-   rG   o  s    
zTFMistralMainLayer.build)	NNNNNNNNN)N)rL   rM   rN   r   r   config_classr8   r   r   r   r   r   r   r   r   r2   r   r   r   rK   rG   rO   r,   r,   r>   r-   r     s:            
^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                   @   s   e Zd ZeZdZdS )TFMistralPreTrainedModelmodelN)rL   rM   rN   r   r   Zbase_model_prefixr,   r,   r,   r-   r     s   r   a1  
    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`.

            Two formats are allowed:
            - a [`~cache_utils.Cache`] instance;
            - 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                       s   e Zd Zed fddZeeed
ej	e
ej	 e
ej	 e
eej	  e
ej	 e
e e
e e
e e
e eeef d
ddZddd	Z  ZS )TFMistralModelr   c                    s&   t  j|f|| t|dd| _d S )Nr   r   )r7   r8   r   r   r;   rn   inputsr=   r>   r,   r-   r8     s    zTFMistralModel.__init__Nr   c
                 C   s    | j |||||||||	d	}
|
S )N	r   r   rf   r   r   r   r   r   r   r   )r;   r   r   rf   r   r   r   r   r   r   r   r,   r,   r-   rK     s    zTFMistralModel.callc              	   C   sJ   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X d S )NTr   )rD   ru   r   rv   r   rB   rG   rE   r,   r,   r-   rG     s    zTFMistralModel.build)	NNNNNNNNN)N)rL   rM   rN   r   r8   r   r   MISTRAL_INPUTS_DOCSTRINGr   r   r   r   r2   r   r   r   rK   rG   rO   r,   r,   r>   r-   r     s2            
r   c                       s   e Zd Z fddZdd Zdd Zdd Zd	d
 Zdd Zdd Z	e
eeddejeej eej eeej  eej eej ee ee ee ee eeef dddZdddZdddZ  ZS )TFMistralForCausalLMc                    sR   t  j|f|| t|dd| _|j| _tjj|jdt|j	dd| _
|| _d S )Nr   r   Flm_headrk   Zkernel_initializerrB   )r7   r8   r   r   r   r   rp   rq   r   initializer_ranger   rn   r   r>   r,   r-   r8   '  s    zTFMistralForCausalLM.__init__c                 C   s   | j jS rt   r   r   r   r,   r,   r-   r   3  s    z)TFMistralForCausalLM.get_input_embeddingsc                 C   s   || j _d S rt   r   r   r,   r,   r-   r   6  s    z)TFMistralForCausalLM.set_input_embeddingsc                 C   s   | j S rt   r   r   r,   r,   r-   get_output_embeddings9  s    z*TFMistralForCausalLM.get_output_embeddingsc                 C   s
   || _ d S rt   r   )r;   Znew_embeddingsr,   r,   r-   set_output_embeddings<  s    z*TFMistralForCausalLM.set_output_embeddingsc                 C   s
   || _ d S rt   r   )r;   decoderr,   r,   r-   set_decoder?  s    z TFMistralForCausalLM.set_decoderc                 C   s   | j S rt   r   r   r,   r,   r-   get_decoderB  s    z TFMistralForCausalLM.get_decoderbatch_size, sequence_lengthNr   r   rf   r   r   labelsr   r   r   r   rx   c                 C   s   | j ||||||||	|
d	}|d }| |}t|tj}d}|dk	r||ddddf }|ddddf }| ||}|
s|f|dd  }|dk	r|f| S |S t|||j|j|j	d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   rJ   r   )
r   r   r   r1   r3   hf_compute_lossr   r   rJ   r   )r;   r   r   rf   r   r   r   r   r   r   r   r   rJ   r   r   Zshifted_logitsoutputr,   r,   r-   rK   E  s:    
zTFMistralForCausalLM.callc                 K   s|   |rt |d d df d}|dd }|d k	rf|d krft jj|ddd}|rft |d d df d}|||||ddS )Nr   rf   T)r   Z	exclusiver   )r   r   rf   r   r   )r   r&   getr   Zcumsum)r;   r   r   r   r   r=   rf   r,   r,   r-   prepare_inputs_for_generation  s    z2TFMistralForCausalLM.prepare_inputs_for_generationc              	   C   s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	rt| jj | j| jj	f W 5 Q R X d S )NTr   r   )
rD   ru   r   rv   r   rB   rG   r   rn   r9   rE   r,   r,   r-   rG     s    zTFMistralForCausalLM.build)
NNNNNNNNNN)NNN)N)rL   rM   rN   r8   r   r   r   r   r   r   r   r   r   formatr   r   r   r   r2   r   r   r   rK   r   rG   rO   r,   r,   r>   r-   r   &  sJ             
:     
r   a  
    The Mistral Model transformer with a sequence classification head on top (linear layer).

    [`MistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    c                       s   e Zd Z fddZdd Zdd Zeee	dde
jee
j ee
j eee
j  ee
j ee
j ee ee ee ee eeef d	d
dZdddZ  ZS )"TFMistralForSequenceClassificationc                    sR   t  j|f|| |j| _t|dd| _tjj| jdt|j	dd| _
|| _d S )Nr   r   Fscorer   )r7   r8   
num_labelsr   r   r   rp   rq   r   r   r   rn   r   r>   r,   r-   r8     s    z+TFMistralForSequenceClassification.__init__c                 C   s   | j jS rt   r   r   r,   r,   r-   r     s    z7TFMistralForSequenceClassification.get_input_embeddingsc                 C   s   || j _d S rt   r   r   r,   r,   r-   r     s    z7TFMistralForSequenceClassification.set_input_embeddingsr   Nr   c                 C   s  | j ||||||||	|
d	}|d }| |}t|}d}| jjdkrLd}n|dk	rtjttj	|| jj|j
ddd }t|dk|tt|d |j
d }tj||ddd}nd}t| jj d d}|dk	rH| jjdkr|d dkrtd	t|s$|d|d |f }| t|dgt|d| jg}|dk	rV|n|}|
s|f|dd  }|dk	r|f| S |S t|||j|j|jd
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   )Z
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.r   )r   r   r   rn   r   r   Zargmaxr1   r   equalr   r#   rc   r   r   r?   rL   r   Z	is_tensorr   rz   r   r	   r   rJ   r   )r;   r   r   rf   r   r   r   r   r   r   r   Ztransformer_outputsrJ   r   Zlogits_shapeZ	in_logitsZsequence_lengthsr   Zpooled_logitsr   r,   r,   r-   rK     sd    
$
$z'TFMistralForSequenceClassification.callc              	   C   s   | j r
d S d| _ t| dd d k	rFt| jj | jd  W 5 Q R X t| dd d k	rt| jj | j| jj	f W 5 Q R X d S )NTr   r   )
rD   ru   r   rv   r   rB   rG   r   rn   r9   rE   r,   r,   r-   rG     s    z(TFMistralForSequenceClassification.build)
NNNNNNNNNN)N)rL   rM   rN   r8   r   r   r   r   r   r   r   r   r   r   r2   r   r   r	   rK   rG   rO   r,   r,   r>   r-   r     s:             
Qr   )r   )N)r   ):r   r   r   typingr   r   r   r   Z
tensorflowr   Zmodeling_tf_outputsr   r   r	   Zmodeling_tf_utilsr
   r   r   r   r   r   r   r   Ztf_utilsr   r   r   utilsr   r   r   Zconfiguration_mistralr   Z
get_loggerrL   r   Z_CONFIG_FOR_DOCr.   r4   rp   ZLayerr5   rP   rb   rg   rh   r   r   r   r   r   r   ZMISTRAL_START_DOCSTRINGr   r   r   r   r   r,   r,   r,   r-   <module>   sV   (



	
 Z (+F){