
    sg                        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-jb                  e2      Z3dZ4dZ5dZ6dZ7dZ8dZ9dejt                  de;de;dejt                  fdZ< G d dejz                        Z> G d dejz                        Z? G d  d!ejz                        Z@ G d" d#ejz                        ZA G d$ d%ejz                        ZB G d& d'ejz                        ZC G d( d)ejz                        ZD G d* d+ejz                        ZE G d, d-e&      ZF e+d.e6       G d/ d0eF             ZG e'eGe5e#e4        G d1 d2ejz                        ZH e+d3e6       G d4 d5eF             ZId6ZJ e)eIe7eJz           e(eIe"e47       y)8z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                    t        j                  |       }|j                  ddddf   j                  | ddddf         }|j                  dddf   j                  |      }t        j                  |dk(  ||      }|S )z1
    Shift input ids one token to the right.
    Nr    r   i)jnp
zeros_likeatsetwhere)r"   r#   r$   shifted_input_idss       j/var/www/html/venv/lib/python3.12/site-packages/transformers/models/blenderbot/modeling_flax_blenderbot.pyshift_tokens_rightr/      s     y1),,QU377	!SbS&8IJ),,QT2667MN		"3t";\K\]    c                   P   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Zd Zd Zej$                  d        Z	 	 	 	 ddej(                  deej(                     deej(                     de	de	deej(                     fdZy)FlaxBlenderbotAttentionconfig	embed_dim	num_heads        dropoutFcausalTbiasdtyper%   Nc           	         | j                   | j                  z  | _        | j                  | j                  z  | j                   k7  r&t        d| j                    d| j                   d      t	        t
        j                  | j                   | j                  | j                  t        j
                  j                  j                  | j                  j                              } |        |        |       c| _        | _        | _         |       | _        t        j$                  | j&                        | _        | j*                  r>t-        t/        j0                  d| j                  j2                  fd      d      | _        y y )	Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).use_biasr:   kernel_initrater    boolr:   )r4   r5   head_dim
ValueErrorr   nnDenser9   r:   jaxinitializersnormalr3   init_stdq_projk_projv_projout_projDropoutr7   dropout_layerr8   r   r(   onesmax_position_embeddingscausal_mask)selfdenses     r.   setupzFlaxBlenderbotAttention.setup   s   $..8==4>>)T^^;MdnnM]$T^^$4B8 
 HHNNYY**++224;;3G3GH
 16%'-T[$+ZZT\\:;;/!T[[@@APX^ D r0   c                 p    |j                  |j                  d d | j                  | j                  fz         S N   )reshapeshaper5   rC   rT   hidden_statess     r.   _split_headsz$FlaxBlenderbotAttention._split_heads   s5    $$]%8%8!%<PTP]P]?^%^__r0   c                 Z    |j                  |j                  d d | j                  fz         S rX   )rZ   r[   r4   r\   s     r.   _merge_headsz$FlaxBlenderbotAttention._merge_heads  s,    $$]%8%8!%<?P%PQQr0   c                 (   | j                  dd      }| j                  ddt        j                  |j                  |j
                        }| j                  ddt        j                  |j                  |j
                        }| j                  ddd       }|r|j                  j                  ^ }	}
}}|j                  }dt        |	      z  |ddfz   }t        j                  |j                  ||      }t        j                  |j                  ||      }||_        ||_        |j                  d   }|j                  |z   |_        t        j                  t        j                  |
      ||z   k  t        |	      d||
fz         }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                  L    t        j                  dt         j                        S )Nr   rB   )r(   arrayint32 r0   r.   <lambda>z?FlaxBlenderbotAttention._concatenate_to_cache.<locals>.<lambda>  s    CIIaWZW`W`Da r0   )r   r   r    )has_variablevariabler(   zerosr[   r:   valuelenr   dynamic_update_slicebroadcast_toarangetupler
   )rT   keyrn   queryattention_maskis_initializedrc   rd   re   
batch_dims
max_lengthr5   depth_per_head	cur_indexindicesnum_updated_cache_vectorspad_masks                    r.   _concatenate_to_cachez-FlaxBlenderbotAttention._concatenate_to_cache  sr    **7LA]]7L#))SYYPSPYPYZ
}}WnciiV[VaVabmmG]<abAKAQAQAWAW>ZY#))IS_,	1a/@@G**:+;+;S'JC,,\-?-?PE"J!&L(-A% + 1 14M MK''

:&5N)NNj!Q(A:$NNH +8^DNE>))r0   r]   key_value_statesrv   
init_cachedeterministicc                    |du}|j                   d   }| j                  |      }|r#| j                  |      }	| j                  |      }
n"| j                  |      }	| j                  |      }
| j	                  |      }| j	                  |	      }	| j	                  |
      }
| j
                  r|j                   d   |	j                   d   }}| j                  dd      r[| j                  d   d   }| j                  d   d   j                   d   }t        j                  | j                  dd|dfdd||f      }n| j                  ddddd|d|f   }t        j                  ||f|j                   dd z         }|N| j
                  rBt        j                  t        j                  |d      j                         }t        ||      }n(| j
                  r}n|t        j                  |d      }| j
                  r,| j                  dd      s|r| j                  |	|
