U
    5Af{                     @   s  d Z ddlmZmZ ddlmZ ddlZddlm	Z
 ddl	ZddlmZmZmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ d	d
lmZmZmZmZ d	dlmZmZm Z m!Z! d	dl"m#Z#m$Z$ ddl%m&Z& e!'e(Z)dZ*dZ+dZ,dZ-dZ.G dd dej/Z0G dd dej/Z1G dd dej/Z2dd Z3dd Z4dd Z5G d d! d!ej/Z6G d"d# d#ej/Z7G d$d% d%eZ8G d&d' d'ej/Z9G d(d) d)ej/Z:e#d*e-G d+d, d,e8Z;e e;e,ee*e+d- G d.d/ d/ej/Z<e#d0e-G d1d2 d2e8Z=e e=e,ee*e+d- dS )3zFlax Mistral model.    )OptionalTupleN)
FrozenDictfreezeunfreeze)combine_masksmake_causal_mask)dot_product_attention_weights)flatten_dictunflatten_dict)lax   )FlaxBaseModelOutputFlaxBaseModelOutputWithPastFlaxCausalLMOutput%FlaxCausalLMOutputWithCrossAttentions)ACT2FNFlaxPreTrainedModelappend_call_sample_docstringlogging)add_start_docstrings%add_start_docstrings_to_model_forward   )MistralConfigr   zmistralai/Mistral-7B-v0.1zksmcg/Mistral-tinya  

    This model inherits from [`FlaxPreTrainedModel`]. 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 Flax Linen
    [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
    regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.

    Finally, this model supports inherent JAX features such as:

    - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
    - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
    - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
    - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)

    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 [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
        dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
            The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16`, or
            `jax.numpy.bfloat16`.

            This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
            specified all the computation will be performed with the given `dtype`.

            **Note that this only specifies the dtype of the computation and does not influence the dtype of model
            parameters.**

            If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
            [`~FlaxPreTrainedModel.to_bf16`].
a
  
    Args:
        input_ids (`numpy.ndarray` of shape `(batch_size, input_ids_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 (`numpy.ndarray` 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 (`numpy.ndarray` 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 (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
            Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
            auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
        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                   @   s6   e Zd ZU eed< ejZejed< dd Zdd Z	dS )FlaxMistralRMSNormconfigdtypec                 C   s&   | j j| _| ddd | j j| _d S )Nweightc                 S   s
   t |S N)jnpones)_shape r#   U/tmp/pip-unpacked-wheel-zw5xktn0/transformers/models/mistral/modeling_flax_mistral.py<lambda>       z*FlaxMistralRMSNorm.setup.<locals>.<lambda>)r   Zrms_norm_epsepsilonparamhidden_sizer   selfr#   r#   r$   setup   s    
zFlaxMistralRMSNorm.setupc                 C   sT   t j|t jd}t |d}|jddd}|t || j  }| jt j|| jd S )Nr      T)Zkeepdims)	r   asarrayfloat32powerZmeansqrtr'   r   r   )r+   hidden_statesZvariancer#   r#   r$   __call__   s
    zFlaxMistralRMSNorm.__call__N
