o
    Zh                     @   sh  d Z ddlZddlZddlmZ ddlmZmZmZ ddl	m
Z ddlZddlm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 ddlmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0 e-1e2Z3dZ4dZ5dZ6dZ7dZ8dZ9dej:de;de;dej:fddZ<G dd dej=Z>G dd  d ej=Z?G d!d" d"ej=Z@G d#d$ d$ej=ZAG d%d& d&ej=ZBG d'd( d(ej=ZCG d)d* d*ej=ZDG d+d, d,ej=ZEG d-d. d.e&ZFe+d/e6G d0d1 d1eFZGe'eGe5e#e4 G d2d3 d3ej=ZHe+d4e6G d5d6 d6eFZId7ZJe)eIe7eJ  e(eIe"e4d8 g d9ZKdS ):zFlax Blenderbot model.    N)partial)CallableOptionalTuple)
FrozenDictfreezeunfreeze)combine_masksmake_causal_mask)dot_product_attention_weights)flatten_dictunflatten_dict)lax)PRNGKey   )FlaxBaseModelOutput-FlaxBaseModelOutputWithPastAndCrossAttentions%FlaxCausalLMOutputWithCrossAttentionsFlaxSeq2SeqLMOutputFlaxSeq2SeqModelOutput)ACT2FNFlaxPreTrainedModelappend_call_sample_docstring append_replace_return_docstringsoverwrite_call_docstring)add_start_docstrings%add_start_docstrings_to_model_forwardloggingreplace_return_docstrings   )BlenderbotConfigr    z facebook/blenderbot-400M-distilla*  
    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 ([`BlenderbotConfig`]): 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.
a  
    Args:
        input_ids (`jnp.ndarray` 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 (`jnp.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)
        decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            For translation and summarization training, `decoder_input_ids` should be provided. If no
            `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
            for denoising pre-training following the paper.
        decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.

            If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
            paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
        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.max_position_embeddings - 1]`.
        decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
            range `[0, config.max_position_embeddings - 1]`.
        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.
a:  
    Args:
        input_ids (`jnp.ndarray` 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 (`jnp.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)
        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.max_position_embeddings - 1]`.
        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.
a  
    Args:
        decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
            Indices of decoder input sequence tokens in the vocabulary.

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

            [What are decoder input IDs?](../glossary#decoder-input-ids)

            For translation and summarization training, `decoder_input_ids` should be provided. If no
            `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
            for denoising pre-training following the paper.
        encoder_outputs (`tuple(tuple(jnp.ndarray)`):
            Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
            `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
            hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
        encoder_attention_mask (`jnp.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)
        decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
            Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
            be used by default.

            If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
            paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
        decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
            range `[0, config.max_position_embeddings - 1]`.
        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.
	input_idspad_token_iddecoder_start_token_idreturnc                 C   sd   t | }|jddddf | ddddf }|jdddf |}t |dk||}|S )z1
    Shift input ids one token to the right.
    Nr   r   i)jnpZ
zeros_likeatsetwhere)r!   r"   r#   Zshifted_input_ids r*   f/var/www/auris/lib/python3.10/site-packages/transformers/models/blenderbot/modeling_flax_blenderbot.pyshift_tokens_right   s
   