||      \  }	}
}|t        j                   |dkD  t        j"                  |j                   d	      j%                  | j&                        t        j"                  |j                   t        j(                  | j&                        j*                        j%                  | j&                              }nd}d}|s | j,                  d	kD  r| j/                  d
      }t1        ||	||| j,                  d|| j&                  d	      }t        j2                  d||
      }| j5                  |      }| j7                  |      }||fS )z#Input shape: Batch x Time x ChannelNr   r    rb   rc   re   )axisr6   r7   T)r9   dropout_rngdropout_ratebroadcast_dropoutr   r:   	precisionz...hqk,...khd->...qhd)r[   rK   rL   rM   r^   r8   rk   	variablesr   dynamic_slicerS   r(   rq   expand_dimsr
   r   selectfullastyper:   finfominr7   make_rngr   einsumr`   rN   )rT   r]   r   rv   r   r   is_cross_attention
batch_sizequery_states
key_statesvalue_statesquery_length
key_length
mask_shiftmax_decoder_lengthrS   attention_biasr   attn_weightsattn_outputs                       r.   __call__z FlaxBlenderbotAttention.__call__%  s,    .T9"((+
 {{=1%56J;;'78L ]3J;;}5L((6&&z2
((6 ;;'3'9'9!'<j>N>Nq>Q*L  ,7!^^G4]C
%)^^G%<\%J%P%PQR%S"!//$$q!Z&;aLRd=e #..q!]l]KZK/OP**;HYHYZ[Z\H]8]^K %$++ --coonS[.\^i^o^opN*>;GN[[(N' __^(KN ;;D--g|D
7;7Q7QL,84Jn
 % ZZ"--s3::4::F--syy/D/H/HIPPQUQ[Q[\N "N!3--	2K4#"'**

 jj!8,U''4mmK0L((r0   r%   N)NNFT)__name__
__module____qualname__r!   __annotations__intr7   floatr8   rA   r9   r(   float32r:   rV   r^   r`   rE   compactr   ndarrayr   r   r   ri   r0   r.   r2   r2      s    NNGUFDD${{E399"4`R ZZ* *D 3704 "[){{[) #3;;/[) !-	[)
 [) [) 
s{{	[)r0   r2   c                       e Zd ZU eed<   ej                  Zej                  ed<   ddZ	 	 ddej                  dej                  de
d	e
deej                     f
d
Zy)FlaxBlenderbotEncoderLayerr3   r:   r%   Nc                 L   | j                   j                  | _        t        | j                   | j                  | j                   j                  | j                   j
                  | j                        | _        t        j                  | j                  d      | _
        t        j                  | j                   j                        | _        t        | j                   j                     | _        t        j                  | j                   j"                        | _        t        j&                  | j                   j(                  | j                  t*        j                  j,                  j/                  | j                   j0                              | _        t        j&                  | j                  | j                  t*        j                  j,                  j/                  | j                   j0                              | _        t        j                  | j                  d      | _        y )Nr3   r4   r5   r7   r:   h㈵>r:   epsilonr?   r:   r>   )r3   d_modelr4   r2   encoder_attention_headsattention_dropoutr:   	self_attnrE   	LayerNormself_attn_layer_normrO   r7   rP   r   activation_functionactivation_fnactivation_dropoutactivation_dropout_layerrF   encoder_ffn_dimrG   rH   rI   rJ   fc1fc2final_layer_normrT   s    r.   rV   z FlaxBlenderbotEncoderLayer.setup  sV   ,,0;;nnkk99KK11**
 %'LLtzz5$Q!ZZT[[-@-@A#DKK$C$CD(*

8V8V(W%88KK''**++224;;3G3GH

 88NN$**#&&:M:M:T:TUYU`U`UiUi:j
 !#4::u Mr0   r]   rv   output_attentionsr   c                 |   |}| j                  |      }| j                  ||      \  }}| j                  ||      }||z   }|}| j                  |      }| j	                  | j                  |            }| j                  ||      }| j                  |      }| j                  ||      }||z   }|f}|r||fz  }|S )N)r]   rv   r   )r   r   rP   r   r   r   r   r   )rT   r]   rv   r   r   residualr   outputss           r.   r   z#FlaxBlenderbotEncoderLayer.__call__  s     !11-@&*nn=aon&p#|**=*V =0 --m<**488M+BC55mS`5a/**=*V =0 "&Gr0   r   )TT)r   r   r   r!   r   r(   r   r:   rV   r   rA   r   r   ri   r0   r.   r   r     sn    {{E399"N6 #'"{{   	
  
s{{	r0   r   c            	       v    e Zd ZU eed<   ej                  Zej                  ed<   d Z	 	 	 	 d
de	de	de	de	fdZ
y	)$FlaxBlenderbotEncoderLayerCollectionr3   r:   c           	          t        | j                  j                        D cg c]-  }t        | j                  t	        |      | j
                        / c}| _        | j                  j                  | _        y c c}w N)namer:   )	ranger3   encoder_layersr   strr:   layersencoder_layerdrop	layerdroprT   is     r.   rV   z*FlaxBlenderbotEncoderLayerCollection.setup  Z     4;;556
 't{{QtzzR
 66	
   2A8r   r   output_hidden_statesreturn_dictc                 6   |rdnd }|rdnd }| j                   D ]P  }	|r||fz   }t        j                  dd      }