__name__
__module____qualname__r   __annotations__r   r1   r   r,   r5   r#   r#   r#   r$   r      s   
r   c                   @   s6   e Zd ZU eed< ejZejed< dd Zdd Z	dS )FlaxMistralRotaryEmbeddingr   r   c                 C   s$   | j j| j j }t| j j|| _d S r   )r   r)   num_attention_headscreate_sinusoidal_positionsmax_position_embeddingssincos)r+   head_dimr#   r#   r$   r,      s    z FlaxMistralRotaryEmbedding.setupc                 C   s^   | j | }tj|ddd\}}t|||}t|||}tj|| jd}tj|| jd}||fS )Nr.   r/   Zaxisr-   )r?   r   splitapply_rotary_pos_embr0   r   )r+   keyqueryposition_idsr?   sin_poscos_posr#   r#   r$   r5      s    
z#FlaxMistralRotaryEmbedding.__call__Nr6   r#   r#   r#   r$   r;      s   
r;   c                   @   s6   e Zd ZU eed< ejZejed< dd Zdd Z	dS )FlaxMistralMLPr   r   c                 C   s   | j j}| j jd k	r| j jnd| }tjj| j j}t| j j	 | _
tj|d| j|d| _tj|d| j|d| _tj|d| j|d| _d S )N   Fuse_biasr   kernel_init)r   r)   Zintermediate_sizejaxnninitializersnormalinitializer_ranger   Z
hidden_actactDenser   	gate_proj	down_projup_proj)r+   Z	embed_dimZ	inner_dimrM   r#   r#   r$   r,      s    zFlaxMistralMLP.setupc                 C   s,   |  |}| | |}| || }|S r   )rW   rS   rU   rV   )r+   r4   Zup_proj_statesZgate_statesr#   r#   r$   r5      s    
zFlaxMistralMLP.__call__Nr6   r#   r#   r#   r$   rI      s   
rI   c                 C   s   | | t | |  S r   )rotate_half)tensorrG   rH   r#   r#   r$   rC      s    rC   c                 C   s   ddt d|d|   }t dt | |d}t j||fdd}t jt |d d d d d f t |d d d d d f fdd}t|d d d d d | f S )	Ng      ?i'  r   r.   zi , j -> i jr1   r/   rA   )	nparangeeinsumastypeconcatenatesincosr   array)num_posZdimZinv_freqZfreqsZemboutr#   r#   r$   r=      s
    Br=   c                 C   sD   t j| d| jd d df  | dd| jd d f fdd}|S )z*Rotates half the hidden dims of the input..r/   r.   NrA   )r   r^   r"   )rY   Zrotate_half_tensorr#   r#   r$   rX      s
    4 rX   c                
   @   s   e Zd ZU eed< ejZejed< dd Zdd Z	dd Z
ejd	d
 Zdejeej eej eeeeejejf dddZdS )FlaxMistralAttentionr   r   c                 C   s2  | j }|j| _|j| _| j| j | _|j| _| j| j | _|j| _| jt	j
k	| _|j| _| j| j | jkrtd| j d| j dtj| j| j d| jd| _tj| j| j d| jd| _tj| j| j d| jd| _tj| jd| jd| _tt	jd|jfdddd}t	j||j d	| _t|| jd| _d S )
Nz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).F)rL   r   r   boolr-   )k)r   r)   r<   	num_headsr@   num_key_value_headsnum_key_value_groupsr>   r   r   r1   attention_softmax_in_fp32Z
rope_theta
ValueErrorrO   rT   q_projk_projv_projo_projr   r    ZtriuZsliding_windowcausal_maskr;   
rotary_emb)r+   r   Zcasual_maskr#   r#   r$   r,      s(    zFlaxMistralAttention.setupc                 C   s   | |jd d || jf S Nr.   )reshaper"   r@   )r+   r4   rg   r#   r#   r$   _split_heads   s    z!FlaxMistralAttention._split_headsc                 C   s   | |jd d | jf S rr   )rs   r"   r)   )r+   r4   r#   r#   r$   _merge_heads   s    z!FlaxMistralAttention._merge_headsc                 C   s   |  dd}| ddtj|j|j}| ddtj|j|j}| dddd }|r|jj^ }	}
}}|j}dt|	 |ddf }t	|j||}t	|j||}||_||_|jd	 }|j| |_t
t|
|| k t|	d	||
f }t||}|||fS )
a[  
        This function takes projected key, value states from a single input token and concatenates the states to cached
        states from previous steps. This function is slighly adapted from the official Flax repository:
        https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
        cache
cached_keycached_valuecache_indexc                   S   s   t jdt jdS )Nr   r-   )r   ra   Zint32r#   r#   r#   r$   r%     r&   z<FlaxMistralAttention._concatenate_to_cache.<locals>.<lambda>)r   r   r   )has_variablevariabler   zerosr"   r   valuelenr   dynamic_update_slicebroadcast_tor[   tupler   )r+   rD   r}   rE   attention_maskZis_initializedrw   rx   ry   Z
batch_dims
max_lengthrg   Zdepth_per_headZ	cur_indexindicesZnum_updated_cache_vectorsZpad_maskr#   r#   r$   _concatenate_to_cache   s(    	