,r,   c                   @   s   e Zd ZU eed< eed< eed< dZeed< dZe	ed< dZ
e	ed	< ejZejed
< dddZdd Zdd Zejdd Z				ddejdeej deej de	de	deej fddZdS )FlaxBlenderbotAttentionconfig	embed_dim	num_heads        dropoutFcausalTbiasdtyper$   Nc                 C   s   | j | j | _| j| j | j krtd| j  d| j dttj| j | j| jt	jj
| jjd}| | | | _| _| _| | _tj| jd| _| jr`ttjd| jjfdddd| _d S d S )	Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).Zuse_biasr5   kernel_initZrater   boolr5   )r/   r0   head_dim
ValueErrorr   nnDenser4   r5   jaxinitializersnormalr.   init_stdq_projk_projv_projout_projDropoutr2   dropout_layerr3   r
   r&   onesmax_position_embeddingscausal_mask)selfZdenser*   r*   r+   setup   s,   
zFlaxBlenderbotAttention.setupc                 C   s    | |jd d | j| jf S N   )reshapeshaper0   r;   rL   hidden_statesr*   r*   r+   _split_heads   s    z$FlaxBlenderbotAttention._split_headsc                 C   s   | |jd d | jf S rN   )rP   rQ   r/   rR   r*   r*   r+   _merge_heads  s   z$FlaxBlenderbotAttention._merge_headsc                 C   s   |  dd}| ddtj|j|j}| ddtj|j|j}| dddd }|rz|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 slightly 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&   arrayZint32r*   r*   r*   r+   <lambda>  s    z?FlaxBlenderbotAttention._concatenate_to_cache.<locals>.<lambda>)r   r   r   )has_variablevariabler&   zerosrQ   r5   valuelenr   dynamic_update_slicebroadcast_toarangetupler	   )rL   keyr_   queryattention_maskZis_initializedrW   rX   rY   Z
batch_dims
max_lengthr0   Zdepth_per_headZ	cur_indexindicesZnum_updated_cache_vectorsZpad_maskr*   r*   r+   _concatenate_to_cache  s(   


z-FlaxBlenderbotAttention._concatenate_to_cacherS   key_value_statesrg   
init_cachedeterministicc                 C   sD  |du}|j d }| |}|r| |}	| |}
n
| |}	| |}
| |}| |	}	| |
}
| jr|j d |	j d }}| ddrj| 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 }t||f|j dd  }|dur| jrttj|dd|j }t||}n| jr|}n|durtj|dd}| jr| dds|r| |	|
||\}	}
}|durt|dkt|j d	| jt|j t| jj| j}nd}d}|s| jd	kr| d
}t||	||| jd|| jdd	}td||
}| |}| |}||fS )z#Input shape: Batch x Time x ChannelNr   r   rV   rW   rY   )Zaxisr1   r2   T)r4   dropout_rngZdropout_rateZbroadcast_dropoutrm   r5   	precisionz...hqk,...khd->...qhd)rQ   rC   rD   rE   rT   r3   r\   	variablesr   Zdynamic_slicerK   r&   rb   Zexpand_dimsr	   rj   selectfullastyper5   Zfinfominr2   Zmake_rngr   ZeinsumrU   rF   )rL   rS   rk   rg   rl   rm   Zis_cross_attention
batch_sizeZquery_statesZ
key_statesZvalue_statesZquery_lengthZ
key_lengthZ
mask_shiftZmax_decoder_lengthrK   Zattention_biasrq   attn_weightsZattn_outputr*   r*   r+   __call__%  sr   







"



z FlaxBlenderbotAttention.__call__r$   N)NNFT)__name__
__module____qualname__r    __annotations__intr2   floatr3   r9   r4   r&   float32r5   rM   rT   rU   r=   compactrj   ndarrayr   r   rz   r*   r*   r*   r+   r-      s<   
 

"r-   c                   @   s^   e Zd ZU eed< ejZejed< dddZ		ddej	d	ej	d
e
de
deej	 f
ddZdS )FlaxBlenderbotEncoderLayerr.   r5   r$   Nc                 C   s   | j j| _t| j | j| j j| j j| jd| _tj	| jdd| _
tj| j jd| _t| j j | _tj| j jd| _tj| j j| jtjj| j jd| _tj| j| jtjj| j jd| _tj	| jdd| _d S )Nr.   r/   r0   r2   r5   h㈵>r5   epsilonr8   r5   r7   )r.   d_modelr/   r-   Zencoder_attention_headsattention_dropoutr5   	self_attnr=   	LayerNormself_attn_layer_normrG   r2   rH   r   activation_functionactivation_fnactivation_dropoutactivation_dropout_layerr>   Zencoder_ffn_dimr?   r@   rA   rB   fc1fc2final_layer_normrL   r*   r*   r+   rM     s*   
z FlaxBlenderbotEncoderLayer.setupTrS   rg   output_attentionsrm   c                 C   s   |}|  |}| j||d\}}| j||d}|| }|}| |}| | |}| j||d}| |}| j||d}|| }|f}|rK||f7 }|S )N)rS   rg   rm   )r   r   rH   r   r   r   r   r   )rL   rS   rg   r   rm   residualry   outputsr*   r*   r+   rz     s    



z#FlaxBlenderbotEncoderLayer.__call__r{   )TT)r|   r}   r~   r    r   r&   r   r5   rM   r   r9   r   rz   r*   r*   r*   r+   r     s"   
 
r   c                	   @   sR   e Zd ZU eed< ejZejed< dd Z				dde	de	d	e	d
e	fddZ
dS )$FlaxBlenderbotEncoderLayerCollectionr.   r5   c                    *    fddt  jjD  _ jj _d S )Nc                    "   g | ]}t  jt| jd qS )namer5   )r   r.   strr5   .0ir   r*   r+   
<listcomp>      z>FlaxBlenderbotEncoderLayerCollection.setup.<locals>.<listcomp>)ranger.   Zencoder_layerslayersZencoder_layerdrop	layerdropr   r*   r   r+   rM        

z*FlaxBlenderbotEncoderLayerCollection.setupTFrm   r   output_hidden_statesreturn_dictc                 C   s   |rdnd }|r
dnd }| j D ]-}	|r||f }tdd}
|s(|
| jk r(d}n|	||||}|d }|r<||d f }q|rD||f7 }|||f}|sTtdd |D S t|||dS )Nr*   r   r   )NNc                 s       | ]	}|d ur|V  qd S Nr*   r   vr*   r*   r+   	<genexpr>      z@FlaxBlenderbotEncoderLayerCollection.__call__.<locals>.<genexpr>last_hidden_staterS   
attentions)r   randomuniformr   rd   r   )rL   rS   rg   rm   r   r   r   Zall_attentionsall_hidden_statesZencoder_layerdropout_probabilitylayer_outputsr   r*   r*   r+   rz     s4   	



z-FlaxBlenderbotEncoderLayerCollection.__call__N)TFFT)r|   r}   r~   r    r   r&   r   r5   rM   r9   rz   r*   r*   r*   r+   r     s"   
 r   c                   @   s|   e Zd ZU eed< ejZejed< dddZ					dd	ej	d
ej	de
ej	 de
ej	 dedededeej	 fddZdS )FlaxBlenderbotDecoderLayerr.   r5   r$   Nc                 C   s  | j j| _t| j | j| j j| j jd| jd| _tj	| j j
d| _t| j j | _tj	| j jd| _tj| jdd| _t| j | j| j j| j j| jd| _tj| jdd| _tj| j j| jtjj| j jd| _tj| j| jtjj| j jd| _tj| jdd| _d S )NT)r.   r/   r0   r2   r3   r5   r8   r   r   r   r   )r.   r   r/   r-   Zdecoder_attention_headsr   r5   r   r=   rG   r2   rH   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normr>   Zdecoder_ffn_dimr?   r@   rA   rB   r   r   r   r   r*   r*   r+   rM     s<   
z FlaxBlenderbotDecoderLayer.setupFTrS   rg   encoder_hidden_statesencoder_attention_maskrl   r   rm   c                 C   s   |}|  |}| j|||d\}}	| j||d}|| }d }
|d ur>|}| |}| j|||d\}}
| j||d}|| }|}| |}| | |}| j||d}| 	|}| j||d}|| }|f}|ro||	|
f7 }|S )N)rS   rg   rl   r   )rS   rk   rg   )
r   r   rH   r   r   r   r   r   r   r   )rL   rS   rg   r   r   rl   r   rm   r   Zself_attn_weightsZcross_attn_weightsr   r*   r*   r+   rz     s:   






z#FlaxBlenderbotDecoderLayer.__call__r{   )NNFTT)r|   r}   r~   r    r   r&   r   r5   rM   r   r   r9   r   rz   r*   r*   r*   r+   r     s4   
 
%	r   c                   @   sp   e Zd ZU eed< ejZejed< dd Z							dde	ej
 d	e	ej
 d
ededededefddZdS )$FlaxBlenderbotDecoderLayerCollectionr.   r5   c                    r   )Nc                    r   r   )r   r.   r   r5   r   r   r*   r+   r   R  r   z>FlaxBlenderbotDecoderLayerCollection.setup.<locals>.<listcomp>)r   r.   Zdecoder_layersr   Zdecoder_layerdropr   r   r*   r   r+   rM   Q  r   z*FlaxBlenderbotDecoderLayerCollection.setupNTFr   r   rm   rl   r   r   r   c
              
   C   s   |rdnd }
|r
dnd }|r|d urdnd }| j D ]<}|r"|
|f7 }
tdd}|s2|| jk r2d}n||||||||d}|d }|rU||d f7 }|d urU||d f7 }q|r]|
|f7 }
||
||g}|	sntdd |D S t||
||d	S )
Nr*   r   r   NNN)rg   r   r   rl   r   rm   rO   c                 s   r   r   r*   r   r*   r*   r+   r     r   z@FlaxBlenderbotDecoderLayerCollection.__call__.<locals>.<genexpr>r   rS   r   cross_attentions)r   r   r   r   rd   r   )rL   rS   rg   r   r   rm   rl   r   r   r   r   Zall_self_attnsZall_cross_attentionsZdecoder_layerr   r   r   r*   r*   r+   rz   X  sF   



z-FlaxBlenderbotDecoderLayerCollection.__call__)NNTFFFT)r|   r}   r~   r    r   r&   r   r5   rM   r   r   r9   rz   r*   r*   r*   r+   r   M  s4   
 	
r   c                	   @   s\   e Zd ZU eed< ejed< ejZ	ej	ed< dd Z
				dded	ed
edefddZdS )FlaxBlenderbotEncoderr.   embed_tokensr5   c                 C   s   t j| jjd| _| jj}| jj| _| jj| _	| jj
r t|nd| _t j| jj|tj j| jjd| _t| j| j| _t j| jdd| _d S Nr8   g      ?)embedding_initr   r   )r=   rG   r.   r2   rH   r   r"   padding_idxrJ   Zmax_source_positionsscale_embeddingmathsqrtembed_scaleEmbedr?   r@   rA   rB   embed_positionsr   r5   r   r   
layer_normrL   r/   r*   r*   r+   rM     s   

zFlaxBlenderbotEncoder.setupFTr   r   r   rm   c                 C   s   |j }|d|d }| || j }	| |}
|	|
 }| j||d}| j||||||d}|d }| |}d }|rH|d }|d d |f }|se||f|rU|dd  n|dd   }tdd |D S t	|||j
d	S )
Nr%   r   )rm   r   r   r   r   r   rO   c                 s   r   r   r*   r   r*   r*   r+   r     r   z1FlaxBlenderbotEncoder.__call__.<locals>.<genexpr>r   )rQ   rP   r   r   r   rH   r   r   rd   r   r   )rL   r!   rg   position_idsr   r   r   rm   input_shapeinputs_embedsZ	embed_posrS   r   last_hidden_statesr*   r*   r+   rz     s8   


$zFlaxBlenderbotEncoder.__call__NFFTT)r|   r}   r~   r    r   r=   r   r&   r   r5   rM   r9   rz   r*   r*   r*   r+   r     s$   
 
r   c                   @   sz   e Zd ZU eed< ejed< ejZ	ej	ed< dd Z
							dd	eej d
eej dededededefddZdS )FlaxBlenderbotDecoderr.   r   r5   c                 C   s   t j| jjd| _| jj}| jj| _| jj| _	| jj
r"t| jjnd| _t j| jj|tj j| jjd| _t| j| j| _t j| jdd| _d S r   )r=   rG   r.   r2   rH   r   r"   r   rJ   Zmax_target_positionsr   r   r   r   r   r?   r@   rA   rB   r   r   r5   r   r   r   r   r*   r*   r+   rM     s   

zFlaxBlenderbotDecoder.setupNFTr   r   rl   r   r   r   rm   c                 C   s   |j }|d|d }| || j }| |}|| }| j||
d}| j|||||
||||	d	}|d }| |}d }|rK|d }|d d |f }|	sh||f|rX|dd  n|dd   }tdd |D S t	|||j
|jd	S )
Nr%   r   )rm   rl   r   r   r   r   r   rO   c                 s   r   r   r*   r   r*   r*   r+   r     r   z1FlaxBlenderbotDecoder.__call__.<locals>.<genexpr>r   )rQ   rP   r   r   r   rH   r   r   rd   r   r   r   )rL   r!   rg   r   r   r   rl   r   r   r   rm   r   r   Z	positionsrS   r   r   r*   r*   r+   rz     s@   

$zFlaxBlenderbotDecoder.__call__)NNFFFTT)r|   r}   r~   r    r   r=   r   r&   r   r5   rM   r   r   r9   rz   r*   r*   r*   r+   r     s6   
 
	
r   c                	   @   sb   e Zd ZU eed< ejZejed< dd Zdd Z	dd Z
					
	
ddedededefddZdS )FlaxBlenderbotModuler.   r5   c                 C   s\   t j| jj| jjtj j| jj| j	d| _
t| j| j	| j
d| _t| j| j	| j
d| _d S )N)r   r5   )r5   r   )r=   r   r.   Z
vocab_sizer   r?   r@   rA   rB   r5   sharedr   encoderr   decoderr   r*   r*   r+   rM   ,  s   zFlaxBlenderbotModule.setupc                 C      | j S r   )r   r   r*   r*   r+   _get_encoder_module7     z(FlaxBlenderbotModule._get_encoder_modulec                 C   r   r   )r   r   r*   r*   r+   _get_decoder_module:  r   z(FlaxBlenderbotModule._get_decoder_moduleFTr   r   r   rm   c                 C   sh   | j ||||||	|
d}| j||||d ||||	|
d	}|	s"|| S t|j|j|j|j|j|j|jdS )N)r!   rg   r   r   r   r   rm   r   )	r!   rg   r   r   r   r   r   r   rm   )r   decoder_hidden_statesdecoder_attentionsr   encoder_last_hidden_stater   encoder_attentions)r   r   r   r   rS   r   r   )rL   r!   rg   decoder_input_idsdecoder_attention_maskr   decoder_position_idsr   r   r   rm   encoder_outputsdecoder_outputsr*   r*   r+   rz   =  s>   
zFlaxBlenderbotModule.__call__Nr   )r|   r}   r~   r    r   r&   r   r5   rM   r   r   r9   rz   r*   r*   r*   r+   r   (  s&   
 	
r   c                       s
  e Zd ZU eZdZeed< dZe	j
ed< ddejdfded	ee d
edejdef
 fddZd+dejjd	ededefddZdd Zeeeeed								d,dejdeej deej dee dee dee dedee defd d!Zee ee!ed										d-d"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dee defd&d'Z"e#e$											d.dejdeej d(eej d#eej deej d$eej dee dee dee dedee defd)d*Z%  Z&S )/FlaxBlenderbotPreTrainedModelmodelbase_model_prefixNmodule_class)r   r   r   Tr.   r   seedr5   _do_initc                    s2   | j d||d|}t j||||||d d S )Nr.   r5   )r   r   r5   r   r*   )r   super__init__)rL   r.   r   r   r5   r   kwargsmodule	__class__r*   r+   r   s  s   	z&FlaxBlenderbotPreTrainedModel.__init__rngparamsr$   c              	   C   s  t j|dd}|jd | jj}t |}|}t |}|j\}}	t t 	|	d d d f ||	f}
t t 	|	d d d f ||	f}t
j|\}}||d}| j||||||
|d }|d urtt|}tt|}| jD ]}|| ||< qrt | _tt|S |S )Ni4r:   ).r%   )r   r2   r   )r&   r^   r'   r(   r.   Zeos_token_id	ones_likerQ   rb   rc   r?   r   splitr   initr   r   Z_missing_keysr   r   )rL   r   r   r   r!   rg   r   r   rx   sequence_lengthr   r   Z
params_rngrq   rngsZrandom_paramsZmissing_keyr*   r*   r+   init_weights  s:   


""


z*FlaxBlenderbotPreTrainedModel.init_weightsc           	   	   C   sv   t j||fdd}t |}t t t |jd |j}dd }| jjt	j
d||||d d|d}t|d	 S )
a+  
        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.
            encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
                `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
                `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
                is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
                cross-attention of the decoder.
        r   r:   r%   c                 [      |   }||||fi |S r   r   r   r   r   r   r   decoder_moduler*   r*   r+   _decoder_forward     zBFlaxBlenderbotPreTrainedModel.init_cache.<locals>._decoder_forwardr   T)r   r   r   r   rl   methodrV   )r&   rI   r   rb   rc   Z
atleast_2drQ   r   r   r?   r   r   r   )	rL   rx   rh   r   r   r   r   r  Zinit_variablesr*   r*   r+   rl     s    
	
	z(FlaxBlenderbotPreTrainedModel.init_cacheoutput_typeconfig_classFr!   rg   r   r   r   r   trainrq   c
                 C   s   |dur|n| j j}|dur|n| j j}|dur|n| j j}|du r't|}|du rA|j\}
}tt|dddf |
|f}i }|	durK|	|d< dd }| j	j
d|pW| jitj|ddtj|ddtj|dd|||| ||d
S )	a/  
        Returns:

        Example:

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

        >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")

        >>> text = "My friends are cool but they eat too many carbs."
        >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
        >>> encoder_outputs = model.encode(**inputs)
        ```Nr2   c                 [   r   r   )r   )r   r!   rg   r   r   Zencode_moduler*   r*   r+   _encoder_forward  s   z>FlaxBlenderbotPreTrainedModel.encode.<locals>._encoder_forwardr   r   r:   )	r!   rg   r   r   r   r   rm   r   r  )r.   r   r   r   r&   r   rQ   rb   rc   r   applyr   rZ   )rL   r!   rg   r   r   r   r   r  r   rq   rx   r   r   r	  r*   r*   r+   encode  s2   