|s|
| j                  k  rd}n |	||||      }|d   }|sH||d   fz   }R |r||fz  }|||f}|st	        d |D              S t        |||      S )Nri   r   r    )NNc              3   &   K   | ]	  }||  y wNri   .0vs     r.   	<genexpr>z@FlaxBlenderbotEncoderLayerCollection.__call__.<locals>.<genexpr>       =qq}=   last_hidden_stater]   
attentions)r   randomuniformr   rs   r   )rT   r]   rv   r   r   r   r   all_attentionsall_hidden_statesencoder_layerdropout_probabilitylayer_outputsr   s                r.   r   z-FlaxBlenderbotEncoderLayerCollection.__call__  s      1d"6BD![[ 	FM#$58H$H!"(..A"6 &9DNN&J , -!"%!	! *!,M !/=3C2E!E!	F$  -!11 "3^D=G==="+;LYg
 	
r0   N)TFFT)r   r   r   r!   r   r(   r   r:   rV   rA   r   ri   r0   r.   r   r     sZ    {{E399"7 #"'%* (
 	(

  (
 #(
 (
r0   r   c                       e Zd ZU eed<   ej                  Zej                  e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Zy)FlaxBlenderbotDecoderLayerr3   r:   r%   Nc                 P   | j                   j                  | _        t        | j                   | j                  | j                   j                  | j                   j
                  d| j                        | _        t        j                  | j                   j                        | _        t        | j                   j                     | _        t        j                  | j                   j                        | _        t        j"                  | j                  d      | _        t        | j                   | j                  | j                   j                  | j                   j
                  | j                        | _        t        j"                  | j                  d      | _        t        j*                  | j                   j,                  | j                  t.        j                  j0                  j3                  | j                   j4                              | _        t        j*                  | j                  | j                  t.        j                  j0                  j3                  | j                   j4                              | _        t        j"                  | j                  d      | _        y )NT)r3   r4   r5   r7   r8   r:   r?   r   r   r   r   )r3   r   r4   r2   decoder_attention_headsr   r:   r   rE   rO   r7   rP   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrF   decoder_ffn_dimrG   rH   rI   rJ   r   r   r   r   s    r.   rV   z FlaxBlenderbotDecoderLayer.setup  s   ,,0;;nnkk99KK11**
  ZZT[[-@-@A#DKK$C$CD(*

8V8V(W%$&LLtzz5$Q!3;;nnkk99KK11**
 (*||$**e'T$88KK''**++224;;3G3GH

 88NN$**#&&:M:M:T:TUYU`U`UiUi:j
 !#4::u Mr0   r]   rv   encoder_hidden_statesencoder_attention_maskr   r   r   c                    |}| j                  |      }| j                  |||      \  }}	| j                  ||      }||z   }d }
|B|}| j                  |      }| j	                  |||      \  }}
| j                  ||      }||z   }|}| j                  |      }| j                  | j                  |            }| j                  ||      }| j                  |      }| j                  ||      }||z   }|f}|r||	|
fz  }|S )N)r]   rv   r   r   )r]   r   rv   )
r   r   rP   r   r   r   r   r   r   r   )rT   r]   rv   r   r   r   r   r   r   self_attn_weightscross_attn_weightsr   s               r.   r   z#FlaxBlenderbotDecoderLayer.__call__  sZ    !11-@ ,0>>'S] ,: ,
(( **=*V =0 " ,$H 88GM040A0A+!65 1B 1-M-
 !..}M.ZM$}4M !--m<**488M+BC55mS`5a/**=*V =0 ")+=>>Gr0   r   )NNFTT)r   r   r   r!   r   r(   r   r:   rV   r   r   rA   r   r   ri   r0   r.   r   r     s    {{E399"NJ 8<8< "&"0{{0 0  (4	0
 !) 50 0  0 0 
s{{	0r0   r   c                       e Zd ZU eed<   ej                  Zej                  ed<   d Z	 	 	 	 	 	 	 dde	ej                     de	ej                     deded	ed
edefdZy)$FlaxBlenderbotDecoderLayerCollectionr3   r:   c           	          t        | j                  j                        D cg c]-  }t        | j                  t	        |      | j
                        / c}| _        | j                  j                  | _        y c c}w r   )	r   r3   decoder_layersr   r   r:   r   decoder_layerdropr   r   s     r.   rV   z*FlaxBlenderbotDecoderLayerCollection.setupQ  r   r   Nr   r   r   r   r   r   r   c
           
      j   |rdnd }
|rdnd }|r|dnd }| j                   D ]`  }|r|
|fz  }
t        j                  dd      }|s|| j                  k  rd}n ||||||||      }|d   }|sL||d   fz  }|X||d   fz  }b |r|
|fz  }
||
||g}|	st	        d |D              S t        ||
||      S )	Nri   r   r    NNN)rv   r   r   r   r   r   rY   c              3   &   K   | ]	  }||  y wr   ri   r   s     r.   r   z@FlaxBlenderbotDecoderLayerCollection.__call__.<locals>.<genexpr>  r   r   r   r]   r   cross_attentions)r   r   r   r   rs   r   )rT   r]   rv   r   r   r   r   r   r   r   r   all_self_attnsall_cross_attentionsdecoder_layerr   r   r   s                    r.   r   z-FlaxBlenderbotDecoderLayerCollection.__call__X  s    #7BD0d&7<Q<]rdh![[ 	@M#!m%55!"(..A"6 &9DNN&J 2 -!#1*?+A)&7"/! *!,M =#3"55(4(]1-=,??(/	@4  -!11 "3^EYZ=G===<++%1	
 	