z*FlaxMistralAttention._concatenate_to_cacheNTF)r4   r   rF   deterministicoutput_attentions
init_cachereturnc              
   C   s2  |  |}| |}| |}	| || j}| || j}| |	| j}	| |||\}}|jd |jd  }
}| ddr| j	d d }| j	d d jd }t
| jdd|dfdd|
|f}n"| jd d d d d |
d |f }|jd }t||f|jdd   }ttj|dd|j}t||}| dds>|rT| ||	||\}}	}tj|| jdd}tj|	| jdd}	t
|dkt|jd	| jt|jt| jj| j}| jrtjn| j}t||||| jj|d
}| jr|| j}td||	}|  |}| !|}|r(||fn|f}|S )Nr   rv   rw   ry   r   )rA   r.   g        )Zbiasr   Zdropout_rater   z...hqk,...khd->...qhd)"rl   rm   rn   rt   rg   rh   rq   r"   rz   	variablesr   Zdynamic_slicerp   r   r   Zexpand_dimsr   r   repeatri   selectfullr]   r   Zfinfominrj   r1   r	   r   Zattention_dropoutr\   ru   ro   )r+   r4   r   rF   r   r   r   Zquery_statesZ
key_statesZvalue_statesZquery_lengthZ
key_lengthZ
mask_shiftZmax_decoder_lengthrp   
batch_sizeZattention_biasZattention_dtypeZattn_weightsattn_outputoutputsr#   r#   r$   r5     sf    	


 
 
"

   
	

zFlaxMistralAttention.__call__)NNTFF)r7   r8   r9   r   r:   r   r1   r   r,   rt   ru   rO   compactr   Zndarrayr   re   r   r5   r#   r#   r#   r$   rd      s*   

"     rd   c                   @   sB   e Zd ZU eed< ejZejed< dd Zde	e	e	dd	d
Z
dS )FlaxMistralDecoderLayerr   r   c                 C   sL   t | j| jd| _t| j| jd| _t | j| jd| _t| j| jd| _d S )Nr-   )	r   r   r   input_layernormrd   	self_attnpost_attention_layernormrI   mlpr*   r#   r#   r$   r,   f  s    zFlaxMistralDecoderLayer.setupNTF)r   r   r   c           
      C   sf   |}|  |}| j||||||d}|d }	||	 }|}| |}| |}|| }|f|dd   S )Nr   rF   r   r   r   r   r   )r   r   r   r   )
r+   r4   r   rF   r   r   r   Zresidualr   r   r#   r#   r$   r5   l  s"    	
	

z FlaxMistralDecoderLayer.__call__)NNTFFr7   r8   r9   r   r:   r   r1   r   r,   re   r5   r#   r#   r#   r$   r   b  s   
	     r   c                
       s   e Zd ZU dZeZdZdZej	e
d< ddejdfeeeejed fd	d
ZdejjeeedddZdd Zeedeeejjeee ee ee dddZ  ZS )FlaxMistralPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    modelNmodule_class)r   r   r   T)r   input_shapeseedr   _do_initc                    s2   | j f ||d|}t j||||||d d S )N)r   r   )r   r   r   r   )r   super__init__)r+   r   r   r   r   r   kwargsmodule	__class__r#   r$   r     s    	z#FlaxMistralPreTrainedModel.__init__)rngr   paramsr   c                 C   s   t j|dd}t |}t t t |jd |}tj	|\}}||d}	| j
j|	|||ddd }
|d k	rtt|
}
tt|}| jD ]}|
| ||< qt | _tt|S |
S d S )Ni4r-   r/   )r   dropoutF)return_dictr   )r   r|   	ones_liker   r[   
atleast_2dr"   rN   randomrB   r   initr
   r   Z_missing_keyssetr   r   )r+   r   r   r   	input_idsr   rF   Z
