
    sgC                    x   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#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/m0Z0 ddl1m2Z2  e/jf                  e4      Z5dZ6dZ7dZ8dZ9dZ:dZ;dejx                  de=de=dejx                  fdZ> G d dej~                        Z@ G d dej~                        ZA G d  d!ej~                        ZB G d" d#ej~                        ZC G d$ d%ej~                        ZD G d& d'ej~                        ZE G d( d)ej~                        ZF G d* d+ej~                        ZG G d, d-ej~                        ZH G d. d/e(      ZI e-d0e8       G d1 d2eI             ZJ e)eJe6e#e7        G d3 d4ej~                        ZK e-d5e8       G d6 d7eI             ZLd8ZM e+eLe9eMz           e*eLe"e79        G d: d;ej~                        ZN e-d<e8       G d= d>eI             ZO e)eOe6e%e7        G d? d@ej~                        ZP e-dAe8       G dB dCeI             ZQ e)eQe6e$e7        G dD dEe(      ZR G dF dGej~                        ZS G dH dIej~                        ZT e-dJe8       G dK dLeR             ZU e)eUe6e!e7       y)MzFlax Bart 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'FlaxSeq2SeqQuestionAnsweringModelOutput#FlaxSeq2SeqSequenceClassifierOutput)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   )
BartConfigzfacebook/bart-baser#   a  
    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 ([`BartConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
        dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
            The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
            `jax.numpy.bfloat16` (on TPUs).

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

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

            If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
            [`~FlaxPreTrainedModel.to_bf16`].
a  
    Args:
        input_ids (`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       ^/var/www/html/venv/lib/python3.12/site-packages/transformers/models/bart/modeling_flax_bart.pyshift_tokens_rightr1      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)FlaxBartAttention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<   )r6   r7   head_dim
ValueErrorr   nnDenser;   r<   jaxinitializersnormalr5   init_stdq_projk_projv_projout_projDropoutr9   dropout_layerr:   r   r*   onesmax_position_embeddingscausal_mask)selfdenses     r0   setupzFlaxBartAttention.setup   s   $..8==4>>)T^^;MdnnM]$T^^$4B8 
 HHNNYY**++224;;3G3GH
 16%'-T[$+ZZT\\:;;/!T[[@@APX^ D r2   c                 p    |j                  |j                  d d | j                  | j                  fz         S N   )reshapeshaper7   rE   rV   hidden_statess     r0   _split_headszFlaxBartAttention._split_heads  s5    $$]%8%8!%<PTP]P]?^%^__r2   c                 Z    |j                  |j                  d d | j                  fz         S rZ   )r\   r]   r6   r^   s     r0   _merge_headszFlaxBartAttention._merge_heads  s,    $$]%8%8!%<?P%PQQr2   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   rD   )r*   arrayint32 r2   r0   <lambda>z9FlaxBartAttention._concatenate_to_cache.<locals>.<lambda>  s    CIIaWZW`W`Da r2   )r   r   r"   )has_variablevariabler*   zerosr]   r<   valuelenr   dynamic_update_slicebroadcast_toarangetupler
   )rV   keyrp   queryattention_maskis_initializedre   rf   rg   
batch_dims
max_lengthr7   depth_per_head	cur_indexindicesnum_updated_cache_vectorspad_masks                    r0   _concatenate_to_cachez'FlaxBartAttention._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>))r2   r_   key_value_statesrx   
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"   rd   re   rg   )axisr8   r9   T)r;   dropout_rngdropout_ratebroadcast_dropoutr   r<   	precisionz...hqk,...khd->...qhd)r]   rM   rN   rO   r`   r:   rm   	variablesr   dynamic_slicerU   r*   rs   expand_dimsr
   r   selectfullastyper<   finfominr9   make_rngr   einsumrb   rP   )rV   r_   r   rx   r   r   is_cross_attention
batch_sizequery_states
key_statesvalue_statesquery_length
key_length
mask_shiftmax_decoder_lengthrU   attention_biasr   attn_weightsattn_outputs                       r0   __call__zFlaxBartAttention.__call__1  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((r2   r'   N)NNFT)__name__
__module____qualname__r#   __annotations__intr9   floatr:   rC   r;   r*   float32r<   rX   r`   rb   rG   compactr   ndarrayr   r   r   rk   r2   r0   r4   r4      s    NNGUFDD${{E399"4`R ZZ* *D 3704 "[){{[) #3;;/[) !-	[)
 [) [) 
s{{	[)r2   r4   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)FlaxBartEncoderLayerr5   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r5   r6   r7   r9   r<   h㈵>r<   epsilonrA   r<   r@   )r5   d_modelr6   r4   encoder_attention_headsattention_dropoutr<   	self_attnrG   	LayerNormself_attn_layer_normrQ   r9   rR   r   activation_functionactivation_fnactivation_dropoutactivation_dropout_layerrH   encoder_ffn_dimrI   rJ   rK   rL   fc1fc2final_layer_normrV   s    r0   rX   zFlaxBartEncoderLayer.setup  sV   ,,*;;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r2   r_   rx   output_attentionsr   c                 |   |}| j                  ||      \  }}| j                  ||      }||z   }| j                  |      }|}| j                  | j	                  |            }| j                  ||      }| j                  |      }| j                  ||      }||z   }| j                  |      }|f}|r||fz  }|S )N)r_   rx   r   )r   rR   r   r   r   r   r   r   )rV   r_   rx   r   r   residualr   outputss           r0   r   zFlaxBartEncoderLayer.__call__  s     !&*nn=aon&p#|**=*V =011-@ **488M+BC55mS`5a/**=*V =0--m< "&Gr2   r   )TT)r   r   r   r#   r   r*   r   r<   rX   r   rC   r   r   rk   r2   r0   r   r     sn    {{E399"N6 #'"{{   	
  