"z$FlaxBlenderbotPreTrainedModel.encoder   r   r   past_key_valuesc                 C   s  |dur|n| j j}|dur|n| j j}|	dur|	n| j j}	|d }|du r6|jdd \}}t||f}|j\}}|du rFt||f}|du rc|durRtdtt	|dddf ||f}i }|durm||d< d|pr| j
i}|r~||d< dg}nd}d	d
 }| jj|tj|ddtj|ddtj|dd|tj|dd|||	|
 |||d}|dur|	r|\}}t|d |d< |S |dur|	s|\}}|dd t|d f |dd  }|S )a  
        Returns:

        Example:

        ```python
        >>> import jax.numpy as jnp
        >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration

        >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")

        >>> text = "My friends are cool but they eat too many carbs."
        >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
        >>> encoder_outputs = model.encode(**inputs)

        >>> decoder_start_token_id = model.config.decoder_start_token_id
        >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

        >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
        >>> last_decoder_hidden_states = outputs.last_hidden_state
        ```Nr   rO   KMake sure to provide `decoder_position_ids` when passing `past_key_values`.r2   r   rV   Fc                 [   r   r   r   r   r*   r*   r+   r  [  r  z>FlaxBlenderbotPreTrainedModel.decode.<locals>._decoder_forwardr   r:   r   r   r   r   r   r   r   r   rm   r   mutabler  r  r   )r.   r   r   r   rQ   r&   rI   r<   rb   rc   r   r   r
  rZ   r   )rL   r   r   r   r   r   r  r   r   r   r  r   rq   r   rx   r   r   inputsr  r  r   pastr*   r*   r+   decode  sb   )
	&z$FlaxBlenderbotPreTrainedModel.decoder   c                 C   sf  |d ur|n| j j}|d ur|n| j j}|	d ur|	n| j j}	|d u r't|}|d u rA|j\}}tt|d d d f ||f}|d u rPt	|| j j