params_rngdropout_rngrngsZrandom_paramsZmissing_keyr#   r#   r$   init_weights  s    


z'FlaxMistralPreTrainedModel.init_weightsc                 C   sd   t ||f}t |}t t t |jd |j}| jjt	j
d|||ddd}t|d S )aW  
        Args:
            batch_size (`int`):
                batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
            max_length (`int`):
                maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
                cache.
        r/   r   FT)r   r   rv   )r   r    r   r   r[   r   r"   r   r   rN   r   PRNGKeyr   )r+   r   r   r   r   rF   Zinit_variablesr#   r#   r$   r     s    

 
     z%FlaxMistralPreTrainedModel.init_cacheF)r   past_key_valuesr   trainr   output_hidden_statesr   c                 C   s  |d k	r|n| j j}|	d k	r |	n| j j}	|
d k	r4|
n| j j}
|j\}}|d kr|d k	r^tdtt|d d d f ||f}|d krt	||f}i }|d k	r||d< d|p| j
i}|r||d< dg}nd}| jj|tj|ddtj|ddtj|dd| d||	|
||d}|d k	r>|
r>|\}}t|d |d	< |S |d k	r||
s||\}}|d d
 t|d f |d
d   }|S )NzCMake sure to provide `position_ids` when passing `past_key_values`.r   r   rv   Fr   r-   )r   mutabler   r   )r   r   r   r   r"   rk   r   r   r[   r    r   r   applyra   r   )r+   r   r   rF   r   r   r   r   r   r   r   r   Zsequence_lengthr   inputsr   r   r#   r#   r$   r5     sP    
"&z#FlaxMistralPreTrainedModel.__call__)N)	NNNNNFNNN)r7   r8   r9   __doc__r   Zconfig_classZbase_model_prefixr   rO   Moduler:   r   r1   r   intr   re   r   rN   r   r   r   r   r   r   MISTRAL_INPUTS_DOCSTRINGdictr   r5   __classcell__r#   r#   r   r$   r     sH   
         r   c                   @   sF   e Zd ZU eed< ejZejed< dd Zde	e	e	e	e	dd	d
Z
dS )FlaxMistralLayerCollectionr   r   c                    s     fddt  jjD  _d S )Nc                    s"   g | ]}t  j jt|d qS ))r   name)r   r   r   str).0ir*   r#   r$   
<listcomp>  s   z4FlaxMistralLayerCollection.setup.<locals>.<listcomp>)ranger   Znum_hidden_layersblocksr*   r#   r*   r$   r,     s    

z FlaxMistralLayerCollection.setupNTFr   r   r   r   r   c	              	   C   sn   |rdnd }	|rdnd }
| j D ]@}|r0|
|f7 }
|||||||d}|d }|r|	|d f7 }	q||
|	f}|S )Nr#   r   r   r   )r   )r+   r4   r   rF   r   r   r   r   r   Zall_attentionsall_hidden_statesblockZlayer_outputsr   r#   r#   r$   r5     s$    


z#FlaxMistralLayerCollection.__call__)NNTFFFFr   r#   r#   r#   r$   r     s"   
	       r   c                   @   sD   e Zd ZU eed< ejZejed< dd Zde	e	e	e	dd	d
Z
dS )FlaxMistralModuler   r   c                 C   sb   | j j| _tjjj| j jd}tj| j j| j|| j	d| _
t| j | j	d| _t| j | j	d| _d S )Nstddev)embedding_initr   r-   )r   r)   rN   rO   rP   rQ   rR   ZEmbed
vocab_sizer   embed_tokensr   layersr   norm)r+   r   r#   r#   r$   r,   E  s    
zFlaxMistralModule.setupNTF)r   r   r   r   c	              
   C   s   |  |d}	| j|	|||||||d}