r0   )NNTFFFT)r   r   r   r!   r   r(   r   r:   rV   r   r   rA   r   ri   r0   r.   r   r   M  s    {{E399"7 8<8<" "'%* 8
  (4	8

 !) 58
 8
 8
  8
 #8
 8
r0   r   c            	           e Zd ZU eed<   ej                  ed<   ej                  Z	ej                  ed<   d Z
	 	 	 	 ddedededefd	Zy
)FlaxBlenderbotEncoderr3   embed_tokensr:   c                    t        j                  | j                  j                        | _        | j                  j
                  }| j                  j                  | _        | j                  j                  | _	        | j                  j                  rt        j                  |      nd| _        t        j                  | j                  j                  |t        j                   j                   j#                  | j                  j$                              | _        t)        | j                  | j*                        | _        t        j.                  | j*                  d      | _        y Nr?   g      ?)embedding_initr   r   )rE   rO   r3   r7   rP   r   r#   padding_idxrR   max_source_positionsscale_embeddingmathsqrtembed_scaleEmbedrG   rH   rI   rJ   embed_positionsr   r:   r   r   
layer_normrT   r4   s     r.   rV   zFlaxBlenderbotEncoder.setup  s    ZZT[[-@-@AKK''	;;33$(KK$G$G!37;;3N3N499Y/TW!xxKK//66..55dkk6J6JK 

 ;4;;

S,,TZZGr0   r   r   r   r   c                    |j                   }|j                  d|d         }| j                  |      | j                  z  }	| j	                  |      }
|	|
z   }| j                  ||      }| j                  ||||||      }|d   }| j                  |      }d }|r|d   }|d d |fz   }|s#||f|r|dd  n|dd  z   }t        d |D              S t        |||j                        S )	Nr'   r   )r   r   r   r   r   r    rY   c              3   &   K   | ]	  }||  y wr   ri   r   s     r.   r   z1FlaxBlenderbotEncoder.__call__.<locals>.<genexpr>  r   r   r   )r[   rZ   r  r  r  rP   r   r  rs   r   r   )rT   r"   rv   position_idsr   r   r   r   input_shapeinputs_embeds	embed_posr]   r   last_hidden_statess                 r.   r   zFlaxBlenderbotEncoder.__call__  s*     oo%%b+b/:	)))4t7G7GG((6	%	1**=*V++'/!5#  
 %QZ!__-?@ #AJM)#2.2D1FFM)=9L`WQR[fmnonpfqrG=G==="0'))
 	
r0   NFFTT)r   r   r   r!   r   rE   r  r(   r   r:   rV   rA   r   ri   r0   r.   r  r    se    (({{E399"H* #(%* "-

  -
 #-
 -
 -
r0   r  c                       e Zd ZU eed<   ej                  ed<   ej                  Z	ej                  ed<   d Z
	 	 	 	 	 	 	 ddeej                     deej                     ded	ed
ededefdZy)FlaxBlenderbotDecoderr3   r  r:   c                    t        j                  | j                  j                        | _        | j                  j
                  }| j                  j                  | _        | j                  j                  | _	        | j                  j                  r)t        j                  | j                  j
                        nd| _        t        j                  | j                  j                  |t        j                   j                   j#                  | j                  j$                              | _        t)        | j                  | j*                        | _        t        j.                  | j*                  d      | _        y r
  )rE   rO   r3   r7   rP   r   r#   r  rR   max_target_positionsr  r  r  r  r  rG   rH   rI   rJ   r  r   r:   r   r   r  r  s     r.   rV   zFlaxBlenderbotDecoder.setup  s    ZZT[[-@-@AKK''	;;33$(KK$G$G!=A[[=X=X499T[[%8%89^a!xxKK//66..55dkk6J6JK 
 ;4;;

S,,TZZGr0   Nr   r   r   r   r   r   r   c                    |j                   }|j                  d|d         }| j                  |      | j                  z  }| j	                  |      }||z   }| j                  ||
      }| j                  |||||
||||		      }|d   }| j                  |      }d }|r|d   }|d d |fz   }|	s#||f|r|dd  n|dd  z   }t        d |D              S t        |||j                  |j                        S )	Nr'   r   )r   r   r   r   r   r   r    rY   c              3   &   K   | ]	  }||  y wr   ri   r   s     r.   r   z1FlaxBlenderbotDecoder.__call__.<locals>.<genexpr>  r   r   r  )r[   rZ   r  r  r  rP   r   r  rs   r   r   r  )rT   r"   rv   r  r   r   r   r   r   r   r   r  r  	positionsr]   r   r  s                    r.   r   zFlaxBlenderbotDecoder.__call__  s>     oo%%b+b/:	)))4t7G7GG ((6	%	1**=*V++!"'!/!5#  

 %QZ!__-?@ #AJM)#2.2D1FFM)=9L`WQR[fmnonpfqrG=G===<0'))$55	
 	