| j jd}|d u rYt|}|d u rs|j\}}tt|d d d f ||f}|d ur{d|ini }| jjd|p| jitj|ddtj|ddtj|ddtj|ddtj|ddtj|dd|||	|
 |dS )N)r#   r2   r   r   r:   )r!   rg   r   r   r   r   r   r   r   rm   r   )r.   r   r   r   r&   r   rQ   rb   rc   r,   r"   r#   r   r
  r   rZ   )rL   r!   rg   r   r   r   r   r   r   r   r  r   rq   rx   r   r   r*   r*   r+   rz     sF   

"

z&FlaxBlenderbotPreTrainedModel.__call__r   )NNNNNFNN
NNNNNNNFNN)NNNNNNNNFNN)'r|   r}   r~   r    r  r   r   r   r   r=   Moduler&   r   r   r   r5   r9   r   r?   r   r   r   r   rl   r   "BLENDERBOT_ENCODE_INPUTS_DOCSTRINGr   r   r   r   dictr  "BLENDERBOT_DECODE_INPUTS_DOCSTRINGr   r  r   BLENDERBOT_INPUTS_DOCSTRINGrz   __classcell__r*   r*   r   r+   r   n  s   
  $)
	
=	
p	
r   z_The bare MBart Model transformer outputting raw hidden-states without any specific head on top.c                   @   s*   e Zd ZU eed< ejZejed< eZ	dS )FlaxBlenderbotModelr.   r5   N)
r|   r}   r~   r    r   r&   r   r5   r   r   r*   r*   r*   r+   r    s   
 r  c                	   @   s~   e Zd ZU eed< ejZejed< ej	j