|
d }| |}|rd|
d |f }||f|
dd   }
n|f|
dd   }
|stdd |
D S t||
d |
d d	S )
Nr   rF   r   r   r   r   r   r   r   r   r.   c                 s   s   | ]}|d k	r|V  qd S r   r#   )r   vr#   r#   r$   	<genexpr>s  s      z-FlaxMistralModule.__call__.<locals>.<genexpr>r/   )Zlast_hidden_stater4   
attentions)r   r]   r   r   r   r   )r+   r   r   rF   r   r   r   r   r   Zinput_embedsr   r4   r   r#   r#   r$   r5   Q  s0    
zFlaxMistralModule.__call__)NNTFFFTr   r#   r#   r#   r$   r   A  s    
       r   zaThe bare Mistral Model transformer outputting raw hidden-states without any specific head on top.c                   @   s   e Zd ZeZdS )FlaxMistralModelN)r7   r8   r9   r   r   r#   r#   r#   r$   r   |  s   r   )Zreal_checkpointc                   @   sF   e Zd ZU eed< ejZejed< dd Zde	e	e	e	e	dd	d
Z
dS )FlaxMistralForCausalLMModuler   r   c                 C   s@   t | j| jd| _tj| jjd| jtjjj	| jj
dd| _d S )Nr-   Fr   rK   )r   r   r   r   rO   rT   r   rN   rP   rQ   rR   lm_headr*   r#   r#   r$   r,     s    z"FlaxMistralForCausalLMModule.setupNTFr   c	              
   C   sT   | j ||||||||d}	|	d }
| |
}|sB|f|	dd   S t||	j|	jdS )Nr   r   r   )Zlogitsr4   r   )r   r   r   r4   r   )r+   r   r   rF   r   r   r   r   r   r   r4   Z	lm_logitsr#   r#   r$   r5     s    
z%FlaxMistralForCausalLMModule.__call__)NNTFFFTr   r#   r#   r#   r$   r     s"   
       r   z\
    The Mistral Model transformer with a language modeling head (linear layer) on top.
    c                   @   s.   e Zd ZeZdeej dddZdd Z	dS )FlaxMistralForCausalLMN)r   c           	      C   s   |j \}}| ||}tj||fdd}|d k	rP|jddd }t||d}n&ttj|ddd d d f ||f}|||dS )Nr   r-   r/   rA   r   )r   r   )r   r   rF   )	r"   r   r   r    Zcumsumr   r   r   r[   )	r+   r   r   r   r   Z
seq_lengthr   Zextended_attention_maskrF   r#   r#   r$   prepare_inputs_for_generation  s    
&z4FlaxMistralForCausalLM.prepare_inputs_for_generationc                 C   s.   |j |d< |d d d dd f d |d< |S )Nr   rF   r/   r   )r   )r+   Zmodel_outputsZmodel_kwargsr#   r#   r$   update_inputs_for_generation  s    
 z3FlaxMistralForCausalLM.update_inputs_for_generation)N)
r7   r8   r9   r   r   r   rN   Arrayr   r   r#   r#   r#   r$   r     s   	r   )>r   typingr   r   Z
flax.linenZlinenrO   rN   Z	jax.numpyZnumpyr   rZ   Zflax.core.frozen_dictr   r   r   r   r   Zflax.linen.attentionr	   Zflax.traverse_utilr
   r   r   Zmodeling_flax_outputsr   r   r   r   Zmodeling_flax_utilsr   r   r   r   utilsr   r   Zconfiguration_mistralr   Z
get_loggerr7   loggerZ_CONFIG_FOR_DOCZ_REAL_CHECKPOINT_FOR_DOCZ_CHECKPOINT_FOR_DOCZMISTRAL_START_DOCSTRINGr   r   r   r;   rI   rC   r=   rX   rd   r   r   r   r   r   r   r   r#   r#   r#   r$   <module>   st   
#2
 + /;
,