r0   )NNFFFTT)r   r   r   r!   r   rE   r  r(   r   r:   rV   r   r   rA   r   ri   r0   r.   r  r    s    (({{E399"H, 8<8< "'%* "6

  (46
 !) 56
 6
  6
 #6
 6
 6
r0   r  c            	           e Zd ZU eed<   ej                  Zej                  ed<   d Zd Z	d Z
	 	 	 	 ddededed	efd
Zy)FlaxBlenderbotModuler3   r:   c                    t        j                  | j                  j                  | j                  j                  t
        j                   j                  j                  | j                  j                        | j                        | _
        t        | j                  | j                  | j                        | _        t        | j                  | j                  | j                        | _        y )N)r  r:   )r:   r  )rE   r  r3   
vocab_sizer   rG   rH   rI   rJ   r:   sharedr  encoderr  decoderr   s    r.   rV   zFlaxBlenderbotModule.setup,  s    hhKK""KK66..55dkk6J6JK**	
 -T[[

Y]YdYde,T[[

Y]YdYder0   c                     | j                   S r   )r*  r   s    r.   _get_encoder_modulez(FlaxBlenderbotModule._get_encoder_module7      ||r0   c                     | j                   S r   )r+  r   s    r.   _get_decoder_modulez(FlaxBlenderbotModule._get_decoder_module:  r.  r0   r   r   r   r   c                 *   | j                  ||||||	|
      }| j                  ||||d   ||||	|
	      }|	s||z   S t        |j                  |j                  |j
                  |j                  |j                  |j                  |j
                        S )N)r"   rv   r  r   r   r   r   r   )	r"   rv   r  r   r   r   r   r   r   )r   decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater   encoder_attentions)r*  r+  r   r   r]   r   r  )rT   r"   rv   decoder_input_idsdecoder_attention_maskr  decoder_position_idsr   r   r   r   encoder_outputsdecoder_outputss                r.   r   zFlaxBlenderbotModule.__call__=  s     ,,)%/!5#' ' 
 ,,'1-"1!"4#1/!5#' ' 

 "_44%-??"1"?"?.99,==&5&G&G"1"?"?.99
 	
r0   Nr  )r   r   r   r!   r   r(   r   r:   rV   r-  r0  rA   r   ri   r0   r.   r&  r&  (  se    {{E399"	f #(%* ".
  .
 #.
 .
 .
r0   r&  c                       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Zd$dej&                  j(                  d	ededefdZd Z ee       eee      	 	 	 	 	 	 	 	 d%dej8                  deej8                     deej8                     dee   dee   dee   dededefd              Z ee        ee!e      	 	 	 	 	 	 	 	 	 	 d&deej8                     deej8                     deej8                     d edee   dee   dee   dededefd!              Z" e#e$      	 	 	 	 	 	 	 	 	 	 	 d'dej8                  deej8                     d"eej8                     deej8                     deej8                     deej8                     dee   dee   dee   dededefd#       Z% xZ&S )(FlaxBlenderbotPreTrainedModelmodelbase_model_prefixNmodule_class)r    r    r   Tr3   r  seedr:   _do_initc                 Z     | j                   d||d|}t        | 	  ||||||       y )Nr3   r:   )r  r@  r:   rA  ri   )r?  super__init__)	rT   r3   r  r@  r:   rA  kwargsmodule	__class__s	           r.   rE  z&FlaxBlenderbotPreTrainedModel.__init__s  s=     #""H&HH[tSXcklr0   rngparamsr%   c           	      8   t        j                  |d      }|j                  d   j                  | j                  j
                        }t        j                  |      }|}t        j                  |      }|j                  \  }}	t        j                  t        j                  |	      d d d f   ||	f      }