jZedejf ed< dd Zdd Zd	d
 Z				ddedededefddZdS ),FlaxBlenderbotForConditionalGenerationModuler.   r5   .	bias_initc                 C   s\   t | j| jd| _tj| jjjd| jtjj	
| jjd| _| d| jd| jjjf| _d S )Nr   Fr6   final_logits_biasr   )r   r.   r5   r   r=   r>   r   Znum_embeddingsr?   r@   rA   rB   lm_headparamr  r  r   r*   r*   r+   rM     s    z2FlaxBlenderbotForConditionalGenerationModule.setupc                 C      | j jS r   )r   r   r   r*   r*   r+   r        z@FlaxBlenderbotForConditionalGenerationModule._get_encoder_modulec                 C   r   r   )r   r   r   r*   r*   r+   r     r!  z@FlaxBlenderbotForConditionalGenerationModule._get_decoder_moduleFTr   r   r   rm   c                 C   s   | j |||||||||	|
d
}|d }| jjr.| j jd d d }| jdd|jii|}n| |}|tj	| j
| j7 }|	sM|f|dd   }|S t||j|j|j|j|j|jdS )	N)
r!   rg   r   r   r   r   r   r   r   rm   r   r   r   	embeddingkernelr   )logitsr   r   r   r   r   r   )r   r.   tie_word_embeddingsrs   r  r
  Tr?   r   Zstop_gradientr  rv   r5   r   r   r   r   r   r   r   )rL   r!   rg   r   r   r   r   r   r   r   rm   r   rS   shared_embedding	lm_logitsoutputr*   r*   r+   rz     s<   