s{{	r2   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	)FlaxBartEncoderLayerCollectionr5   r<   c           	          t        | j                  j                        D cg c]-  }t        | j                  t	        |      | j
                        / c}| _        | j                  j                  | _        y c c}w N)namer<   )	ranger5   encoder_layersr   strr<   layersencoder_layerdrop	layerdroprV   is     r0   rX   z$FlaxBartEncoderLayerCollection.setup  Y    V[\`\g\g\v\vVw
QR 3q6L
 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 )Nrk   r   r"   )NNc              3   &   K   | ]	  }||  y wNrk   .0vs     r0   	<genexpr>z:FlaxBartEncoderLayerCollection.__call__.<locals>.<genexpr>       =qq}=   last_hidden_stater_   
attentions)r   randomuniformr   ru   r   )rV   r_   rx   r   r   r   r   all_attentionsall_hidden_statesencoder_layerdropout_probabilitylayer_outputsr   s                r0   r   z'FlaxBartEncoderLayerCollection.__call__  s      1d"6BD![[ 	FM#$58H$H!"(..A"6 &9DNN&J , -!"%!	! *!,M !/=3C2E!E!	F$  -!11 "3^D=G==="+;LYg
 	
r2   N)TFFT)r   r   r   r#   r   r*   r   r<   rX   rC   r   rk   r2   r0   r   r     sZ    {{E399"7 #"'%* (
 	(

  (
 #(
 (
r2   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)FlaxBartDecoderLayerr5   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)r5   r6   r7   r9   r:   r<   rA   r   r   r   r   )r5   r   r6   r4   decoder_attention_headsr   r<   r   rG   rQ   r9   rR   r   r   r   r   r   r   r   encoder_attnencoder_attn_layer_normrH   decoder_ffn_dimrI   rJ   rK   rL   r   r   r   r   s    r0   rX   zFlaxBartDecoderLayer.setup  s   ,,*;;nnkk99KK11**
  ZZT[[-@-@A#DKK$C$CD(*

8V8V(W%$&LLtzz5$Q!-;;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r2   r_   rx   encoder_hidden_statesencoder_attention_maskr   r   r   c                    |}| j                  |||      \  }}	| j                  ||      }||z   }| j                  |      }d }
|B|}| j                  |||      \  }}
| j                  ||      }||z   }| j	                  |      }|}| j                  | j                  |            }| j                  ||      }| j                  |      }| j                  ||      }||z   }| j                  |      }|f}|r||	|
fz  }|S )N)r_   rx   r   r   )r_   r   rx   )
r   rR   r   r   r   r   r   r   r   r   )rV   r_   rx   r   r   r   r   r   r   self_attn_weightscross_attn_weightsr   s               r0   r   zFlaxBartDecoderLayer.__call__"  sZ    ! ,0>>'S] ,: ,
(( **=*V =011-@ " ,$H040A0A+!65 1B 1-M-
 !..}M.ZM$}4M 88GM !**488M+BC55mS`5a/**=*V =0--m< ")+=>>Gr2   r   )NNFTT)r   r   r   r#   r   r*   r   r<   rX   r   r   rC   r   r   rk   r2   r0   r   r     s    {{E399"NJ 8<8< "&"0{{0 0  (4	0
 !) 50 0  0 0 
s{{	0r2   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)FlaxBartDecoderLayerCollectionr5   r<   c           	          t        | j                  j                        D cg c]-  }t        | j                  t	        |      | j
                        / c}| _        | j                  j                  | _        y c c}w r   )	r   r5   decoder_layersr   r   r<   r   decoder_layerdropr   r   s     r0   rX   z$FlaxBartDecoderLayerCollection.setupY  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 )	Nrk   r   r"   NNN)rx   r   r   r   r   r   r[   c              3   &   K   | ]	  }||  y wr   rk   r   s     r0   r   z:FlaxBartDecoderLayerCollection.__call__.<locals>.<genexpr>  r   r   r   r_   r   cross_attentions)r   r   r   r   ru   r   )rV   r_   rx   r   r   r   r   r   r   r   r   all_self_attnsall_cross_attentionsdecoder_layerr   r   r   s                    r0   r   z'FlaxBartDecoderLayerCollection.__call___  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	
 	
r2   )NNTFFFTr   r   r   r#   r   r*   r   r<   rX   r   r   rC   r   rk   r2   r0   r   r   U  s    {{E399"7 8<8<" "'%* 8
  (4	8

 !) 58
 8
 8
  8
 #8
 8
r2   r   c                       e Zd ZU dZeed<   eed<   eed<   eed<   ej                  Z
ej                  ed<   d Zdej                  d	efd
Zy)FlaxBartClassificationHeadz-Head for sentence-level classification tasks.r5   	inner_dimnum_classespooler_dropoutr<   c                    t        j                  | j                  | j                  t        j                   j
                  j                  | j                  j                              | _	        t        j                  | j                        | _        t        j                  | j                  | j                  t        j                   j
                  j                  | j                  j                              | _        y )Nr   rA   )rG   rH   r  r<   rI   rJ   rK   r5   rL   rW   rQ   r  r9   r  rP   r   s    r0   rX   z FlaxBartClassificationHead.setup  s    XXNN$**#&&:M:M:T:TUYU`U`UiUi:j

 zzt':':;**++224;;3G3GH
r2   r_   r   c                     | j                  ||      }| j                  |      }t        j                  |      }| j                  ||      }| j	                  |      }|S )Nr   )r9   rW   r*   tanhrP   )rV   r_   r   s      r0   r   z#FlaxBartClassificationHead.__call__  sV    ]-P

=1/]-Pm4r2   N)r   r   r   __doc__r#   r   r   r   r*   r   r<   rX   r   rC   r   rk   r2   r0   r
  r
    sJ    7N{{E399"	
ckk $ r2   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
)FlaxBartEncoderr5   embed_tokensr<   c                 
   t        j                  | j                  j                        | _        | j                  j
                  }| j                  j                  | _        | j                  j                  | _	        | j                  j                  rt        j                  |      nd| _        d| _        t        j                  | j                  j                  | j                  z   |t         j                   j"                  j%                  | j                  j&                        | j(                        | _        t-        | j                  | j(                        | _        t        j0                  | j(                  d      | _        y NrA   g      ?r[   embedding_initr<   r   r   )rG   rQ   r5   r9   rR   r   r%   padding_idxrT   max_source_positionsscale_embeddingmathsqrtembed_scaleoffsetEmbedrI   rJ   rK   rL   r<   embed_positionsr   r   r   layernorm_embeddingrV   r6   s     r0   rX   zFlaxBartEncoder.setup  s    ZZT[[-@-@AKK''	;;33$(KK$G$G!37;;3N3N499Y/TW !xxKK//$++=66..55dkk6J6JK**	 
 5T[[$**M#%<<djj%#P r2   r   r   r   r   c                    |j                   }|j                  d|d         }| j                  |      | j                  z  }	| j	                  || j
                  z         }
|	|
z   }| j                  |      }| j                  ||      }| j                  ||||||      }|s|S t        |j                  |j                  |j                        S )Nr)   r   )r   r   r   r   r   )r]   r\   r  r  r!  r  r"  rR   r   r   r   r_   r   )rV   r$   rx   position_idsr   r   r   r   input_shapeinputs_embeds	embed_posr_   r   s                r0   r   zFlaxBartEncoder.__call__  s      oo%%b+b/:	)))4t7G7GG(()CD	%	100?**=*V++'/!5#  
 N"%77!//))
 	
r2   NFFTT)r   r   r   r#   r   rG   r   r*   r   r<   rX   rC   r   rk   r2   r0   r  r    se    (({{E399"Q2 #(%* "%

  %
 #%
 %
 %
r2   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)FlaxBartDecoderr5   r  r<   c                 2   t        j                  | j                  j                        | _        | j                  j
                  }| j                  j                  | _        | j                  j                  | _	        | j                  j                  r)t        j                  | j                  j
                        nd| _        d| _        t        j                  | j                  j                  | j                  z   |t         j                   j"                  j%                  | j                  j&                        | j(                        | _        t-        | j                  | j(                        | _        t        j0                  | j(                  d      | _        y r  )rG   rQ   r5   r9   rR   r   r%   r  rT   max_target_positionsr  r  r  r  r  r   rI   rJ   rK   rL   r<   r!  r   r   r   r"  r#  s     r0   rX   zFlaxBartDecoder.setup  s   ZZT[[-@-@AKK''	;;33$(KK$G$G!=A[[=X=X499T[[%8%89^a !xxKK//$++=66..55dkk6J6JK**	 
 5T[[$**M#%<<djj%#P r2   Nr   r   r   r   r   r   r   c                    |j                   }|j                  d|d         }| j                  |      | j                  z  }| j	                  || j
                  z         }||z   }| j                  |      }| j                  ||
      }| j                  |||||
||||		      }|	s|S t        |j                  |j                  |j                  |j                        S )Nr)   r   r   r   r   r   r   r  )r]   r\   r  r  r!  r  r"  rR   r   r   r   r_   r   r  )rV   r$   rx   r%  r   r   r   r   r   r   r   r&  r'  	positionsr_   r   s                   r0   r   zFlaxBartDecoder.__call__  s      oo%%b+b/:	)))4t7G7GG (()CD	%	100?**=*V++!"'!/!5#  

 N<%77!//))$55	
 	
r2   NNFFFTT)r   r   r   r#   r   rG   r   r*   r   r<   rX   r   r   rC   r   rk   r2   r0   r+  r+    s    (({{E399"Q4 8<8< "'%* ".

  (4.
 !) 5.
 .
  .
 #.
 .
 .
r2   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)FlaxBartModuler5   r<   c                    t        j                  | j                  j                  | j                  j                  t
        j                   j                  j                  | j                  j                        | j                        | _
        t        | j                  | j                  | j                        | _        t        | j                  | j                  | j                        | _        y )Nr  )r<   r  )rG   r   r5   
vocab_sizer   rI   rJ   rK   rL   r<   sharedr  encoderr+  decoderr   s    r0   rX   zFlaxBartModule.setupG  s    hhKK""KK66..55dkk6J6JK**	
 't{{$**SWS^S^_&t{{$**SWS^S^_r2   c                     | j                   S r   )r7  r   s    r0   _get_encoder_modulez"FlaxBartModule._get_encoder_moduleR      ||r2   c                     | j                   S r   r8  r   s    r0   _get_decoder_modulez"FlaxBartModule._get_decoder_moduleU  r;  r2   r   r   r   r   c                 *   | j                  ||||||	|
      }| j                  ||||d   ||||	|
	      }|	s||z   S t        |j                  |j                  |j
                  |j                  |j                  |j                  |j
                        S )N)r$   rx   r%  r   r   r   r   r   )	r$   rx   r%  r   r   r   r   r   r   )r   decoder_hidden_statesdecoder_attentionsr  encoder_last_hidden_stater   encoder_attentions)r7  r8  r   r   r_   r   r  )rV   r$   rx   decoder_input_idsdecoder_attention_maskr%  decoder_position_idsr   r   r   r   encoder_outputsdecoder_outputss                r0   r   zFlaxBartModule.__call__X  s     ,,)%/!5#' ' 
 ,,'1-"1!"4#1/!5#' ' 

 "_44%-??"1"?"?.99,==&5&G&G"1"?"?.99
 	
r2   Nr)  )r   r   r   r#   r   r*   r   r<   rX   r:  r>  rC   r   rk   r2   r0   r3  r3  C  se    {{E399"	` #(%* ".
  .
 #.
 .
 .
r2   r3  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 )(FlaxBartPreTrainedModelmodelbase_model_prefixNmodule_classr"   r"   r   Tr5   r&  seedr<   _do_initc                 Z     | j                   d||d|}t        | 	  ||||||       y )Nr5   r<   r&  rO  r<   rP  rk   )rM  super__init__	rV   r5   r&  rO  r<   rP  kwargsmodule	__class__s	           r0   rU  z FlaxBartPreTrainedModel.__init__  s=     #""H&HH[tSXcklr2   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i4rD   ).r)   r[  r9   r[  )r*   ro   r,   r-   r5   eos_token_id	ones_liker]   rs   rt   rI   r   splitrX  initr   r	   _missing_keysr   r   )rV   rZ  r&  r[  r$   rx   rD  rE  r   sequence_lengthr%  rF  
params_rngr   rngsrandom_paramsmissing_keys                    r0   init_weightsz$FlaxBartPreTrainedModel.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  r2   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.
        r]  rD   r)   c                 8    | j                         } ||||fi |S r   r>  rX  rD  rE  rF  rW  decoder_modules         r0   _decoder_forwardz<FlaxBartPreTrainedModel.init_cache.<locals>._decoder_forward  0    #779N!!&$ 	 r2   r   T)rD  rE  rF  r   r   methodrd   r*   rS   r`  rs   rt   
atleast_2dr]   rX  rb  rI   r   r   r	   )	rV   r   r{   rG  rD  rE  rF  ro  init_variabless	            r0   r   z"FlaxBartPreTrainedModel.init_cache  s      HHj*%=TJ!$/@!A"//JJs~~&78>>rBCEVE\E\ 
	 ))JJq!/#9!5"1!"4# * 
 w/00r2   output_typeconfig_classr$   rx   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, FlaxBartForConditionalGeneration

        >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")

        >>> 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)
        ```Nr9   c                 8    | j                         } ||||fi |S r   )r:  )rX  r$   rx   r%  rW  encode_modules         r0   _encoder_forwardz8FlaxBartPreTrainedModel.encode.<locals>._encoder_forward  s$    "668M NLSFSSr2   r[  r]  rD   )	r$   rx   r%  r   r   r   r   rf  rq  )r5   r   r   r   r*   r`  r]   rs   rt   rX  applyr[  ri   )rV   r$   rx   r%  r   r   r   rx  r[  r   r   rd  rf  r|  s                 r0   encodezFlaxBartPreTrainedModel.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##)# ! 
 	
r2   r   rE  rF  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 )ax  
        Returns:

        Example:

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

        >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")

        >>> 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   r[   KMake sure to provide `decoder_position_ids` when passing `past_key_values`.r9   r[  rd   Fc                 8    | j                         } ||||fi |S r   rl  rm  s         r0   ro  z8FlaxBartPreTrainedModel.decode.<locals>._decoder_forwardt  rp  r2   r]  rD   rD  rE  rF  r   r   r   r   r   r   rf  mutablerq  r  r"   )r5   r   r   r   r]   r*   rS   rF   rs   rt   r[  rX  r}  ri   r	   )rV   rD  rG  r   rE  rF  r  r   r   r   rx  r[  r   r   r   rd  rf  inputsr  ro  r   pasts                         r0   decodezFlaxBartPreTrainedModel.decode&  s#   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##)# $ 
" &;#MGT)1$w-)@G%&N(#MGTbqkXd7m%<$>>LGr2   rD  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&   r9   r[  r]  rD   )r$   rx   r%  rD  rE  rF  r   r   r   r   rf  )r5   r   r   r   r*   r`  r]   rs   rt   r1   r%   r&   rX  r}  r[  ri   )rV   r$   rx   rD  rE  r%  rF  r   r   r   rx  r[  r   r   rd  rf  s                   r0   r   z FlaxBartPreTrainedModel.__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##) ! 
 	
r2   r   )NNNNNFNN
NNNNNNNFNN)NNNNNNNNFNN)'r   r   r   r#   rw  rL  r   r   rM  rG   Moduler*   r   r   r   r<   rC   rU  rI   r   r   r   ri  r   r   BART_ENCODE_INPUTS_DOCSTRINGr!   r   r   r   dictr~  BART_DECODE_INPUTS_DOCSTRINGr   r  r   BART_INPUTS_DOCSTRINGr   __classcell__rY  s   @r0   rJ  rJ    s?   L$s$"L"))"
 #);;
m
m 3Z
m 	
m
 yy
m 
m"!

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

 $D>;
 'tn;
 d^;
 ;
 ;
 ;
 Y 8;
z 67+Xgqr
 9=8<6: $,0/3&*#n !) 5	n
 !) 5n 's{{3n n $D>n 'tnn d^n n n n s 8n` ++@A 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
 B9
r2   rJ  z^The bare Bart 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)FlaxBartModelr5   r<   N)
r   r   r   r#   r   r*   r   r<   r3  rM  rk   r2   r0   r  r    s!    
 {{E399"!Lr2   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)&FlaxBartForConditionalGenerationModuler5   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 )NrR  Fr>   final_logits_biasr"   )r3  r5   r<   rK  rG   rH   r6  num_embeddingsrI   rJ   rK   rL   lm_headparamr  r  r   s    r0   rX   z,FlaxBartForConditionalGenerationModule.setup  s    #4;;djjI
xxJJ,,**++224;;3G3GH	
 "&,?RSUYU_U_UfUfUuUuQv!wr2   c                 .    | j                   j                  S r   rK  r7  r   s    r0   r:  z:FlaxBartForConditionalGenerationModule._get_encoder_module      zz!!!r2   c                 .    | j                   j                  S r   rK  r8  r   s    r0   r>  z:FlaxBartForConditionalGenerationModule._get_decoder_module  r  r2   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$   rx   rD  rE  r%  rF  r   r   r   r   r   r[  r6  	embeddingkernelr"   logitsr@  rA  r  rB  r   rC  )rK  r5   tie_word_embeddingsr   r  r}  TrI   r   stop_gradientr  r   r<   r   r@  rA  r  rB  r   rC  )rV   r$   rx   rD  rE  r%  rF  r   r   r   r   r   r_   shared_embedding	lm_logitsoutputs                   r0   r   z/FlaxBartForConditionalGenerationModule.__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
 	
r2   Nr)  )r   r   r   r#   r   r*   r   r<   rI   rG   rJ   ro   r  r   r   rX   r:  r>  rC   r   rk   r2   r0   r  r    s    {{E399",/FF,?,?,E,EIxS[[()Ex"" #(%* "0
  0
 #0
 0
 0
r2   r  zLThe BART 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) FlaxBartForConditionalGenerationr<   ru  Nr   rE  rF  r  r   r   r   rx  r[  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 )aY  
        Returns:

        Example:

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

        >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")

        >>> 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   r[   r  r9   r[  rd   Fc                 ~   | j                         } ||||fi |}|d   }
j                  j                  rJ| j                  j                  d   d   d   }| j
                  j                  dd|j                  ii|      }	n| j                  |      }	|	| j                  j                  
j                        z  }	|	|fS )Nr   r[  r6  r  r  )r>  r5   r  rK  r   r  r}  r  r  r   r<   )rX  rD  rE  rF  rW  rn  r   r_   r  r  rV   s             r0   ro  zAFlaxBartForConditionalGeneration.decode.<locals>._decoder_forward  s    #779N$!&$ 	G $AJM{{..#)<<#9#9(#CH#Mk#Z "NN00(XGWGYGY<Z1[]jk	"NN=9	1188DDIg%%r2   r]  rD   r  r  r_   r   r  r"   r  )r5   r   r   r   r]   r*   rS   rF   rs   rt   r[  rX  r}  ri   r   r_   r   r  r	   )rV   rD  rG  r   rE  rF  r  r   r   r   rx  r[  r   r   r   rd  rf  r  r  ro  r   r  rH  r  s   `                       r0   r  z'FlaxBartForConditionalGeneration.decode1  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r2   rx   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 )Nr]  rD   r)   r   r"   r   r   )r  rG  r   rE  rF  	r]   r   r*   rS   cumsumr   rr   rs   rt   )rV   rD  r{   rx   rE  rG  rW  r   
seq_lengthr  extended_attention_maskr%  s               r0   prepare_inputs_for_generationz>FlaxBartForConditionalGeneration.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
 	
r2   c                 L    |j                   |d<   |d   d d dd f   dz   |d<   |S )Nr  rF  r)   r"   r  rV   model_outputsmodel_kwargss      r0   update_inputs_for_generationz=FlaxBartForConditionalGeneration.update_inputs_for_generation  s?    *7*G*G&'/;<R/STUWYWZTZ/[^_/_+,r2   r  r  )r   r   r   r  rM  r*   r   r<   r   r   r  r!   r   r#   r   r   r  rC   r   r  rI   Arrayr  r  rk   r2   r0   r  r  *  s8    :L{{E399"67+P_ij
 9=8<6: $,0/3&*#E !) 5	E
 !) 5E 's{{3E E $D>E 'tnE d^E E E E k 8EV /36:
 !+	

 !) 3
>r2   r  a  
    Returns:

    Summarization example:

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

    >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
    >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large-cnn")

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

    >>> # Generate Summary
    >>> summary_ids = model.generate(inputs["input_ids"]).sequences
    >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
    ```

    Mask filling example:

    ```python
    >>> import jax
    >>> from transformers import AutoTokenizer, FlaxBartForConditionalGeneration

    >>> model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large")
    >>> tokenizer = AutoTokenizer.from_pretrained("facebook/bart-large")

    >>> TXT = "My friends are <mask> but they eat too many carbs."
    >>> input_ids = tokenizer([TXT], return_tensors="jax")["input_ids"]

    >>> logits = model(input_ids).logits
    >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero()[0].item()
    >>> probs = jax.nn.softmax(logits[0, masked_index], axis=0)
    >>> values, predictions = jax.lax.top_k(probs, k=1)

    >>> tokenizer.decode(predictions).split()
    ```
ru  c            	           e Zd ZU eed<   ej                  Zej                  ed<   dZe	e
   ed<   d Zd Zd Z	 	 	 	 dded	ed
edefdZy)'FlaxBartForSequenceClassificationModuler5   r<   N
num_labelsc                 4   t        | j                  | j                        | _        t	        | j                  | j                  j
                  | j                  | j                  n| j                  j                  | j                  j                        | _        y )NrR  )r5   r  r  r  )	r3  r5   r<   rK  r
  r   r  classifier_dropoutclassification_headr   s    r0   rX   z-FlaxBartForSequenceClassificationModule.setup  sb    #4;;djjI
#=;;kk))+/??+FDKKLbLb;;99	$
 r2   c                 .    | j                   j                  S r   r  r   s    r0   r:  z;FlaxBartForSequenceClassificationModule._get_encoder_module  r  r2   c                 .    | j                   j                  S r   r  r   s    r0   r>  z;FlaxBartForSequenceClassificationModule._get_decoder_module   r  r2   r   r   r   r   c                    | j                  |||||||||	|

      }|d   }t        j                  || j                  j                  k(  dd      }t        |t        j                  j                  j                        st        t        j                  |j                  d                  dkD  rt        d      t        |j                  d      dk(        rt        d      |t        j                  |j                   d         dz  z   }t        j                  ||j#                  d      j%                  dd      k(  dd      }t        j&                  d||      j                  d      }| j)                  ||
	      }|	s|f|dd  z   }|S t+        ||j,                  |j.                  |j0                  |j2                  |j4                  |j6                  
      S )Nr  r   r"   z7All examples must have the same number of <eos> tokens.z+There are missing <eos> tokens in input_idsgư>r)   zijk, ij -> ijkr   r  )rK  r*   r.   r5   r_  
isinstancerI   interpreterspartial_evalDynamicJaxprTracerrq   uniquesumrF   anyrt   r]   maxr\   r   r  r   r@  rA  r  rB  r   rC  )rV   r$   rx   rD  rE  r%  rF  r   r   r   r   r   r_   eos_maskeos_mask_noisedsentence_representationr  r  s                     r0   r   z0FlaxBartForSequenceClassificationModule.__call__#  s    **)/#9%!5/!5#'  
  
99Y$++*B*BBAqI (C$4$4$A$A$T$TU3::hll1o./!3 !Z[[8<<?a'( !NOO 'HNN14E)F)MMOyyO4G4G4J4R4RSUWX4Y!Y[\^_`H"%**-=}h"W"["[\]"^))*AQ^)_Y,FM2")"?"?&99$55&-&G&G")"?"?&99
 	
r2   r)  )r   r   r   r#   r   r*   r   r<   r  r   r   rX   r:  r>  rC   r   rk   r2   r0   r  r    sr    {{E399" $J$
"" #(%* "9
  9
 #9
 9
 9
r2   r  z
    Bart model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
    tasks.
    c                   (    e Zd ZeZej                  Zy)!FlaxBartForSequenceClassificationN)r   r   r   r  rM  r*   r   r<   rk   r2   r0   r  r  _  s     ;LKKEr2   r  c            	           e Zd ZU eed<   ej                  Zej                  ed<   dZd Z	d Z
d Z	 	 	 	 ddeded	ed
efdZy)"FlaxBartForQuestionAnsweringModuler5   r<   r[   c                 (   t        | j                  | j                        | _        t	        j
                  | j                  | j                  t        j                  j                  j                  | j                  j                              | _        y )NrR  r   )r3  r5   r<   rK  rG   rH   r  rI   rJ   rK   rL   
qa_outputsr   s    r0   rX   z(FlaxBartForQuestionAnsweringModule.setupx  sY    #4;;djjI
((OO4::366;N;N;U;UVZVaVaVjVj;k
r2   c                 .    | j                   j                  S r   r  r   s    r0   r:  z6FlaxBartForQuestionAnsweringModule._get_encoder_module~  r  r2   c                 .    | j                   j                  S r   r  r   s    r0   r>  z6FlaxBartForQuestionAnsweringModule._get_decoder_module  r  r2   r   r   r   r   c                    | j                  |||||||||	|

      }|d   }| j                  |      }t        j                  ||j                  d   d      \  }}|j                  d      }|j                  d      }|	s||f|dd  z   }|S t        |||j                  |j                  |j                  |j                  |j                  |j                        S )Nr  r   r)   r   r"   )start_logits
end_logitsr@  rA  r  rB  r   rC  )rK  r  r*   ra  r]   squeezer   r@  rA  r  rB  r   rC  )rV   r$   rx   rD  rE  r%  rF  r   r   r   r   r   sequence_outputr  r  r  r  s                    r0   r   z+FlaxBartForQuestionAnsweringModule.__call__  s     **)/#9%!5/!5#'  
 "!*1#&99VV\\"5EB#O j#++B/''+
"J/'!"+=FM6%!")"?"?&99$55&-&G&G")"?"?&99	
 		
r2   Nr)  )r   r   r   r#   r   r*   r   r<   r  rX   r:  r>  rC   r   rk   r2   r0   r  r  s  si    {{E399"J
"" #(%* ".
  .
 #.
 .
 .
r2   r  z
    BART Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
    layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
    c                   (    e Zd ZeZej                  Zy)FlaxBartForQuestionAnsweringN)r   r   r   r  rM  r*   r   r<   rk   r2   r0   r  r    s     6LKKEr2   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      	 	 	 	 	 	 	 	 	 	 	 d dej4                  deej4                     deej4                     deej4                     deej4                     dee   dee   dee   dedededefd       Z xZS )!FlaxBartDecoderPreTrainedModelrK  rL  NrM  rN  r   Tr5   r&  rO  r<   rP  c                 v    d|_         d|_         | j                  d||d|}t        |   ||||||       y )NTFrR  rS  rk   )
is_decoderis_encoder_decoderrM  rT  rU  rV  s	           r0   rU  z'FlaxBartDecoderPreTrainedModel.__init__  sM     !$)!"""H&HH[tSXcklr2   rZ  r[  r'   c           	         t        j                  |d      }t        j                  |      }|j                  \  }}t        j                  t        j
                  |      d d d f   ||f      }t        j                  j                  |      \  }	}
|	|
d}t        j                  || j                  j                  fz         }|}| j                  j                  ||||||d      }|d   S )Nr]  rD   r^  F)r   r[  )r*   ro   r`  r]   rs   rt   rI   r   ra  r5   r   rX  rb  )rV   rZ  r&  r[  r$   rx   r   rd  r%  re  r   rf  r   r   module_init_outputss                  r0   ri  z+FlaxBartDecoderPreTrainedModel.init_weights  s    IIk6	y1&/oo#
O''

?(CD!G(Lz[jNkl"%**"2"23"7
K$= #		+9L9L8N*N O!/"kk..!" / 
 #8,,r2   c                    t        j                  ||fd      }t        j                  |d      }t        j                  t        j                  t        j
                  |      j                  d         |j                        }| j                  j                  t        j                  j                  d      |||dd      }t        |d         S )	aW  
        Args:
            batch_size (`int`):
                batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
            max_length (`int`):
                maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
                cache.
        r]  rD   r)   r   FT)r   r   rd   rr  )rV   r   r{   r$   rx   r%  rt  s          r0   r   z)FlaxBartDecoderPreTrainedModel.init_cache  s     HHj*5TB	y=''

3>>)3L3R3RSU3V(WYbYhYhi))JJq!9nlX]jn * 
 w/00r2   r$   rx   r%  r   r   r   r   r   rx  r  r   c                 L   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|+|)|j                  d d \  }}t        j                  ||f      }|t        j                  |      }|A|j                  \  }}t        j                  t        j                  |      d d d f   ||f      }|d|ini }d|
xs | j                  i}|r	||d<   dg}nd}| j                  j                  |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 )Nr[   r9   r[  rd   Fr]  rD   )r$   rx   r%  r   r   r   r   r   r   rf  r  r  r"   )r5   r   r   r   r]   r*   rS   r`  rs   rt   r[  rX  r}  ri   r	   )rV   r$   rx   r%  r   r   r   r   r   rx  r[  r  r   r   rd  rf  r  r  r   s                      r0   r   z'FlaxBartDecoderPreTrainedModel.__call__  s     2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++BYBY ,1G1O*?*E*Ebq*I'J%(XXz?.K%L" ! ]]95N*3//'J++CJJ,Ga,PS]_nRopL ,7+B	;'F1dkk2
 -F7OiGG++##ii	699^4@<t<"7#9/!5##) $ 
  &;'.$G_)1/'2J)KG%&N('.$G_bqkXog.F%G$IIGTUTVKWGr2   r   )NNNNNNNFNNN)r   r   r   r#   rw  rL  r   r   rM  rG   r  r*   r   r   r   r<   rC   rU  rI   r   r   r   ri  r   r   r  r   r   r  r   r  r  s   @r0   r  r    s   L$s$"L"))"
 #);;mm 3Zm 	m
 yym m-

 2 2 - -PZ -fp -.1& ++GH 15.27;8<,0/3&* $#F;;F !-F s{{+	F
  (4F !) 5F $D>F 'tnF d^F F F F F IFr2   r  c                   ^    e Zd ZU dZeed<   ej                  Zej                  ed<   d Z	d Z
y)FlaxBartDecoderWrapperz
    This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
    used in combination with the [`EncoderDecoderModel`] framework.
    r5   r<   c                 b   | j                   j                  }t        j                  | j                   j                  |t
        j                  j                  j                  | j                   j                        | j                        }t        | j                   || j                        | _        y )Nr  )r5   r  r<   )r5   r   rG   r   r5  rI   rJ   rK   rL   r<   r+  r8  )rV   r6   r  s      r0   rX   zFlaxBartDecoderWrapper.setupY  su    KK''	xxKK""66..55dkk6J6JK**	
 'dkk\`\f\fgr2   c                 &     | j                   |i |S r   r=  )rV   argsrW  s      r0   r   zFlaxBartDecoderWrapper.__call__c  s    t||T,V,,r2   N)r   r   r   r  r#   r   r*   r   r<   rX   r   rk   r2   r0   r  r  P  s,    
 {{E399"h-r2   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)FlaxBartForCausalLMModuler5   r<   c                 >   t        | j                  | j                        | _        t	        j
                  | j                  j                  d| j                  t        j                  j                  j                  | j                  j                              | _        y )NrR  Fr>   )r  r5   r<   rK  rG   rH   r5  rI   rJ   rK   rL   r  r   s    r0   rX   zFlaxBartForCausalLMModule.setupk  sa    +4;;djjQ
xxKK""**++224;;3G3GH	
r2   Nr   r   r   r   r   r   r   c                    | j                  ||||||
||||	
      }|d   }| j                  j                  rM| j                   j                  d   d   d   d   }| j                  j                  dd|j                  ii|      }n| j	                  |      }|	s	|f|dd  z   S t        ||j                  |j                  |j                  	      S )
Nr/  r   r[  r8  r  r  r  r"   r  )rK  r5   r  r   r  r}  r  r   r_   r   r  )rV   r$   rx   r%  r   r   r   r   r   r   r   r   r_   r  r  s                  r0   r   z"FlaxBartForCausalLMModule.__call__t  s     **!"'!/!5#  
  
;;**#zz33H=iHXYde**HxAQASAS6T+UWdeI]3I<'!"+--4!//))$55	
 	
r2   r1  r  rk   r2   r0   r  r  g  s    {{E399"
 8<8< "'%* "*

  (4*
 !) 5*
 *
  *
 #*
 *
 *
r2   r  z
    Bart Decoder Model with a language modeling head on top (linear layer with weights tied to the input embeddings)
    e.g for autoregressive tasks.
    c                   >    e Zd ZeZddeej                     fdZd Z	y)FlaxBartForCausalLMNrx   c                 H   |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 )Nr]  rD   r)   r   r"   r  )r  rx   r%  r  )	rV   r$   r{   rx   r   r  r  r  r%  s	            r0   r  z1FlaxBartForCausalLM.prepare_inputs_for_generation  s    !*
J//*jA #&((J
+C4"P%)00b09A=L&)&>&>?VXfhn&o#++CJJz,NtUVw,WZdfpYqrL  /5(
 	
r2   c                 L    |j                   |d<   |d   d d dd f   dz   |d<   |S )Nr  r%  r)   r"   r  r  s      r0   r  z0FlaxBartForCausalLM.update_inputs_for_generation  s8    *7*G*G&''3N'CArsF'Ka'O^$r2   r   )
r   r   r   r  rM  r   rI   r  r  r  rk   r2   r0   r  r    s'     -L
S[\_\e\eSf 
*r2   r  )Vr  r  r   	functoolsr   typingr   r   r   
flax.linenlinenrG   rI   	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   r   r   modeling_flax_utilsr   r   r   r   r   utilsr   r   r    r!   configuration_bartr#   
get_loggerr   logger_CHECKPOINT_FOR_DOC_CONFIG_FOR_DOCBART_START_DOCSTRINGr  r  r  r   r   r1   r  r4   r   r   r   r   r
  r  r+  r3  rJ  r  r  r  *FLAX_BART_CONDITIONAL_GENERATION_DOCSTRINGr  r  r  r  r  r  r  r  rk   r2   r0   <module>r     s?       , ,  
  > > 6 > ;      u t * 
		H	%*   D0 f  <,  ^	#++ 	S 	Z] 	bebmbm 	d)		 d)N6299 6r2
RYY 2
jU299 UpB
RYY B
J :>
bii >
BH
bii H
VC
RYY C
LI
1 I
X
 d"+ "	" ],?AWYh iE
RYY E
P RTho'> ood&. *P $&;>h&h !$2ETc
M
bii M
`  (? 
 %'	?
 ?
D  #: 
  +	D%8 DN-RYY -.7
		 7
t  8 < )	r2   