t        j                  t        j                  |	      d d d f   ||	f      }t        j                  j                  |      \  }}||d}| j                  j                  ||||||
|      d   }|dt        t!        |            }t        t!        |            }| j"                  D ]
  }||   ||<    t               | _        t%        t'        |            S |S )Ni4rB   ).r'   )rJ  r7   rJ  )r(   rm   r*   r+   r3   eos_token_id	ones_liker[   rq   rr   rG   r   splitrG  initr   r	   _missing_keysr   r   )rT   rI  r  rJ  r"   rv   r6  r7  r   sequence_lengthr  r8  
params_rngr   rngsrandom_paramsmissing_keys                    r.   init_weightsz*FlaxBlenderbotPreTrainedModel.init_weights  s   IIk6	LL+//0H0HI	y1%!$y!9&/oo#
O''

?(CD!G(Lz[jNkl"//

?0KDRSG0TWacrVst"%**"2"23"7
K$=((" 
  (-)@AM!(6"23F#11 A&3K&@{#A!$D.011  r0   c           	         t        j                  ||fd      }t        j                  |      }t        j                  t        j                  t        j
                  |      j                  d         |j                        }d }| j                  j                  t        j                  j                  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.
        rL  rB   r'   c                 8    | j                         } ||||fi |S r   r0  rG  r6  r7  r8  rF  decoder_modules         r.   _decoder_forwardzBFlaxBlenderbotPreTrainedModel.init_cache.<locals>._decoder_forward  0    #779N!!&$ 	 r0   r   T)r6  r7  r8  r   r   methodrb   )r(   rQ   rN  rq   rr   
atleast_2dr[   rG  rP  rG   r   r   r	   )	rT   r   ry   r9  r6  r7  r8  r]  init_variabless	            r.   r   z(FlaxBlenderbotPreTrainedModel.init_cache  s      HHj*%=TJ!$/@!A"//JJs~~&78>>rBCEVE\E\ 
	 ))JJq!/#9!5"1!"4# * 
 w/00r0   output_typeconfig_classr"   rv   r  r   r   r   trainr   c
                 T   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|t	        j
                  |      }|A|j                  \  }
}t	        j                  t	        j                  |      dddf   |
|f      }i }|	|	|d<   d }| j                  j                  d|xs | j                  it	        j                  |d      t	        j                  |d      t	        j                  |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)
        ```Nr7   c                 8    | j                         } ||||fi |S r   )r-  )rG  r"   rv   r  rF  encode_modules         r.   _encoder_forwardz>FlaxBlenderbotPreTrainedModel.encode.<locals>._encoder_forward  s$    "668M NLSFSSr0   rJ  rL  rB   )	r"   rv   r  r   r   r   r   rT  r_  )r3   r   r   r   r(   rN  r[   rq   rr   rG  applyrJ  rg   )rT   r"   rv   r  r   r   r   re  rJ  r   r   rR  rT  ri  s                 r.   encodez$FlaxBlenderbotPreTrainedModel.encode  s.   : 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY! ]]95N*3//'J++CJJ,Ga,PS]_nRopL ")DO	T {{  v,-ii	699^4@<t</!5##)# ! 
 	
r0   r   r7  r8  past_key_valuesc                    ||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	|d   }|)|j                  dd \  }}t        j                  ||f      }|j                  \  }}|t        j                  ||f      }|?|t        d      t        j                  t        j                  |      dddf   ||f      }i }|||d<   d|xs | j                  i}|r	||d<   dg}nd}d	 }| j                  j                  |t        j                  |d
      t        j                  |d
      t        j                  |d
      |t        j                  |d
      |||	|
 |||      }||	r|\  }}t        |d         |d<   |S |"|	s |\  }}|dd t        |d         fz   |dd z   }|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   rY   KMake sure to provide `decoder_position_ids` when passing `past_key_values`.r7   rJ  rb   Fc                 8    | j                         } ||||fi |S r   rZ  r[  s         r.   r]  z>FlaxBlenderbotPreTrainedModel.decode.<locals>._decoder_forward[  r^  r0   rL  rB   r6  r7  r8  r   r   r   r   r   r   rT  mutabler_  rl  r    )r3   r   r   r   r[   r(   rQ   rD   rq   rr   rJ  rG  rj  rg   r	   )rT   r6  r9  r   r7  r8  rl  r   r   r   re  rJ  r   r   r   rR  rT  inputsrq  r]  r   pasts                         r.   decodez$FlaxBlenderbotPreTrainedModel.decode  s#   R 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY / 2!)*?*E*Ebq*I'J%(XXz?.K%L"&7&=&=#
O!)%(XXz?.K%L"'* !noo#&#3#3

?+D!G4z?6S$ 
 ")DOF1dkk2
 -F7OiGG	 ++##!ii(9F#&99-C4#P!$+?t!L"7#&99-C4#P/!5##)# $ 
" &;#MGT)1$w-)@G%&N(#MGTbqkXd7m%<$>>LGr0   r6  c                    ||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	|t	        j
                  |      }|A|j                  \  }}t	        j                  t	        j                  |      d d d f   ||f      }|6t        || j                   j                  | j                   j                        }|t	        j
                  |      }|A|j                  \  }}t	        j                  t	        j                  |      d d d f   ||f      }|d|ini }| j                  j                  d|xs | j                  it	        j                  |d      t	        j                  |d      t	        j                  |d      t	        j                  |d      t	        j                  |d      t	        j                  |d      |||	|
 |      S )N)r$   r7   rJ  rL  rB   )r"   rv   r  r6  r7  r8  r   r   r   r   rT  )r3   r   r   r   r(   rN  r[   rq   rr   r/   r#   r$   rG  rj  rJ  rg   )rT   r"   rv   r6  r7  r  r8  r   r   r   re  rJ  r   r   rR  rT  s                   r.   r   z&FlaxBlenderbotPreTrainedModel.__call__  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY ! ]]95N*3//'J++CJJ,Ga,PS]_nRopL $ 24;;33DKKLnLn! ")%(]]3D%E"'*;*A*A'J#&#3#3

?+D!G4z?6S$ 
 ,7+B	;'{{  v,-ii	699^4@<t<!ii(9F#&99-C4#P!$+?t!L/!5##) ! 
 	
r0   r   )NNNNNFNN
NNNNNNNFNN)NNNNNNNNFNN)'r   r   r   r!   rd  r>  r   r   r?  rE   Moduler(   r   r   r   r:   rA   rE  rG   r   r   r   rW  r   r   "BLENDERBOT_ENCODE_INPUTS_DOCSTRINGr   r   r   r   dictrk  "BLENDERBOT_DECODE_INPUTS_DOCSTRINGr   rt  r   BLENDERBOT_INPUTS_DOCSTRINGr   __classcell__)rH  s   @r.   r<  r<  n  sA   #L$s$"L"))"
 #);;
m 
m 3Z
m 	
m
 yy
m 
m"!

 2 2 "! "!PZ "!fp "!H'1R <=+>M]^ 15.2,0/3&*#;
;;;
 !-;
 s{{+	;

 $D>;
 'tn;
 d^;
 ;
 ;
 ;
 _ >;
z <=AP` 9=8<6: $,0/3&*#n !) 5	n
 !) 5n 's{{3n n $D>n 'tnn d^n n n n >n` ++FG 15378<.26:,0/3&*#9
;;9
 !-9
 $CKK0	9

 !) 59
 s{{+9
 's{{39
 $D>9
 'tn9
 d^9
 9
 9
 9
 H9
r0   r<  z_The bare MBart Model transformer outputting raw hidden-states without any specific head on top.c                   R    e Zd ZU eed<   ej                  Zej                  ed<   eZ	y)FlaxBlenderbotModelr3   r:   N)
r   r   r   r!   r   r(   r   r:   r&  r?  ri   r0   r.   r~  r~    s!    
 {{E399"'Lr0   r~  c            	           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 Zd Zd Z	 	 	 	 dded	ed
edefdZy),FlaxBlenderbotForConditionalGenerationModuler3   r:   .	bias_initc                    t        | j                  | j                        | _        t	        j
                  | j                  j                  j                  d| j                  t        j                  j                  j                  | j                  j                              | _        | j                  d| j                  d| j                  j                  j                  f      | _        y )NrC  Fr<   final_logits_biasr    )r&  r3   r:   r=  rE   rF   r)  num_embeddingsrG   rH   rI   rJ   lm_headparamr  r  r   s    r.   rV   z2FlaxBlenderbotForConditionalGenerationModule.setup  s    )DJJO
xxJJ,,**++224;;3G3GH	
 "&,?RSUYU_U_UfUfUuUuQv!wr0   c                 .    | j                   j                  S r   )r=  r*  r   s    r.   r-  z@FlaxBlenderbotForConditionalGenerationModule._get_encoder_module      zz!!!r0   c                 .    | j                   j                  S r   )r=  r+  r   s    r.   r0  z@FlaxBlenderbotForConditionalGenerationModule._get_decoder_module  r  r0   r   r   r   r   c                 d   | j                  |||||||||	|

      }|d   }| j                  j                  rJ| j                   j                  d   d   d   }| j                  j                  dd|j                  ii|      }n| j	                  |      }|t        j                  j                  | j                  j                  | j                              z  }|	s|f|dd  z   }|S t        ||j                  |j                  |j                   |j"                  |j$                  |j&                        S )	N)
r"   rv   r6  r7  r  r8  r   r   r   r   r   rJ  r)  	embeddingkernelr    )logitsr2  r3  r  r4  r   r5  )r=  r3   tie_word_embeddingsr   r  rj  TrG   r   stop_gradientr  r   r:   r   r2  r3  r  r4  r   r5  )rT   r"   rv   r6  r7  r  r8  r   r   r   r   r   r]   shared_embedding	lm_logitsoutputs                   r.   r   z5FlaxBlenderbotForConditionalGenerationModule.__call__  s0    **)/#9%!5/!5#'  
  
;;**#zz33H=hGT**HxAQASAS6T+UWdeI]3ISWW**4+A+A+H+H+TUU	\GABK/FM"")"?"?&99$55&-&G&G")"?"?&99
 	
r0   Nr  )r   r   r   r!   r   r(   r   r:   rG   rE   rH   rm   r  r   r   rV   r-  r0  rA   r   ri   r0   r.   r  r    s    {{E399",/FF,?,?,E,EIxS[[()Ex"" #(%* "0
  0
 #0
 0
 0
r0   r  zRThe Blenderbot Model with a language modeling head. Can be used for summarization.c                   p   e Zd ZU eZej                  Zej                  ed<    e	e
       eee      	 	 	 	 	 	 	 	 	 	 ddeej                     deej                     deej                     dedee   d	ee   d
ee   dededefd              Z	 	 	 ddeej*                     deej*                     fdZd Zy)&FlaxBlenderbotForConditionalGenerationr:   rb  Nr   r7  r8  rl  r   r   r   re  rJ  r   c                 (    ||n j                   j                  }||n j                   j                  }|	|	n j                   j                  }	|d   }|)|j                  dd \  }}t        j                  ||f      }|j                  \  }}|t        j                  ||f      }|?|t        d      t        j                  t        j                  |      dddf   ||f      }i }|||d<   d|xs  j                  i}|r	||d<   dg}nd} fd	} j                  j                  |t        j                  |d
      t        j                  |d
      t        j                  |d
      |t        j                  |d
      |||	|
 |||      }||\  }}n|\  \  }}}|	r.t        ||j                  |j                   |j"                        }n	|f|dd z   }||	rt%        d         |d<   |S ||	s|dd t%        d         fz   |dd z   }|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   rY   rn  r7   rJ  rb   Fc                 L   | j                         } ||||fi |}|d   }
j                  j                  rJ| j                  j                  d   d   d   }| j
                  j                  dd|j                  ii|      }	n| j                  |      }	|	| j                  z  }	|	|fS )Nr   rJ  r)  r  r  )	r0  r3   r  r=  r   r  rj  r  r  )rG  r6  r7  r8  rF  r\  r   r]   r  r  rT   s             r.   r]  zGFlaxBlenderbotForConditionalGeneration.decode.<locals>._decoder_forwardg  s    #779N$!&$ 	G $AJM{{..#)<<#9#9(#CH#Mk#Z "NN00(XGWGYGY<Z1[]jk	"NN=9	111Ig%%r0   rL  rB   rp  )r  r]   r   r  r    rl  )r3   r   r   r   r[   r(   rQ   rD   rq   rr   rJ  rG  rj  rg   r   r]   r   r  r	   )rT   r6  r9  r   r7  r8  rl  r   r   r   re  rJ  r   r   r   rR  rT  rr  rq  r]  r   r  r:  rs  s   `                       r.   rt  z-FlaxBlenderbotForConditionalGeneration.decode  ss   N 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY / 2!)*?*E*Ebq*I'J%(XXz?.K%L"&7&=&=#