z5FlaxBlenderbotForConditionalGenerationModule.__call__Nr   )r|   r}   r~   r    r   r&   r   r5   r?   r=   r@   r^   r  r   r   rM   r   r   r9   rz   r*   r*   r*   r+   r    s(   
 
	
r  zRThe Blenderbot Model with a language modeling head. Can be used for summarization.c                   @   s   e Zd ZU eZejZejed< e	e
eeed										dd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dee defddZ			ddeej deej fddZdd ZdS )&FlaxBlenderbotForConditionalGenerationr5   r  NFr   r   r   r  r   r   r   r  r   rq   c                    s  |dur|n j j}|dur|n j j}|	dur|	n j j}	|d }|du r6|jdd \}}t||f}|j\}}|du rFt||f}|du rc|durRtdtt	|dddf ||f}i }|durm||d< d|pr j
i}|r~||d< dg}nd} fd	d
} jj|tj|ddtj|ddtj|dd|tj|dd|||	|
 |||d}|du r|\}}n|\\}}}|	rt||j|j|jd}n	|f|dd  }|dur|	rt|d |d< |S |dur|	s|dd t|d f |dd  }|S )aw  
        Returns:

        Example:

        ```python
        >>> import jax.numpy as jnp
        >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration

        >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")

        >>> text = "My friends are cool but they eat too many carbs."
        >>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
        >>> encoder_outputs = model.encode(**inputs)

        >>> decoder_start_token_id = model.config.decoder_start_token_id
        >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

        >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
        >>> logits = outputs.logits
        ```Nr   rO   r  r2   r   rV   Fc           
         sv   |   }||||fi |}|d } jjr-| jjd d d }| jdd|jii|}	n| |}	|	| j7 }	|	|fS )Nr   r   r   r"  r#  )	r   r.   r%  r   rs   r  r
  r&  r  )
r   r   r   r   r   r  r   rS   r'  r(  r   r*   r+   r  g  s   

zGFlaxBlenderbotForConditionalGeneration.decode.<locals>._decoder_forwardr   r:   r  )r$  rS   r   r   r   r  )r.   r   r   r   rQ   r&   rI   r<   rb   rc   r   r   r
  rZ   r   rS   r   r   r   )rL   r   r   r   r   r   r  r   r   r   r  r   rq   r   rx   r   r   r  r  r  r   r(  r   r  r*   r   r+   r    st   '

&z-FlaxBlenderbotForConditionalGeneration.decoderg   c                 K   s   |j \}}| |||}	tj||fdd}
|d ur)|jddd }t|
|d}
nttj|ddd d d f ||f}|	|||
|dS )Nr   r:   r%   rp   r   )r   r   )r  r   r   r   r   )	rQ   rl   r&   rI   Zcumsumr   ra   rb   rc   )rL   r   rh   rg   r   r   r   rx   Z
seq_lengthr  Zextended_attention_maskr   r*   r*   r+   prepare_inputs_for_generation  s   

&zDFlaxBlenderbotForConditionalGeneration.prepare_inputs_for_generationc                 C   s.   |j |d< |d d d dd f d |d< |S )Nr  r   r%   r   )r  )rL   Zmodel_outputsZmodel_kwargsr*   r*   r+   update_inputs_for_generation  s   
 zCFlaxBlenderbotForConditionalGeneration.update_inputs_for_generationr  r   )r|   r}   r~   r  r   r&   r   r5   r   r   r  r   r   r    r   r   r  r9   r   r  r?   ZArrayr+  r,  r*   r*   r*   r+   r*    s\   
 
	
 