O!)%(XXz?.K%L"'* !noo#&#3#3

?+D!G4z?6S$ 
 ")DOF1dkk2
 -F7OiGG	&& ++##!ii(9F#&99-C4#P!$+?t!L"7#&99-C4#P/!5##)# $ 
  ")0&I18.(Y$; -;;*55!0!A!A	G !l_QR%88G &;)1$w-)@G%&N(bqkXd7m%<$>>LGr0   rv   c                 N   |j                   \  }}| j                  |||      }	t        j                  ||fd      }
|-|j	                  d      dz
  }t        j                  |
|d      }
n4t        j                  t        j                  |d      d d d f   ||f      }|	|||
|dS )NrL  rB   r'   r   r    )r   r   )rl  r9  r   r7  r8  )	r[   r   r(   rQ   cumsumr   rp   rq   rr   )rT   r6  ry   rv   r7  r9  rF  r   
seq_lengthrl  extended_attention_maskr  s               r.   prepare_inputs_for_generationzDFlaxBlenderbotForConditionalGeneration.prepare_inputs_for_generation  s     "3!8!8
J//*j/R #&((J
+C4"P!-188b8AAEL&)&>&>?VXnpv&w#++CJJz,NtUVw,WZdfpYqrL  /.&4&=$0
 	
r0   c                 L    |j                   |d<   |d   d d dd f   dz   |d<   |S )Nrl  r8  r'   r    )rl  )rT   model_outputsmodel_kwargss      r.   update_inputs_for_generationzCFlaxBlenderbotForConditionalGeneration.update_inputs_for_generation  s?    *7*G*G&'/;<R/STUWYWZTZ/[^_/_+,r0   rv  r   )r   r   r   r  r?  r(   r   r:   r   r   rz  r   r   r!   r   r   ry  rA   r   rt  rG   Arrayr  r  ri   r0   r.   r  r    s9    @L{{E399"<=+P_op
 9=8<6: $,0/3&*#E !) 5	E
 !) 5E 's{{3E E $D>E 'tnE d^E E E E q >EV /36:
 !+	

 !) 3
>r0   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])
    ```
rb  )K__doc__r  r   	functoolsr   typingr   r   r   
flax.linenlinenrE   rG   	jax.numpynumpyr(   flax.core.frozen_dictr   r   r	   r
   r   flax.linen.attentionr   flax.traverse_utilr   r   r   
jax.randomr   modeling_flax_outputsr   r   r   r   r   modeling_flax_utilsr   r   r   r   r   utilsr   r   r   r   configuration_blenderbotr!   
get_loggerr   logger_CONFIG_FOR_DOC_CHECKPOINT_FOR_DOCBLENDERBOT_START_DOCSTRINGr{  rx  rz  r   r   r/   rw  r2   r   r   r   r   r  r  r&  r<  r~  r  r  0FLAX_BLENDERBOT_CONDITIONAL_GENERATION_DOCSTRINGri   r0   r.   <module>r     s       , ,  
  > > 6 > ;     u t 6 
		H	%$8  ,0 f& "<,& "`	#++ 	S 	Z] 	bebmbm 	d)bii d)P5 5r3
299 3
nU UrC
299 C
LB
BII B
JL
BII L
`C
299 C
LK
$7 K
\
 e(7 (	( 02EG]_n oE
299 E
P XZto-J ood4 0( *"RR !*8KZir0   