r*  a  
    Returns:

    Conversation example::

    ```py
    >>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration

    >>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
    >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")

    >>> UTTERANCE = "My friends are cool but they eat too many carbs."
    >>> inputs = tokenizer([UTTERANCE], max_length=1024, return_tensors="np")

    >>> # Generate Reply
    >>> reply_ids = model.generate(inputs["input_ids"], num_beams=4, max_length=5, early_stopping=True).sequences
    >>> print([tokenizer.decode(g, skip_special_tokens=True, clean_up_tokenization_spaces=False) for g in reply_ids])
    ```
r  )r*  r  r   )L__doc__r   r   	functoolsr   typingr   r   r   Z
flax.linenZlinenr=   r?   Z	jax.numpynumpyr&   Zflax.core.frozen_dictr   r   r   r	   r
   Zflax.linen.attentionr   Zflax.traverse_utilr   r   r   Z
jax.randomr   Zmodeling_flax_outputsr   r   r   r   r   Zmodeling_flax_utilsr   r   r   r   r   utilsr   r   r   r   Zconfiguration_blenderbotr    Z
get_loggerr|   loggerZ_CONFIG_FOR_DOCZ_CHECKPOINT_FOR_DOCZBLENDERBOT_START_DOCSTRINGr  r  r  r   r   r,   r  r-   r   r   r   r   r   r   r   r   r  r  r*  Z0FLAX_BLENDERBOT_CONDITIONAL_GENERATION_DOCSTRING__all__r*   r*   r*   r+   <module>   sv   
30 )97YFEPF  PH 3