Ë
    T^(h…[ ã                  óÒ  — d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
 ddlZddl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 dd
lmZmZmZmZ ddlm Z  ddl!m"Z"  ejF                  e$«      Z%dZ&e G d„ de«      «       Z'e G d„ de«      «       Z( G d„ de«      Z)dZ*dZ+ ee*«       G d„ de)«      «       Z, ede*«       G d„ de)e«      «       Z- ede*«       G d„ de)e«      «       Z.g d¢Z/y) zTFRAG model implementation.é    )ÚannotationsN)Ú	dataclass)ÚListÚOptionalÚTupleÚUnioné   )ÚPretrainedConfig)ÚTFLogitsProcessorList)ÚTFCausalLanguageModelingLossÚTFModelInputTypeÚTFPreTrainedModelÚkerasÚ
shape_listÚunpack_inputs)ÚModelOutputÚ%add_start_docstrings_to_model_forwardÚloggingÚreplace_return_docstringsé   )Ú	RagConfig)ÚRagRetrieverr   c                  óò   — e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	ded
<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   y)ÚTFRetrievAugLMMarginOutputa‡  
    Base class for retriever augmented marginalized models outputs.

    Args:
        loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss.
        logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
            each vocabulary token.
        past_key_values (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
            sequence_length, embed_size_per_head)`).

            Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
            (see `past_key_values` input) to speed up sequential decoding.
        doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
            Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
            `question_encoder_last_hidden_state`.
        retrieved_doc_embeds (`tf.Tensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
            Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
            the `doc_scores`.
        retrieved_doc_ids (`tf.Tensor` (int32) of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
            The indexes of the embedded documents retrieved by the retriever.
        context_input_ids (`tf.Tensor`(int32) of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
            Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
        context_attention_mask (`tf.Tensor` (int32) of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
            Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
            retriever.
        question_encoder_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
            model.
        question_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
        question_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
        generator_enc_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
        generator_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
        generator_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
        generator_dec_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
        generator_dec_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
    Nútf.Tensor | NoneÚlossúOptional[tf.Tensor]ÚlogitsúList[tf.Tensor] | NoneÚpast_key_valuesÚ
doc_scoresÚretrieved_doc_embedsÚretrieved_doc_idsÚcontext_input_idsÚcontext_attention_maskÚ"question_encoder_last_hidden_stateúTuple[tf.Tensor, ...] | NoneÚquestion_enc_hidden_statesÚquestion_enc_attentionsÚgenerator_enc_last_hidden_stateÚgenerator_enc_hidden_statesÚgenerator_enc_attentionsÚgenerator_dec_hidden_statesÚgenerator_dec_attentions)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   r    r!   r"   r#   r$   r%   r&   r(   r)   r*   r+   r,   r-   r.   © ó    úe/var/www/skyplay_api_hub/venv/lib/python3.12/site-packages/transformers/models/rag/modeling_tf_rag.pyr   r   /   sÇ   … ñBðH "€DÐ
Ó!Ø"&€FÐÓ&Ø.2€OÐ+Ó2Ø#'€JÐ Ó'Ø-1ÐÐ*Ó1Ø*.ÐÐ'Ó.Ø*.ÐÐ'Ó.Ø/3ÐÐ,Ó3Ø;?Ð&Ð(8Ó?Ø?CÐÐ <ÓCØ<@ÐÐ9Ó@Ø8<Ð#Ð%5Ó<Ø@DÐÐ!=ÓDØ=AÐÐ:ÓAØ@DÐÐ!=ÓDØ=AÐÐ:ÔAr5   r   c                  óä   — e Zd ZU dZdZded<   dZded<   dZded<   dZded	<   dZ	ded
<   dZ
ded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   y)ÚTFRetrievAugLMOutputa«  
    Args:
        logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head. The score is possibly marginalized over all documents for
            each vocabulary token.
        past_key_values (`List[tf.Tensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            List of `tf.Tensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size, num_heads,
            sequence_length, embed_size_per_head)`).

            Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used
            (see `past_key_values` input) to speed up sequential decoding.
        doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
            Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
            `question_encoder_last_hidden_state`.
        retrieved_doc_embeds (`tf.Tensor` of shape `(batch_size, config.n_docs, hidden_size)`, *optional*, returned when *output_retrieved=True*):
            Embedded documents retrieved by the retriever. Is used with `question_encoder_last_hidden_state` to compute
            the `doc_scores`.
        retrieved_doc_ids (`tf.Tensor` of shape `(batch_size, config.n_docs)`, *optional*, returned when *output_retrieved=True*):
            The indexes of the embedded documents retrieved by the retriever.
        context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
            Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.
        context_attention_mask (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
            Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
            retriever.
        question_encoder_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden states at the output of the last layer of the question encoder pooled output of the
            model.
        question_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.
        question_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights of the question encoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
        generator_enc_last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the generator encoder of the model.
        generator_enc_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.
        generator_enc_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
        generator_dec_hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `tf.Tensor` (one for the output of the embeddings and one for the output of each layer) of shape
            `(batch_size, sequence_length, hidden_size)`.

            Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.
        generator_dec_attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted
            average in the self-attention heads.
    Nr   r   r   r    r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   )r/   r0   r1   r2   r   r3   r    r!   r"   r#   r$   r%   r&   r(   r)   r*   r+   r,   r-   r.   r4   r5   r6   r8   r8   ‡   s»   … ñ>ð@ #'€FÐÓ&Ø.2€OÐ+Ó2Ø#'€JÐ Ó'Ø-1ÐÐ*Ó1Ø*.ÐÐ'Ó.Ø*.ÐÐ'Ó.Ø/3ÐÐ,Ó3Ø;?Ð&Ð(8Ó?Ø?CÐÐ <ÓCØ<@ÐÐ9Ó@Ø8<Ð#Ð%5Ó<Ø@DÐÐ!=ÓDØ=AÐÐ:ÓAØ@DÐÐ!=ÓDØ=AÐÐ:ÔAr5   r8   c                  óF   — e Zd ZdZeZdZdgZe	 	 	 d	 	 	 	 	 	 	 dd„«       Z	y)ÚTFRagPreTrainedModela²  
    RAG models were released with the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP
    Tasks](https://arxiv.org/abs/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandra Piktus et al.

    RAG is a retriever augmented model and encapsulate three components: a question encoder, a dataset retriever and a
    generator, the encoder and generator are trainable while the retriever is just an indexed dataset.

    ÚragÚposition_idsNc                ó®  — |j                  «       D ��ci c]%  \  }}|j                  d«      r|t        d«      d |“Œ' }}}|j                  «       D ��ci c]%  \  }}|j                  d«      r|t        d«      d |“Œ' }	}}|j                  «       D ]  }
|d|
z   = Œ
 |	j                  «       D ]  }
|d|
z   = Œ
 |j	                  dd«      }|€R|€J d«       ‚ddlm} d|vrdd	lm} |j                  |«      }||d<    |j                  |g|¢­d
| j                  dœ|¤Ž}|	j	                  dd«      }|€O|€J d«       ‚ddlm} d|	vrdd	lm} |j                  |«      }||	d<    |j                  |fd| j                  dœ|	¤Ž}|j                  dd«      }|€+t        j                  |j                  |j                  fi |¤Ž} | ||||¬«      S c c}}w c c}}w )a–  
        Instantiates an question encoder and a generator from one or two base classes of the library from pretrained
        model checkpoints.

        Params:
            question_encoder_pretrained_model_name_or_path (`str`, *optional*):
                Information necessary to initiate the question encoder. Can be either:

                    - A string with the *shortcut name* of a pretrained model to load from cache or download, e.g.,
                      `google-bert/bert-base-uncased`.
                    - A string with the *identifier name* of a pretrained model that was user-uploaded to our S3, e.g.,
                      `dbmdz/bert-base-german-cased`.
                    - A path to a *directory* containing model weights saved using
                      [`~TFPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
                    - A path or url to a *pytorch index checkpoint file* (e.g, `./pt_model/`). In this case,
                      `question_encoder_from_pt` should be set to `True`.

            generator_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`):
                Information necessary to initiate the generator. Can be either:

                    - A string with the *shortcut name* of a pretrained model to load from cache or download, e.g.,
                      `google-t5/t5-small`.
                    - A string with the *identifier name* of a pretrained model that was user-uploaded to our S3, e.g.,
                      `facebook/bart-base`.
                    - A path to a *directory* containing model weights saved using
                      [`~TFPreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`.
                    - A path or url to a *pytorch checkpoint file* (e.g, `./pt_model/`). In this case,
                      `generator_from_pt` should be set to `True`.

            model_args (remaining positional arguments, *optional*):
                All remaining positional arguments will be passed to the underlying model's `__init__` method.
            retriever ([`RagRetriever`], *optional*):
                The retriever to use.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to update the configuration object (after it being loaded) and initiate the model (e.g.,
                `output_attentions=True`).

                - To update the question_encoder configuration, use the prefix *question_encoder_* for each
                  configuration parameter.
                - To update the generator configuration, use the prefix *generator_* for each configuration parameter.
                - To update the parent model configuration, do not use a prefix for each configuration parameter.

                Behaves differently depending on whether a `config` is provided or automatically loaded.

        Example:

        ```python
        >>> from transformers import RagRetriever, TFRagModel

        >>> # initialize a RAG from two pretrained models.
        >>> model = TFRagModel.from_pretrained_question_encoder_generator(
        ...     "facebook/dpr-question_encoder-single-nq-base", "google-t5/t5-small"
        ... )
        >>> # alternatively, initialize from pytorch pretrained models can also be done
        >>> model = TFRagModel.from_pretrained_question_encoder_generator(
        ...     "facebook/dpr-question_encoder-single-nq-base",
        ...     "facebook/bart-base",
        ...     generator_from_pt=True,
        ...     question_encoder_from_pt=True,
        ... )

        >>> # saving model after fine-tuning
        >>> model.save_pretrained("./rag")

        >>> # load retriever
        >>> retriever = RagRetriever.from_pretrained(
        ...     "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
        ... )
        >>> # load fine-tuned model with retriever
        >>> model = TFRagModel.from_pretrained("./rag", retriever=retriever)
        ```Úquestion_encoder_NÚ
generator_ÚmodelznIf `model` is not defined as an argument, a `question_encoder_pretrained_model_name_or_path` has to be definedé   ©ÚTFAutoModelÚconfig)Ú
AutoConfigÚquestion_encoder©ÚnameÚload_weight_prefixÚ	generatorzqIf `generator_model` is not defined as an argument, a `generator_pretrained_model_name_or_path` has to be defined©ÚTFAutoModelForSeq2SeqLM)rF   rJ   rD   Ú	retriever)ÚitemsÚ
startswithÚlenÚkeysÚpopÚauto.modeling_tf_autorC   Úauto.configuration_autorE   Úfrom_pretrainedrI   rL   Úgetr   Ú'from_question_encoder_generator_configsrD   )ÚclsÚ.question_encoder_pretrained_model_name_or_pathÚ'generator_pretrained_model_name_or_pathrM   Ú
model_argsÚkwargsÚargumentÚvalueÚkwargs_question_encoderÚkwargs_generatorÚkeyrF   rC   rE   Úquestion_encoder_configrJ   rL   Úgenerator_configrD   s                      r6   Ú*from_pretrained_question_encoder_generatorz?TFRagPreTrainedModel.from_pretrained_question_encoder_generatorè   su  € ðf $*§<¡<£>÷#
á�˜%Ø×"Ñ"Ð#6Ô7ð ”SÐ,Ó-Ð/Ð0°%Ñ7ð#
Ðñ #
ð $*§<¡<£>÷
á�˜%Ø×"Ñ" <Ô0ð ”S˜Ó&Ð(Ð)¨5Ñ0ð
Ðñ 
ð +×/Ñ/Ó1ò 	2ˆCØÐ*¨SÑ0Ñ1ð	2à#×(Ñ(Ó*ò 	+ˆCØ�| cÑ)Ñ*ð	+ð 3×6Ñ6°wÀÓEÐØÐ#ØAÐMð ðóÐMõ
 <àÐ6Ñ6Ý@à*4×*DÑ*DÐEsÓ*tÐ'Ø4KÐ'¨Ñ1à:˜{×:Ñ:Ø>ð ð ñ	 à'Ø#&×#9Ñ#9ñ ð
 *ñ Ðð %×(Ñ(¨°dÓ;ˆ	ØÐØ:ÐFð ð!óÐFõ
 HàÐ/Ñ/Ý@à#-×#=Ñ#=Ð>eÓ#fÐ Ø-=Ð  Ñ*à?Ð/×?Ñ?Ø7ðà Ø#&×#9Ñ#9ñð #ñ	ˆIð —‘˜H dÓ+ˆØˆ>Ü×FÑFØ ×'Ñ'¨×)9Ñ)9ñØ=CñˆFñ Ð$4À	ÐRXÐdmÔnÐnùóS#
ùó
s   ”*GÁ*G)NNN)rY   úOptional[str]rZ   re   rM   r   Úreturnr   )
r/   r0   r1   r2   r   Úconfig_classÚbase_model_prefixÚ_keys_to_ignore_on_load_missingÚclassmethodrd   r4   r5   r6   r:   r:   Ú   sn   „ ñð €LØÐØ'6Ð&7Ð#àð IMØAEØ"&ð	Yoà8EðYoð 2?ðYoð  ð	Yoð 
òYoó ñYor5   r:   aˆ	  

    RAG is a sequence-to-sequence model which encapsulates two core components: a question encoder and a generator.
    During a forward pass, we encode the input with the question encoder and pass it to the retriever to extract
    relevant context documents. The documents are then prepended to the input. Such contextualized inputs is passed to
    the generator.

    The question encoder can be any *autoencoding* model, preferably [`TFDPRQuestionEncoder`], and the generator can be
    any *seq2seq* model, preferably [`TFBartForConditionalGeneration`].

    The model can be initialized with a [`RagRetriever`] for end-to-end generation or used in combination with the
    outputs of a retriever in multiple steps---see examples for more details. The model is compatible any
    *autoencoding* model as the `question_encoder` and any *seq2seq* model with language model head as the `generator`.
    It has been tested with [`TFDPRQuestionEncoder`] as the `question_encoder` and [`TFBartForConditionalGeneration`]
    as the `generator`.

    This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a Tensorflow [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
    subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
    general usage and behavior.

    The model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in
    SavedModel format.

    Args:
        config ([`RagConfig`]):
            Model configuration class with all the parameters of the model. Initializing with a config file does not
            load the weights associated with the model, only the configuration. Check out the
            [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
        question_encoder ([`TFPreTrainedModel`]):
            An encoder model compatible with the faiss index encapsulated by the `retriever`.
        generator ([`TFPreTrainedModel`]):
            A seq2seq model used as the generator in the RAG architecture.
        retriever ([`RagRetriever`]):
            A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
a†  
    Args:
        input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. [`RagConfig`], used to initialize the model, specifies
            which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to
            obtain the indices.
        attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        encoder_outputs (`tuple(tuple(tf.Tensor)`, *optional*)
            Tuple consists of (`generator_enc_last_hidden_state`, *optional*: `generator_enc_hidden_states`,
            *optional*: `generator_enc_attentions`). `generator_enc_last_hidden_state` of shape `(batch_size, n_docs *
            sequence_length, hidden_size)` is a sequence of hidden-states at the output of the last layer of the
            generator's encoder.

            Used by the ([`TFRagModel`]) model during decoding.
        decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
            Provide for generation tasks. `None` by default, construct as per instructions for the generator model
            you're using with your RAG instance.
        decoder_attention_mask (`torch.BoolTensor` 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.
        past_key_values (`tuple(tuple(tf.Tensor))`):
            Tuple consists of two elements: `encoder_outputs` of the RAG model (see `encoder_outputs`) and
            `past_key_values` of the underlying generator. Can be used to speed up decoding. `past_key_values` are used
            in the ([`RagTokenForGeneration`]) model during decoding.
        doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
            Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
            `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` `doc_scores`
            has to be provided to the forward pass. `doc_scores` can be computed via
            `question_encoder_last_hidden_state` and `retrieved_doc_embeds`, see examples for more information.
        context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
            Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
            retriever.

            If the model has is not initialized with a `retriever` ``context_input_ids` has to be provided to the
            forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`]. context_attention_mask
            (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when
            *output_retrieved=True*): Attention mask post-processed from the retrieved documents and the question
            encoder `input_ids` by the retriever.

            If the model has is not initialized with a `retriever` `context_attention_mask` has to be provided to the
            forward pass. `context_attention_mask` are returned by [`~RagRetriever.__call__`].
        use_cache (`bool`, *optional*, defaults to `True`):
            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
            `past_key_values`).
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        output_retrieved(`bool`, *optional*):
            Whether or not to return the `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
            `context_attention_mask`. See returned tensors for more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`TFRetrievAugLMOutput`] instead of a plain tuple.
        n_docs (`int`, *optional*, defaults to `config.n_docs``)
            Number of documents to retrieve and/or number of documents for which to generate an answer.
c                  óø   ‡ — e Zd ZdZ	 	 	 	 	 d	 	 	 	 	 	 	 	 	 dˆ fd„Zd	d„Ze ee«       e	e
e¬«      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Zdd„Zˆ xZS )Ú
TFRagModelÚtf_rag_model_1c                ó^  •— |€|�|€J d«       ‚|€,t        j                  |j                  |j                  fi |¤Ž}n-t        || j                  «      sJ d|› d| j                  › �«       ‚t        ‰	| �  |fi |¤Ž |€#ddlm} |j                  |j                  d¬«      }|€7ddlm} |�|n| j                  }|j                  |j                  d	|d
z   ¬«      }|| _        | j                  �5t        |t        «      sJ dt!        | j                  «      › d�«       ‚|| _        || _
        || _        y )NzQEither a configuration or an question_encoder and a generator has to be provided.zconfig: z has to be of type rA   rB   rF   )rH   rK   rJ   z
/generatorrG   z`self.retriever` is of type z&, but should be of type `RagRetriever`)r   rW   rD   Ú
isinstancerg   ÚsuperÚ__init__rS   rC   Úfrom_configrF   rL   rI   rJ   rM   r   Útype)
ÚselfrD   rF   rJ   rM   rI   r\   rC   rL   Ú	__class__s
            €r6   rq   zTFRagModel.__init__ô  sa  ø€ ð Ð!Ð&6Ð&BÀyÐG\ð 	
Ø_ó	
Ð]ð ˆ>Ü×FÑFØ ×'Ñ'¨×)9Ñ)9ñØ=Cñ‰Fô ˜f d×&7Ñ&7Ô8Ðs¸HÀVÀHÐL_Ð`d×`qÑ`qÐ_rÐ:sÓsÐ8Ü‰Ñ˜Ñ* 6Ò*àÐ#Ý;à*×6Ñ6°v×7NÑ7NÐUgÐ6ÓhÐàÐÝGà7IÐ7UÑ!3Ð[_×[rÑ[rÐØ/×;Ñ;Ø× Ñ  {ÐGYÐ\hÑGhð <ó ˆIð #ˆŒØ�>‰>Ð%Ü˜i¬Ô6ð Ø.¬t°D·N±NÓ/CÐ.DÐDjÐkóÐ6ð 'ˆDŒNà 0ˆÔØ"ˆ�r5   c                ó   — || _         y ©N)rM   ©rt   rM   s     r6   Úset_retrieverzTFRagModel.set_retriever   s	   € Ø"ˆ�r5   ©Úoutput_typerg   c                ó–  — d|vsJ d«       ‚|�|n| j                   j                  }| j                  duxr |du xs
 |	du xs |du xr |du }|�€d|�rF| j                  ||d|¬«      }|d   }| j                  ||j	                  «       | j
                  j                   j                  |d¬«      }|d	   |d
   |d   |d   f\  }}	}}t        j                  |t        j                  «      }t        j                  |	t        j                  «      }	t        j                  |t        j                  «      }t        j                  |t        j                  «      }t        j                  t        j                  t        j                  |d¬«      |d¬«      d¬«      }n|€J d«       ‚|	€J d«       ‚|€J d«       ‚|€J d«       ‚|j                  d   |z  dk(  sJ d|› d|j                  d   › d�«       ‚|�t        j                  ||d¬«      }|�t        j                  ||d¬«      }| j                  ||	|||||
d|¬«	      }|sd}d}d}d}d}nj                   }|j"                  }|r|sd}d}	d}d}t%        |j&                  ||j(                  ||	|||j*                  |j,                  |j.                  |j0                  |j2                  ¬«      S )aa  
        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, RagRetriever, TFRagModel
        >>> import torch

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-base")
        >>> retriever = RagRetriever.from_pretrained(
        ...     "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
        ... )
        >>> # initialize with RagRetriever to do everything in one forward call
        >>> model = TFRagModel.from_pretrained("facebook/rag-token-base", retriever=retriever, from_pt=True)

        >>> input_dict = tokenizer.prepare_seq2seq_batch(
        ...     "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
        ... )
        >>> input_ids = input_dict["input_ids"]
        >>> outputs = model(input_ids)
        ```Údecoder_cached_statesú8Please use past_key_values to cache intermediate outputsNT)Úattention_maskÚreturn_dictÚtrainingr   Útf©ÚprefixÚn_docsÚreturn_tensorsr$   r%   r"   Údoc_idsr   ©Úaxis©Útranspose_bz˜Make sure that `context_input_ids` are passed, if no `retriever` is set. Alternatively, you can set a retriever using the `set_retriever(...)` function.z�Make sure that `context_attention_mask` are passed, if no `retriever` is set. Alternatively, you can set a retriever using the `set_retriever(...)` function.z‘Make sure that `doc_scores` are passed, if no `retriever` is set. Alternatively, you can set a retriever using the `set_retriever(...)` function.z^Make sure that `doc_scores` are passed when passing `encoder_outputs` to the forward function.úM The first dimension of `context_input_ids` should be a multiple of `n_docs`=ú	, but is ú.)r   Úencoder_outputsÚdecoder_input_idsÚdecoder_attention_maskr    Ú	use_cacher€   r�   rw   )r   r!   r    r$   r%   r"   r#   r&   r(   r)   r*   r+   r,   r-   r.   )rD   r…   rM   rF   ÚnumpyrJ   r„   r‚   ÚcastÚint32Úfloat32ÚsqueezeÚmatmulÚexpand_dimsÚshapeÚrepeatÚhidden_statesÚ
attentionsr8   r   r    Úencoder_last_hidden_stateÚencoder_hidden_statesÚencoder_attentionsÚdecoder_hidden_statesÚdecoder_attentions)rt   Ú	input_idsr   r�   r�   r‘   r    r!   r$   r%   r’   Úoutput_attentionsÚoutput_hidden_statesÚoutput_retrievedr…   r€   r�   r\   Úhas_to_retrieveÚquestion_enc_outputsr&   Úretriever_outputsr"   r#   Úgen_outputsr(   r)   s                              r6   ÚcallzTFRagModel.call#  s—  € ðZ '¨fÑ4ð 	
ØFó	
Ð4ð
 "Ð-‘°4·;±;×3EÑ3Eˆð �N‰N $Ð&ò (Ø" dÐ*ÒbÐ.DÈÐ.LÒbÐPZÐ^bÐPbò(à 4Ð'ð 	ð Ñ"ÚØ'+×'<Ñ'<Ø¨nÈ$ÐYað (=ó (Ð$ð 6JØñ6Ð2ð %)§N¡NØØ6×<Ñ<Ó>ØŸ>™>×0Ñ0×7Ñ7Ø!Ø#'ð %3ó %Ð!ð &Ð&9Ñ:Ø%Ð&>Ñ?Ø%Ð&<Ñ=Ø% iÑ0ð	fÑbÐ!Ð#9Ð;OÐQbô %'§G¡GÐ,=¼r¿x¹xÓ$HÐ!Ü)+¯©Ð1GÌÏÉÓ)RÐ&Ü')§w¡wÐ/CÄRÇZÁZÓ'PÐ$Ü$&§G¡GÐ,=¼r¿x¹xÓ$HÐ!ô  ŸZ™ZÜ—I‘IÜŸ™Ð'IÐPQÔRØ,Ø$(ôð
 ô‘
ð )Ð4ð ðPóÐ4ð .Ð9ð ðTóÐ9ð "Ð-ð ðJóÐ-ð
 Ð%ð 	
Øló	
Ð%ð × Ñ  Ñ# fÑ,°Ò2ð 	
Ø[Ð\bÐ[cð dØ!×'Ñ'¨Ñ*Ð+¨1ð.ó	
Ð2ð Ð(Ü "§	¡	Ð*;¸VÈ!Ô LÐà!Ð-Ü%'§Y¡YÐ/EÀvÐTUÔ%VÐ"à—n‘nØØ1Ø+Ø/Ø#9Ø+ØØØð %ó 

ˆñ Ø15Ð.Ø)-Ð&Ø&*Ð#Ø#'Ð Ø $Ñà)=×)KÑ)KÐ&Ø&:×&EÑ&EÐ#áÑ&6à 'ÐØ%)Ð"Ø#'Ð Ø $Ðä#Ø×%Ñ%Ø!Ø'×7Ñ7Ø/Ø#9Ø!5Ø/Ø/QØ'AØ$;Ø,7×,QÑ,QØ(3×(IÑ(IØ%0×%CÑ%CØ(3×(IÑ(IØ%0×%CÑ%Cô
ð 	
r5   c                ó�  — | j                   ry d| _         t        j                  | j                  j                  «      5  | j                  j                  d «       d d d «       t        j                  | j                  j                  «      5  | j                  j                  d «       d d d «       y # 1 sw Y   ŒWxY w# 1 sw Y   y xY w)NT)Úbuiltr‚   Ú
name_scoperJ   rH   ÚbuildrF   ©rt   Úinput_shapes     r6   r¯   zTFRagModel.buildÓ  s–   € Ø�:Š:ØØˆŒ
Ü�]‰]˜4Ÿ>™>×.Ñ.Ó/ñ 	'Ø�N‰N× Ñ  Ô&÷	'ä�]‰]˜4×0Ñ0×5Ñ5Ó6ñ 	.Ø×!Ñ!×'Ñ'¨Ô-÷	.ð 	.÷	'ð 	'ú÷	.ð 	.ús   ¾B0ÂB<Â0B9Â<C)NNNNN)
rD   úOptional[PretrainedConfig]rF   úOptional[TFPreTrainedModel]rJ   r³   rM   úOptional[RagRetriever]rI   re   ©rM   r   )NNNNNNNNNNNNNNNF)"r£   úTFModelInputType | Noner   únp.ndarray | tf.Tensor | Noner�   r·   r�   r·   r‘   r·   r    ú1Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | Noner!   r·   r$   r·   r%   r·   r’   úbool | Noner¤   r¹   r¥   r¹   r¦   r¹   r…   ú
int | Noner€   r¹   r�   Úboolrf   r8   rw   )r/   r0   r1   rI   rq   ry   r   r   ÚRAG_FORWARD_INPUTS_DOCSTRINGr   r8   Ú_CONFIG_FOR_DOCr«   r¯   Ú__classcell__©ru   s   @r6   rl   rl   ð  s}  ø„ à)Ðð .2Ø8<Ø15Ø,0Ø,0ð*#à*ð*#ð 6ð*#ð /ð	*#ð
 *ð*#ð *õ*#óX#ð Ù*Ð+GÓHÙÐ+?ÈoÔ^ð .2Ø8<Ø9=Ø;?Ø@DØMQØ48Ø;?Ø@DØ!%Ø)-Ø,0Ø(,Ø!Ø#'Øð#k
à*ðk
ð 6ðk
ð 7ð	k
ð
 9ðk
ð !>ðk
ð Kðk
ð 2ðk
ð 9ðk
ð !>ðk
ð ðk
ð 'ðk
ð *ðk
ð &ðk
ð ðk
ð  !ð!k
ð" ð#k
ð& 
ò'k
ó _ó Ió ðk
÷Z.r5   rl   zr
    A TF RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass.
    c            	      ó°  ‡ — e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 dˆ fd„Zdd„Z	 	 	 	 	 	 dd„Zed„ «       Zed„ «       Z	ed„ «       Z
edd	„«       Zdd
„Ze ee«       eee¬«      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Zddddddd e«       f	 	 	 dd„Zd„ Zd„ Zdd„Zdd„Zdd„Zdd„Zˆ xZS )ÚTFRagTokenForGenerationz!tf_rag_token_for_generation_1/ragNc                óØ   •— |€|�|€J d«       ‚|€+t        j                  |j                  |j                  fi |¤Ž}t        ‰| �  |«       t        ||||| j                  d¬«      | _        y ©NzHEither a configuration or an encoder and a generator has to be provided.r;   )rD   rF   rJ   rM   rI   rH   ©r   rW   rD   rp   rq   rl   rI   r;   ©rt   rD   rF   rJ   rM   r\   ru   s         €r6   rq   z TFRagTokenForGeneration.__init__æ  ó‹   ø€ ð Ð!Ð&6Ð&BÀyÐG\ð 	
ØVó	
Ð]ð ˆ>Ü×FÑFØ ×'Ñ'¨×)9Ñ)9ñØ=CñˆFô 	‰Ñ˜Ô ô ØØ-ØØØ#×6Ñ6Øô
ˆ�r5   c                ó&   — || j                   _        y rw   ©r;   rM   rx   s     r6   ry   z%TFRagTokenForGeneration.set_retriever  ó   € Ø&ˆ�‰Õr5   c           
     ó4   — |�|d d …dd …f   }d ||||||d|dœ	S )NéÿÿÿÿT)	r£   r�   r!   r%   r�   r    r’   Údo_marginalizer…   r4   )	rt   r�   r    r   r’   r�   r!   r…   r\   s	            r6   Úprepare_inputs_for_generationz5TFRagTokenForGeneration.prepare_inputs_for_generation  sB   € ð Ð&à 1²!°R±S°&Ñ 9Ðð Ø.Ø$Ø&4Ø!2Ø.Ø"Ø"Øñ

ð 
	
r5   c                ó.   — | j                   j                  S rw   rÈ   ©rt   s    r6   rM   z!TFRagTokenForGeneration.retriever"  ó   € à�x‰x×!Ñ!Ð!r5   c                ó.   — | j                   j                  S rw   ©r;   rJ   rÏ   s    r6   rJ   z!TFRagTokenForGeneration.generator&  rÐ   r5   c                ó.   — | j                   j                  S rw   ©r;   rF   rÏ   s    r6   rF   z(TFRagTokenForGeneration.question_encoder*  ó   € à�x‰x×(Ñ(Ð(r5   c                óN   ‡— ˆfd„}t         j                  j                  || «      S )a,  
        RAG-specific `_gather_beams`: gathers the beam slices indexed by beam_indices into new beam array. If the
        nested tensor has a shape mismatch with the beam indices, then it means it is the cache. In that case, isolates
        and takes care of the extra dimension for ndocs.
        c                ó„  •— | j                   d   ‰j                   d   k7  }|rW| j                   d   ‰j                   d   z  }‰j                   d   }t        j                  | |d|g| j                   dd  ¢­«      } t        j                  | ‰dd¬«      }|r+t        j                  |z  dg|j                   dd  ¢­«      }|S )Nr   rË   rA   r   )ÚparamsÚindicesr‰   Ú
batch_dimsr	   )rš   r‚   ÚreshapeÚgather)ÚtensorÚis_rag_cacher…   Ú
batch_sizeÚgathered_tensorÚbeam_indicess        €r6   Ú	gather_fnz8TFRagTokenForGeneration._gather_beams.<locals>.gather_fn6  sÈ   ø€ Ø!Ÿ<™<¨™?¨l×.@Ñ.@ÀÑ.CÑCˆLÙØŸ™ a™¨L×,>Ñ,>¸qÑ,AÑA�Ø)×/Ñ/°Ñ2�
äŸ™ F¨Z¸¸VÐ,WÀfÇlÁlÐSTÐSUÐFVÑ,WÓX�ä Ÿi™i¨v¸|ÐRSÐ`aÔbˆOáä"$§*¡*¨_¸zÈFÑ?RÐTVÐ>sÐYh×YnÑYnÐopÐoqÐYrÑ>sÓ"t�à"Ð"r5   )r‚   ÚnestÚmap_structure)Únestedrá   Ú
batch_axisrâ   s    `  r6   Ú_gather_beamsz%TFRagTokenForGeneration._gather_beams.  s!   ø€ ô	#ô  �w‰w×$Ñ$ Y°Ó7Ð7r5   c                ó¼  — |�|n| j                   j                  }t        j                  j	                  |d¬«      }t        j
                  ||j                  d   |z  |d|j                  d   g«      }t        j                  j	                  |d¬«      }t        j                  |d¬«      }t        j                  |d¬«      }||z   }t        j                  |d¬«      S )NrË   rˆ   r   r   )	rD   r…   r‚   ÚnnÚlog_softmaxrÛ   rš   r™   Úreduce_logsumexp)rt   Ú
seq_logitsr!   r…   Úseq_logprobsÚdoc_logprobsÚlog_prob_sums          r6   Úmarginalizez#TFRagTokenForGeneration.marginalizeH  sÁ   € Ø!Ð-‘°4·;±;×3EÑ3Eˆô —u‘u×(Ñ(¨¸"Ð(Ó=ˆÜ—z‘z ,°×1AÑ1AÀ!Ñ1DÈÑ1NÐPVÐXZÐ\f×\lÑ\lÐmoÑ\pÐ0qÓrˆÜ—u‘u×(Ñ(¨¸!Ð(Ó<ˆÜ—~‘~ l¸Ô<ˆÜ—~‘~ l¸Ô<ˆØ# lÑ2ˆÜ×"Ñ" <°aÔ8Ð8r5   rz   c                ó>  — d|vsJ d«       ‚|r|n| j                   j                  }|r|n| j                   j                  }|�|€|}d}
| j                  |||||||	|||
|||||¬«      }d}|j                  }|�C|€J ‚| j                  |j                  |j                  ||| j                   j                  |¬«      }|r| j                  ||j                  |«      }t        di d|“d|“d	|j                  “d
|j                  “d|j                  “d|j                  “d|j                  “d|j                  “d|j                  “d|j                   “d|j"                  “d|j$                  “d|j&                  “d|j(                  “d|j*                  “d|j,                  “ŽS )aâ  
        do_marginalize (`bool`, *optional*):
            If `True`, the logits are marginalized over all documents by making use of
            `torch.nn.functional.log_softmax`.
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the cross entropy classification loss according to Rag-Token model formulation See
            https://arxiv.org/pdf/2005.11401.pdf Section 2.1 for details about Rag-Token formulation. Indices should be
            in `[0, ..., config.vocab_size - 1]`.
        reduce_loss (`bool`, *optional*):
            Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `tf.Tensor.sum`
            operation.
        kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
            Legacy dictionary, which is required so that model can use *generate()* function.

        Returns:

        Example:

        ```python
        >>> import tensorflow as tf
        >>> from transformers import AutoTokenizer, RagRetriever, TFRagTokenForGeneration

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-nq")
        >>> retriever = RagRetriever.from_pretrained(
        ...     "facebook/rag-token-nq", index_name="exact", use_dummy_dataset=True
        ... )
        >>> # initialize with RagRetriever to do everything in one forward call
        >>> model = TFRagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever, from_pt=True)

        >>> input_dict = tokenizer.prepare_seq2seq_batch(
        ...     "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
        ... )
        >>> outputs = model(input_dict, output_retrieved=True)

        >>> # or use retriever separately
        >>> # 1. Encode
        >>> input_ids = input_dict["input_ids"]
        >>> question_hidden_states = model.question_encoder(input_ids)[0]
        >>> # 2. Retrieve
        >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
        >>> doc_scores = tf.squeeze(
        ...     tf.matmul(
        ...         tf.expand_dims(question_hidden_states, axis=1), docs_dict["retrieved_doc_embeds"], transpose_b=True
        ...     ),
        ...     axis=1,
        ... )
        >>> # 3. Forward to generator
        >>> outputs = model(
        ...     inputs=None,
        ...     context_input_ids=docs_dict["context_input_ids"],
        ...     context_attention_mask=docs_dict["context_attention_mask"],
        ...     doc_scores=doc_scores,
        ...     decoder_input_ids=input_dict["labels"],
        ... )

        >>> # or directly generate
        >>> generated = model.generate(
        ...     context_input_ids=docs_dict["context_input_ids"],
        ...     context_attention_mask=docs_dict["context_attention_mask"],
        ...     doc_scores=doc_scores,
        ... )
        >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)
        ```r}   r~   NF©r   r�   r�   r‘   r$   r%   r!   r    r’   r¤   r¥   r¦   r…   r�   ©Úreduce_lossÚepsilonr…   r   r   r    r!   r$   r%   r"   r#   r&   r(   r)   r*   r+   r,   r-   r.   r4   )rD   rÌ   rô   r;   r   Úget_nllr!   Úlabel_smoothingrð   r   r    r$   r%   r"   r#   r&   r(   r)   r*   r+   r,   r-   r.   )rt   r£   r   r�   r‘   r�   r    r!   r$   r%   r’   r¤   r¥   r¦   r…   rÌ   Úlabelsrô   r€   r�   r\   Úoutputsr   r   s                           r6   r«   zTFRagTokenForGeneration.callT  s  € ðt '¨fÑ4ð 	
ØFó	
Ð4ñ ,:™¸t¿{¹{×?YÑ?YˆÙ%0‘k°d·k±k×6MÑ6MˆàÐØ Ð(Ø$*Ð!ØˆIà—(‘(ØØ)Ø+Ø/Ø#9Ø/Ø#9Ø!Ø+ØØ/Ø!5Ø-ØØð ó 
ˆð$ ˆØ—‘ˆØÐØ$Ð0Ð0Ð0Ø—<‘<Ø—‘Ø×"Ñ"ØØ'ØŸ™×3Ñ3Øð  ó ˆDñ Ø×%Ñ% f¨g×.@Ñ.@À&ÓIˆFä)ò 
Ùð
áð
ð $×3Ò3ð
ð ×)Ò)ð	
ð
 &×7Ò7ð
ð $+×#AÒ#Að
ð ")×!=Ò!=ð
ð &×7Ò7ð
ð 07×/YÒ/Yð
ð (/×'IÒ'Ið
ð %,×$CÒ$Cð
ð -4×,SÒ,Sð
ð )0×(KÒ(Kð
ð &-×%EÒ%Eð
ð )0×(KÒ(Kð
ð  &-×%EÒ%Eð!
ð 	
r5   c	                óÜ  ‡‡‡— ‰€| j                   Št        j                  ‰«      Š ‰j                  di |	¤Ž}
‰�‰n| j                  j
                  Š| j                  ��7|�€4| j                  ||¬«      d   }| j                  ||j                  «       j                  t        j                  «      | j                  j                  j                  ‰d¬«      }|d   |d   |d   }}}t        j                  |t        j                   «      }t        j                  |t        j                   «      }t        j                  |t        j                  «      }t        j"                  t        j$                  |d¬	«      |d
¬«      }t        j&                  |d¬	«      }|j(                  d   ‰z  dk(  sJ d‰› d|j(                  d   › d�«       ‚|j(                  d   ‰z  Š| j*                  j                  j-                  «       } |||‰j.                  ‰j0                  d
¬«      }t        j2                  ‰‰j4                  z  dft        j                  ‰j6                  t        j                   «      «      }|d   }d ˆˆfd„	} ||‰j4                  ¬«      } ||‰j4                  ¬«      |d<   t        j8                  |‰j4                  d¬	«      }||
d<   ||
d<   ||
d<   ‰|
d<   | j;                  ‰t        j(                  |«      d   |¬«      }‰j4                  dk(  rb | j<                  d|‰j>                  ‰j@                  ‰jB                  |‰j.                  ‰j0                  ‰jD                  ‰jF                  dœ	|
¤ŽS ‰j4                  dkD  rÐ‰j4                  ‰jH                  k  r&tK        d‰j4                  › d‰jH                  › d�«      ‚ˆfd„} ||«      } ||
d   «      |
d<    ||
d   d   «      |
d   d<    | jL                  d|‰j>                  ‰j@                  ‰jB                  |‰j.                  ‰j0                  ‰jD                  ‰jF                  dœ	|
¤ŽS tK        d‰j4                  › �«      ‚)!a|  
        Implements TFRAG token decoding.

        Args:
            input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                The sequence used as a prompt for the generation. If `input_ids` is not passed, then
                `context_input_ids` has to be provided.
            attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
                Input IDs post-processed from the retrieved documents and the question encoder `input_ids` by the
                retriever.

                If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
                forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
            context_attention_mask (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
                Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
                retriever.

                If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
                forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
            doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
                Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
                `question_encoder_last_hidden_state`.

                If the model has is not initialized with a `retriever`, `context_input_ids` has to be provided to the
                forward pass. `context_input_ids` are returned by [`~RagRetriever.__call__`].
            n_docs (`int`, *optional*, defaults to `config.n_docs`)
                Number of documents to retrieve and/or number of documents for which to generate an answer.
            generation_config (`~generation.GenerationConfig`, *optional*):
                The generation configuration to be used as base parametrization for the generation call. `**kwargs`
                passed to generate matching the attributes of `generation_config` will override them. If
                `generation_config` is not provided, the default will be used, which had the following loading
                priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
                configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
                default values, whose documentation should be checked to parameterize generation.
            logits_processor (`TFLogitsProcessorList`, *optional*):
                Custom logits processors that complement the default logits processors built from arguments and a
                model's config. If a logit processor is passed that is already created with the arguments or a model's
                config an error is thrown.
            kwargs (`Dict[str, Any]`, *optional*):
                Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
                forwarded to the `forward` function of the model.

        Return:
            `tf.Tensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated sequences. The
            second dimension (sequence_length) is either equal to `max_length` or shorter if all batches finished early
            due to the `eos_token_id`.
        ©r   r   r‚   rƒ   r$   r%   r"   r   rˆ   TrŠ   rŒ   r�   rŽ   )r£   r   r¤   r¥   r€   Úlast_hidden_statec                óÞ   •— | j                   dd }‰d‰f|z   }t        j                  | |«      } ‰|‰f|z   }t        j                  | |«      } ‰|z  ‰z  f|z   }t        j                  | |«      S )zÌ
            Broadcast tensor with `num_beams` replica, with correct order Input: tensor of shape (batch_size*n_docs ,
            d) Output: tensor of shape (batch_size*num_beams*n_docs , d)
            r   N)rš   r‚   rÛ   Úbroadcast_to)rÝ   Ú	num_beamsÚd_shape_listÚ	new_shaperß   r…   s       €€r6   Úextend_enc_outputz;TFRagTokenForGeneration.generate.<locals>.extend_enc_outputj  s…   ø€ ð "Ÿ<™<¨¨Ð+ˆLð $ Q¨Ð/°,Ñ>ˆIÜ—Z‘Z ¨	Ó2ˆFð $ Y°Ð7¸,ÑFˆIÜ—_‘_ V¨YÓ7ˆFð $ iÑ/°&Ñ8Ð:¸\ÑIˆIÜ—:‘:˜f iÓ0Ð0r5   )rÿ   r!   r�   r   r…   rË   )Úgeneration_configÚinput_ids_seq_lengthÚlogits_processor)	r£   Ú
max_lengthÚpad_token_idÚeos_token_idr  r¤   r¥   Úoutput_scoresÚreturn_dict_in_generatezwBeam search decoding cannot return more sequences than it has beams. Please set num_beams >= num_return_sequences, got z and z (respectivelly)c                ój   •— t        | «      }t        j                  | d‰j                  g|dd z   «      S )zFUnflattens the first, flat batch*beam dimension of a non-scalar array.rË   r   N)r   r‚   rÛ   rÿ   )rÝ   rš   r  s     €r6   Úunflatten_beam_dimz<TFRagTokenForGeneration.generate.<locals>.unflatten_beam_dim¨  s7   ø€ ä" 6Ó*�Ü—z‘z &¨2Ð/@×/JÑ/JÐ*KÈeÐTUÐTVÈiÑ*WÓXÐXr5   uH   `num_beams` has to be an integer strictly superior to 0 (â‰¥ 1), but is r4   rw   )'r  ÚcopyÚdeepcopyÚupdaterD   r…   rM   rF   r“   ÚastypeÚnpr–   rJ   r„   r‚   r”   r•   r˜   r™   r—   rš   r;   Úget_encoderr¤   r¥   Úfillrÿ   Údecoder_start_token_idr›   Ú_get_logits_processorÚgreedy_searchr  r  r  r	  r
  Únum_return_sequencesÚ
ValueErrorÚbeam_search)rt   r£   r   r$   r%   r!   r…   r  r  r\   Úmodel_kwargsÚquestion_hidden_statesÚoutr"   Úencoderr�   r�   rü   r  Úpre_processorr  rß   s         ``             @r6   Úgeneratez TFRagTokenForGeneration.generateï  s¾  ú€ ðF Ð$Ø $× 6Ñ 6ÐÜ ŸM™MÐ*;Ó<ÐØ/Ð(×/Ñ/Ñ9°&Ñ9ˆð "Ð-‘°4·;±;×3EÑ3Eˆð �>‰>Ñ%Ð*;Ñ*CØ%)×%:Ñ%:¸9ÐUcÐ%:Ó%dÐefÑ%gÐ"Ø—.‘.ØØ&×,Ñ,Ó.×5Ñ5´b·j±jÓAØ—~‘~×,Ñ,×3Ñ3ØØ#ð !ó ˆCð Ð'Ñ(ØÐ,Ñ-ØÐ*Ñ+ð 8LÐ5Ðô !#§¡Ð(9¼2¿8¹8Ó DÐÜ%'§W¡WÐ-CÄRÇXÁXÓ%NÐ"Ü#%§7¡7Ð+?ÄÇÁÓ#LÐ ô Ÿ™Ü—‘Ð5¸AÔ>Ð@TÐbfôˆJô Ÿ™ J°QÔ7ˆJà!×'Ñ'¨Ñ*¨VÑ3¸Ò9ð 	
Ø[Ð\bÐ[cð dØ!×'Ñ'¨Ñ*Ð+¨1ð.ó	
Ð9ð
 '×,Ñ,¨QÑ/°6Ñ9ˆ
à—(‘(×$Ñ$×0Ñ0Ó2ˆÙ!Ø'Ø1Ø/×AÑAØ!2×!GÑ!GØô
ˆô ŸG™GØÐ+×5Ñ5Ñ5°qÐ9Ü�G‰GÐ%×<Ñ<¼b¿h¹hÓGó
Ðð ,Ð,?Ñ@Ðö	1ñ, "3Ð3IÐUf×UpÑUpÔ!qÐÙ/@ØÐ):×)DÑ)Dô0
ˆÐ+Ñ,ô —Y‘Y˜zÐ+<×+FÑ+FÈQÔOˆ
ð &0ˆ�\Ñ"Ø*9ˆÐ&Ñ'Ø)?ˆÐ%Ñ&Ø!'ˆ�XÑà×2Ñ2Ø/Ü!#§¡Ð*;Ó!<¸RÑ!@Ø-ð 3ó 
ˆð ×&Ñ&¨!Ò+Ø%�4×%Ñ%ð Ø+Ø,×7Ñ7Ø.×;Ñ;Ø.×;Ñ;Ø!.Ø"3×"EÑ"EØ%6×%KÑ%KØ/×=Ñ=Ø(9×(QÑ(Qñð ñð ð ×(Ñ(¨1Ò,Ø ×*Ñ*Ð->×-SÑ-SÒSÜ ð2Ø2C×2MÑ2MÐ1Nð OØ)×>Ñ>Ð?Ð?OðQóð ôYñ
 !3Ð3DÓ EÐÙ-?ÀÐM]Ñ@^Ó-_ˆLÐ)Ñ*ÙCUØÐ.Ñ/Ð0CÑDóDˆLÐ*Ñ+Ð,?Ñ@ð $�4×#Ñ#ð Ø+Ø,×7Ñ7Ø.×;Ñ;Ø.×;Ñ;Ø!.Ø"3×"EÑ"EØ%6×%KÑ%KØ/×=Ñ=Ø(9×(QÑ(Qñð ñð ô ØZÐ[l×[vÑ[vÐZwÐxóð r5   c                óJ   — | j                   j                  j                  «       S rw   )r;   rJ   Úget_input_embeddingsrÏ   s    r6   r!  z,TFRagTokenForGeneration.get_input_embeddingsÄ  s   € Ø�x‰x×!Ñ!×6Ñ6Ó8Ð8r5   c                óJ   — | j                   j                  j                  «       S rw   )r;   rJ   Úget_output_embeddingsrÏ   s    r6   r#  z-TFRagTokenForGeneration.get_output_embeddingsÇ  s   € Ø�x‰x×!Ñ!×7Ñ7Ó9Ð9r5   c           
     ó  — |€)| j                   j                  j                  }|€J d«       ‚| j                   j                  j                  }|€J d«       ‚t	        j
                  t        |«      d   dft	        j                  ||j                  «      «      }t	        j                  ||dd…dd…f   gd«      }t	        j                  |dk(  t	        j
                  t        |«      t	        j                  ||j                  «      «      |«      }t        j                  j                  |t	        j                  d|j                  «      «      }t	        j                  |g«      5  t	        j                  |«      }ddd«       |S # 1 sw Y   |S xY w)zCShift input ids one token to the right, and pad with start_token_idNzŒself.generator.config.decoder_start_token_id has to be defined. In Rag we commonly use Bart as generator, see Bart docs for more informationz1self.model.config.pad_token_id has to be defined.r   r   rË   iœÿÿÿ)rJ   rD   r  r  r‚   r  r   r”   ÚdtypeÚconcatÚwhereÚ	debuggingÚassert_greater_equalÚcontrol_dependenciesÚidentity)rt   r£   Ústart_token_idr  Ústart_tokensÚshifted_input_idsÚassert_gte0s          r6   Úshift_tokens_rightz*TFRagTokenForGeneration.shift_tokens_rightË  sb  € ð Ð!Ø!Ÿ^™^×2Ñ2×IÑIˆNØ!Ð-ð ðAóÐ-ð
 —~‘~×,Ñ,×9Ñ9ˆØÐ'Ð\Ð)\Ó\Ð'ä—w‘w¤
¨9Ó 5°aÑ 8¸!Ð<¼b¿g¹gÀnÐV_×VeÑVeÓ>fÓgˆÜŸI™I |°YºqÀ#À2À#¸vÑ5FÐ&GÈÓLÐô ŸH™HØ Ñ%Ü�G‰G”JÐ0Ó1´2·7±7¸<ÈÏÉÓ3YÓZØó
Ðô —l‘l×7Ñ7Ð8IÌ2Ï7É7ÐSTÐVg×VmÑVmÓKnÓoˆô ×$Ñ$ k ]Ó3ñ 	?Ü "§¡Ð,=Ó >Ð÷	?ð !Ð ÷	?ð !Ð ús   Å!FÆFc           
     óŒ  — |�|n| j                   j                  }t        j                  |d d …dd …f   t        j                  |j
                  d   dgt        j                  | j                   j                  j                  |j                  «      «      gd¬«      }| j                  |||«      }| j                  ||d|¬«      }|S )Nr   r   rˆ   T)Úfrom_logitsrô   )rD   r…   r‚   r&  r  rš   r”   rJ   r  r%  rð   Úhf_compute_loss)	rt   rì   r!   Útargetrô   rõ   r…   Úrag_logprobsr   s	            r6   rö   zTFRagTokenForGeneration.get_nllì  s¬   € Ø!Ð-‘°4·;±;×3EÑ3Eˆô —‘Ø’A�q‘r�E‰]œBŸG™G V§\¡\°!¡_°aÐ$8¼"¿'¹'À$Ç+Á+×BWÑBW×BdÑBdÐfl×frÑfrÓ:sÓtÐuØô
ˆð ×'Ñ'¨
°JÀÓGˆØ×#Ñ# F¨LÀdÐXcÐ#Ódˆàˆr5   c                óî  — t         j                  j                  dt         j                  j                  j                  ¬«      }|du r<d}t        j                  ||d|z
  ¬«      }t
        j                  j                  |«      }|}t        j                  |d«      }	t        j                  |	| j                  j                  j                  «      }
t        j                  t        j                  |d|j                  d	   f«      |
«      }t        j                  |	|
«      } |||«      }t        j                   |d¬
«       }t        j                   |«      }||j                  d   z  }d|z
  |z  ||z  z   }|S )z(CrossEntropyLoss that ignores pad tokensT)r2  Ú	reductionFg•Ö&è.>r   )Úclip_value_minÚclip_value_max)rË   rË   rA   rˆ   ç      ð?)r   ÚlossesÚSparseCategoricalCrossentropyÚ	ReductionÚSUMr‚   Úclip_by_valueÚmathÚlogrÛ   Ú	not_equalrD   rJ   r  Úboolean_maskrš   Ú
reduce_sum)rt   rø   Úy_predÚsmooth_epsilonr2  rô   Úloss_fnÚepsr   Úmelted_labelsÚactive_lossÚreduced_logitsÚnll_lossÚsmooth_lossÚeps_ir   s                   r6   r3  z'TFRagTokenForGeneration.hf_compute_lossú  s=  € ô —,‘,×<Ñ<ØÜ—l‘l×,Ñ,×0Ñ0ð =ó 
ˆð
 ˜%ÑØˆCÜ×%Ñ% f¸SÐQRÐUXÑQXÔYˆFÜ—W‘W—[‘[ Ó(ˆFàˆÜŸ
™
 6¨5Ó1ˆÜ—l‘l =°$·+±+×2GÑ2G×2TÑ2TÓUˆäŸ™¬¯©°F¸RÀÇÁÈaÁÐ<QÓ)RÐT_Ó`ˆÜ—‘ °Ó<ˆÙ˜6 >Ó2ˆä—}‘} ^¸"Ô=Ð=ˆÜ—m‘m KÓ0ˆØ ×!5Ñ!5°bÑ!9Ñ9ˆà�nÑ$¨Ñ0°5¸;Ñ3FÑFˆàˆr5   c                óú   — | j                   ry d| _         t        | dd «      �Nt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       y y # 1 sw Y   y xY w©NTr;   ©r­   Úgetattrr‚   r®   r;   rH   r¯   r°   s     r6   r¯   zTFRagTokenForGeneration.build  óe   € Ø�:Š:ØØˆŒ
Ü�4˜ Ó%Ð1Ü—‘˜tŸx™xŸ}™}Ó-ñ %Ø—‘—‘˜tÔ$÷%ð %ð 2÷%ð %úó   ÁA1Á1A:©NNNN©rD   r²   rF   r³   rJ   r³   rM   r´   rµ   )NNNNNN)r   rw   ©NNNNNNNNNNNNNNNNNNF)(r£   r¶   r   r·   r�   r·   r‘   r·   r�   r·   r    r¸   r!   r·   r$   r·   r%   r·   r’   r¹   r¤   r¹   r¥   r¹   r¦   r¹   r…   rº   rÌ   r¹   rø   r·   rô   r¹   r€   r¹   r�   r»   rf   r   ©r£   r¶   r   r   )Fç        N)rY  TF)r/   r0   r1   rI   rq   ry   rÍ   ÚpropertyrM   rJ   rF   Ústaticmethodrç   rð   r   r   r¼   r   r   r½   r«   r   r  r!  r#  r0  rö   r3  r¯   r¾   r¿   s   @r6   rÁ   rÁ   Ý  s\  ø„ ð =Ðð .2Ø8<Ø15Ø,0ð
à*ð
ð 6ð
ð /ð	
ð
 *õ
ó:'ð ØØØØØó
ð6 ñ"ó ð"ð ñ"ó ð"ð ñ)ó ð)ð ò8ó ð8ó2
9ð Ù*Ð+GÓHÙÐ+EÐTcÔdð .2Ø8<Ø;?Ø@DØ9=ØMQØ48Ø;?Ø@DØ!%Ø)-Ø,0Ø(,Ø!Ø&*Ø04Ø#'Ø#'Øð)V
à*ðV
ð 6ðV
ð 9ð	V
ð
 !>ðV
ð 7ðV
ð KðV
ð 2ðV
ð 9ðV
ð !>ðV
ð ðV
ð 'ðV
ð *ðV
ð &ðV
ð ðV
ð  $ð!V
ð" .ð#V
ð$ !ð%V
ð& !ð'V
ð( ð)V
ð, 
$ò-V
ó eó Ió ðV
ðt .2Ø+/ØØ#ØØØÙ.Ó0ðSà*ðSð )óSòj9ò:ó!óBó÷<%r5   rÁ   zx
    A TF RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.
    c                  óp  ‡ — e Zd ZdZ	 	 	 	 d	 	 	 	 	 	 	 dˆ fd„Zdd„Zed„ «       Zed„ «       Zed„ «       Z	e
 ee«       eee¬«      	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       «       «       Z	 dd	„Z	 	 	 	 	 	 	 	 	 d	 	 	 dd
„Zed„ «       Zdd„Zˆ xZS )ÚTFRagSequenceForGenerationz$tf_rag_sequence_for_generation_1/ragc                óØ   •— |€|�|€J d«       ‚|€+t        j                  |j                  |j                  fi |¤Ž}t        ‰| �  |«       t        ||||| j                  d¬«      | _        y rÃ   rÄ   rÅ   s         €r6   rq   z#TFRagSequenceForGeneration.__init__*  rÆ   r5   c                ó&   — || j                   _        y rw   rÈ   rx   s     r6   ry   z(TFRagSequenceForGeneration.set_retrieverG  rÉ   r5   c                ó.   — | j                   j                  S rw   rÈ   rÏ   s    r6   rM   z$TFRagSequenceForGeneration.retrieverJ  rÐ   r5   c                ó.   — | j                   j                  S rw   rÒ   rÏ   s    r6   rJ   z$TFRagSequenceForGeneration.generatorN  rÐ   r5   c                ó.   — | j                   j                  S rw   rÔ   rÏ   s    r6   rF   z+TFRagSequenceForGeneration.question_encoderR  rÕ   r5   rz   c                óô  — d|vsJ d«       ‚|r|n| j                   j                  }|r|n| j                   j                  }|�|€|}d}
| j                  |||||||	|||
|||||¬«      }d}|�?| j	                  |j
                  |j                  ||| j                   j                  |¬«      }t        di d|“d|j
                  “d	|j                  “d
|j                  “d|j                  “d|j                  “d|j                  “d|j                  “d|j                  “d|j                  “d|j                   “d|j"                  “d|j$                  “d|j&                  “d|j(                  “d|j*                  “ŽS )aù  
        exclude_bos_score (`bool`, *optional*):
            Only relevant if `labels` is passed. If `True`, the score of the BOS token is disregarded when computing
            the loss.
        labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the cross entropy classification loss according to Rag-Sequence model formulation See
            https://arxiv.org/pdf/2005.11401.pdf Section 2.1 for details about Rag-Sequence formulation. Indices should
            be in `[0, ..., config.vocab_size - 1]`.
        reduce_loss (`bool`, *optional*):
            Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `tf.Tensor.sum`
            operation.
        kwargs (`Dict[str, any]`, *optional*, defaults to `{}`):
            Legacy dictionary, which is required so that model can use *generate()* function.

        Returns:

        Example:

        ```python
        >>> from transformers import AutoTokenizer, RagRetriever, TFRagSequenceForGeneration

        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-sequence-nq")
        >>> retriever = RagRetriever.from_pretrained(
        ...     "facebook/rag-sequence-nq", index_name="exact", use_dummy_dataset=True
        ... )
        >>> # initialize with RagRetriever to do everything in one forward call
        >>> model = TFRagSequenceForGeneration.from_pretrained(
        ...     "facebook/rag-sequence-nq", retriever=retriever, from_pt=True
        ... )

        >>> input_dict = tokenizer.prepare_seq2seq_batch(
        ...     "How many people live in Paris?", "In Paris, there are 10 million people.", return_tensors="tf"
        ... )
        >>> outputs = model(input_dict, output_retrieved=True)

        >>> # or use retriever separately
        >>> # 1. Encode
        >>> input_ids = input_dict["input_ids"]
        >>> question_hidden_states = model.question_encoder(input_ids)[0]
        >>> # 2. Retrieve
        >>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.numpy(), return_tensors="tf")
        >>> doc_scores = tf.squeeze(
        ...     tf.matmul(
        ...         tf.expand_dims(question_hidden_states, axis=1), docs_dict["retrieved_doc_embeds"], transpose_b=True
        ...     ),
        ...     axis=1,
        ... )
        >>> # 3. Forward to generator
        >>> outputs = model(
        ...     inputs=None,
        ...     context_input_ids=docs_dict["context_input_ids"],
        ...     context_attention_mask=docs_dict["context_attention_mask"],
        ...     doc_scores=doc_scores,
        ...     decoder_input_ids=input_dict["labels"],
        ... )

        >>> # or directly generate
        >>> generated = model.generate(
        ...     context_input_ids=docs_dict["context_input_ids"],
        ...     context_attention_mask=docs_dict["context_attention_mask"],
        ...     doc_scores=doc_scores,
        ... )
        >>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)
        ```r}   r~   NFrò   ró   r   r   r!   r    r$   r%   r"   r#   r&   r(   r)   r*   r+   r,   r-   r.   r4   )rD   Úexclude_bos_scorerô   r;   rö   r   r!   r÷   r   r    r$   r%   r"   r#   r&   r(   r)   r*   r+   r,   r-   r.   )rt   r£   r   r�   r‘   r�   r    r!   r$   r%   r’   r¤   r¥   r¦   r…   rd  rø   rô   r€   r�   r\   rù   r   s                          r6   r«   zTFRagSequenceForGeneration.callV  sè  € ðv '¨fÑ4ð 	
ØFó	
Ð4ñ 2CÑ-ÈÏÉ×HeÑHeÐÙ%0‘k°d·k±k×6MÑ6MˆàÐØ Ð(Ø$*Ð!ØˆIà—(‘(ØØ)Ø+Ø/Ø#9Ø/Ø#9Ø!Ø+ØØ/Ø!5Ø-ØØð ó 
ˆð$ ˆØÐØ—<‘<Ø—‘Ø×"Ñ"ØØ'ØŸ™×3Ñ3Øð  ó ˆDô *ò 
Ùð
à—>’>ð
ð ×)Ò)ð
ð $×3Ò3ð	
ð
 &×7Ò7ð
ð $+×#AÒ#Að
ð ")×!=Ò!=ð
ð &×7Ò7ð
ð 07×/YÒ/Yð
ð (/×'IÒ'Ið
ð %,×$CÒ$Cð
ð -4×,SÒ,Sð
ð )0×(KÒ(Kð
ð &-×%EÒ%Eð
ð )0×(KÒ(Kð
ð  &-×%EÒ%Eð!
ð 	
r5   c           
     ó6  ‡ ‡— t        j                  ‰d d …dd …f   t        j                  ‰j                  d   dgt        j                  ‰ j
                  j                  j                  ‰j                  «      «      gd¬«      Š‰ j
                  j                  xs  ‰ j
                  j                  j                  }|�|n‰ j
                  j                  }t        j                  t        j                  ‰d d …df   |«      «      }	|d uxr |	}
ˆ ˆfd„}t         j                  j                  |d¬«      }t        j                  ||j                  d   |z  |d|j                  d   f«      }t         j                  j                  |d¬«      }t        j                   |d¬«      }t        j                   |d¬«      }|d d …d d …d d…d d …f   }|d d …d d …dd…d d …f   }|d d …d d …dd …d d …f   }t        j                  |||z   |gd¬«      }t        j                   ‰d¬«      Št        j                   ‰d¬«      Št        j"                  ‰|d¬«      Št%        ‰j                  «      t%        |j                  «      k(  sJ ‚d„ } ||‰¬«      }t        j&                  |dd	¬
«      } |||«      \  }}|r&|
r$t        j&                  |d d …d d …dd …f   d¬«      }nt        j&                  |d¬«      }t        j&                  |d¬«      }t         j(                  j+                  |d¬«      }t         j(                  j+                  |d¬«      }| }| }|r*t        j&                  |«      }t        j&                  |«      }||j                  d   z  }d|z
  |z  ||z  z   }|S )Nr   r   rˆ   c                óŠ  •— t        j                  ‰t        j                  ‰j                  j                  j
                  ‰j                  «      «      }t        j                  |«      r.t        j                  |d| «      } t        j                  |d|«      }t        j                  | d¬«      t        j                  |d¬«      fS )NrY  rË   rˆ   )
r‚   Úequalr”   rD   rJ   r  r%  Ú
reduce_anyr'  r—   )ÚllÚ
smooth_objÚpad_maskrt   r4  s      €€r6   Ú
_mask_padsz6TFRagSequenceForGeneration.get_nll.<locals>._mask_padsü  s†   ø€ Ü—x‘x ¬¯©°·±×0EÑ0E×0RÑ0RÐTZ×T`ÑT`Ó(aÓbˆHÜ�}‰}˜XÔ&Ü—X‘X˜h¨¨RÓ0�ÜŸX™X h°°ZÓ@�
Ü—:‘:˜b rÔ*¬B¯J©J°zÈÔ,KÐKÐKr5   rË   rA   c                óÔ   — d„ }t        j                  | d| j                  d   f«      }|j                  }t        j                  |d«      } |||«      }t        j                  ||«      S )Nc                ó  — t        j                  t        j                  t        j                  |«      d   |j                  ¬«      |d d …df   gd¬«      }t        j
                  | |«      }t        j                  |d¬«      S )Nr   )r%  rË   rˆ   )r‚   ÚstackÚrangerš   r%  Ú	gather_ndr™   )r4  Ú	id_tensorÚidxÚresults       r6   Úgather2dzJTFRagSequenceForGeneration.get_nll.<locals>.torch_gather.<locals>.gather2d  sc   € Ü—h‘h¤§¡¬¯©°)Ó)<¸QÑ)?ÀyÇÁÔ WÐYbÒcdÐfgÐcgÑYhÐiÐprÔs�ÜŸ™ f¨cÓ2�Ü—~‘~ f°2Ô6Ð6r5   rË   )rË   r   )r‚   rÛ   rš   )Úparamrr  ru  r4  Útarget_shapert  s         r6   Útorch_gatherz8TFRagSequenceForGeneration.get_nll.<locals>.torch_gather  s\   € ò7ô
 —Z‘Z ¨¨E¯K©K¸©OÐ'<Ó=ˆFØ$Ÿ?™?ˆLäŸ
™
 9¨gÓ6ˆIÙ˜f iÓ0ˆFÜ—:‘:˜f lÓ3Ð3r5   )rr  T)r‰   Úkeepdimsr:  )r‚   r&  r  rš   r”   rD   rJ   r  r%  Úbos_token_idr…   Ú
reduce_allrg  ré   rê   rÛ   r™   r›   rP   rD  r@  rë   )rt   rì   r!   r4  rô   rõ   rd  r…   rz  Úequal_bos_token_id_allÚuse_bosrl  rí   rî   Úfirst_token_scoresÚsecond_token_scoresÚ	remainderr5  rx  ri  rj  rL  rM  rN  r   s   `  `                     r6   rö   z"TFRagSequenceForGeneration.get_nllí  s'  ù€ ô —‘Ø’A�q‘r�E‰]œBŸG™G V§\¡\°!¡_°aÐ$8¼"¿'¹'À$Ç+Á+×BWÑBW×BdÑBdÐfl×frÑfrÓ:sÓtÐuØô
ˆð —{‘{×/Ñ/ÒU°4·;±;×3HÑ3H×3UÑ3UˆØ!Ð-‘°4·;±;×3EÑ3EˆÜ!#§¡¬r¯x©x¸ºqÀ!¸t¹ÀlÓ/SÓ!TÐØ dÐ*ÒEÐ/Eˆõ	Lô —u‘u×(Ñ(¨¸"Ð(Ó=ˆÜ—z‘zØ˜:×+Ñ+¨AÑ.°&Ñ8¸&À"Àj×FVÑFVÐWYÑFZÐ[ó
ˆô —u‘u×(Ñ(¨¸!Ð(Ó<ˆÜ—~‘~ l¸Ô<ˆÜ—~‘~ l¸Ô<ˆð *ª!ªQ°°°²A¨+Ñ6ÐØ*ª1ªa°°1°²a¨<Ñ8ÐØ ¢¢A q¡rª1 Ñ-ˆ	Ü—y‘yÐ"4Ð6IÈLÑ6XÐZcÐ!dÐklÔmˆô —‘ ¨QÔ/ˆÜ—‘ ¨RÔ0ˆÜ—‘˜6 6°Ô2ˆÜ�6—<‘<Ó ¤C¨×(:Ñ(:Ó$;Ò;Ð;Ð;ò	4ñ ˜,°&Ô9ˆÜ—]‘] <°bÀ4ÔHˆ
á# B¨
Ó3‰ˆˆJñ ¡Ü—‘˜r¢!¢Q¨© (™|°!Ô4‰Bä—‘˜r¨Ô*ˆBä—]‘] :°AÔ6ˆ
Ü�W‰W×%Ñ% b¨qÐ%Ó1ˆÜ—W‘W×-Ñ-¨j¸qÐ-ÓAˆ
à�3ˆØ!�kˆáÜ—}‘} XÓ.ˆHÜŸ-™-¨Ó4ˆKà˜,×,Ñ,¨RÑ0Ñ0ˆØ�g‘ Ñ)¨E°KÑ,?Ñ?ˆØˆr5   c
                óä  — |	�|	n| j                   j                  }	|�|n| j                   j                  }|�|n| j                   j                  }|�|n| j                   j                  }|€	|€J d«       ‚| j
                  �]|€[| j                  ||¬«      d   }| j                  ||j                  «       | j                  j                   j                  |	d¬«      d   }g }||
d<   ||
d	<   d|
d
<   |�|j                  d   n|j                  d   |	z  }t        |«      D �]œ  }|||	z  |dz   |	z   } | j                  j                  |fi |
¤Ž}|r`t        j                  t        |D �ci c]*  }t!        |j                  «       j#                  «       «      |“Œ, c}j%                  «       «      «      }|j                  d   }|�*t        j&                  |||dz    |df«      } | ||d¬«      }n„|€J d«       ‚|€J d«       ‚t        j&                  ||df«      }|||	z  |dz   |	z   }t        j&                  ||df«      }|||dz   …dd…f   }t        j&                  ||df«      } | d||||d¬«      }t        j(                  j+                  |d    |¬«      d   }|j-                  t        j.                  ||«      «       �ŒŸ | j1                  || j                   j                  j2                  ¬«      S c c}w )aË  
        Implements RAG sequence "thorough" decoding. Read the [`~generation.GenerationMixin.generate`]` documentation
        for more information on how to set other generate input parameters

        Args:
            input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                The sequence used as a prompt for the generation. If `input_ids` is not passed, then
                `context_input_ids` has to be provided.
            attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for
                tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention
                masks?](../glossary#attention-mask)
            context_input_ids (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
                Input IDs post-processed from the retrieved documents and the question encoder input_ids by the
                retriever.
            context_attention_mask (`tf.Tensor` of shape `(batch_size * config.n_docs, config.max_combined_length)`, *optional*, returned when *output_retrieved=True*):
                Attention mask post-processed from the retrieved documents and the question encoder `input_ids` by the
                retriever. If the model has is not initialized with a `retriever` or `input_ids` is not given,
                `context_input_ids` and `context_attention_mask` have to be provided to the forward pass. They are
                returned by [`~RagRetriever.__call__`].
            doc_scores (`tf.Tensor` of shape `(batch_size, config.n_docs)`):
                Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
                `question_encoder_last_hidden_state`. If the model has is not initialized with a `retriever` or
                `input_ids` is not given, `doc_scores` has to be provided to the forward pass. `doc_scores` are
                returned by [`~RagRetriever.__call__`].
            do_deduplication (`bool`, *optional*):
                Whether or not to deduplicate the generations from different context documents for a given input. Has
                to be set to `False` if used while training with distributed backend.
            num_return_sequences(`int`, *optional*, defaults to 1):
                The number of independently computed returned sequences for each element in the batch. Note that this
                is not the value we pass to the `generator`'s `[`~generation.GenerationMixin.generate`]` function,
                where we set `num_return_sequences` to `num_beams`.
            num_beams (`int`, *optional*, defaults to 1):
                Number of beams for beam search. 1 means no beam search.
            n_docs (`int`, *optional*, defaults to `config.n_docs`)
                Number of documents to retrieve and/or number of documents for which to generate an answer.
            kwargs (`Dict[str, Any]`, *optional*):
                Additional kwargs will be passed to [`~generation.GenerationMixin.generate`]

        Return:
            `tf.Tensor` of shape `(batch_size * num_return_sequences, sequence_length)`: The generated sequences. The
            second dimension (sequence length) is either equal to `max_length` or shorter if all batches finished early
            due to the `eos_token_id`.
        Nz= At least one of input_ids or context_input_ids must be givenrû   r   r‚   rƒ   r$   rÿ   r  r   r   T)rø   rd  z�Make sure that `context_attention_mask` are passed, if no `input_ids` is set. Alternatively, you can set a retriever using the `set_retriever(...)` function.z‘Make sure that `doc_scores` are passed, if no `input_ids` is set. Alternatively, you can set a retriever using the `set_retriever(...)` function.)r£   r$   r%   r!   rø   rd  r   )Úk)r  )rD   r…   Údo_deduplicationr  rÿ   rM   rF   r“   rJ   r„   rš   rp  r  r‚   ro  ÚlistÚstrÚtolistÚvaluesÚtiler@  Útop_kÚappendrÜ   Ú_cat_and_padr  )rt   r£   r   r$   r%   r!   rƒ  r  rÿ   r…   r  Únum_doc_return_sequencesr  Úhyposrß   ÚindexÚgenerator_input_idsÚoutput_sequencesr‚  Únum_candidatesÚnew_input_idsrù   Úindividual_input_idsÚindividual_attention_maskÚindividual_doc_scoresÚtop_cand_indss                             r6   r  z#TFRagSequenceForGeneration.generateA  sv  € ðt "Ð-‘°4·;±;×3EÑ3EˆØ/?Ð/KÑ+ÐQU×Q\ÑQ\×QmÑQmÐà$8Ð$DÑ È$Ï+É+×JjÑJjð 	!ð "+Ð!6‘I¸D¿K¹K×<QÑ<Qˆ	àÐ$Ð(9Ð(Eð 	
ØKó	
ÐEð �>‰>Ð%Ð*;Ð*CØ%)×%:Ñ%:¸9ÐUcÐ%:Ó%dÐefÑ%gÐ"Ø $§¡ØØ&×,Ñ,Ó.Ø—~‘~×,Ñ,×3Ñ3ØØ#ð !/ó !ð "ñ!#Ðð ˆØ$-ˆ�[Ñ!Ø/8ˆÐ+Ñ,Ø)-ˆÐ%Ñ&à+4Ð+@�Y—_‘_ QÒ'ÐFW×F]ÑF]Ð^_ÑF`ÐdjÑFjˆ
ä˜:Ó&ó 4	EˆEà"3°E¸F±NÀeÈaÁiÐSYÑEYÐ"ZÐà6˜tŸ~™~×6Ñ6Ø#ñ àñ Ðñ  ä#%§8¡8¬DÐVfÖ1gÐQR´#°a·g±g³i×6FÑ6FÓ6HÓ2IÈ1Ñ2LÒ1g×1nÑ1nÓ1pÓ,qÓ#rÐ à-×3Ñ3ØñˆNð
 Ð$Ü "§¡¨	°%¸%À!¹)Ð(DÀ~ÐWXÐFYÓ Z�Ù˜}Ð5EÐY]Ô^‘à-Ð9ð ðTóÐ9ð "Ð-ð ðJóÐ-ô
 (*§w¡wØ'¨.¸!Ð)<ó(Ð$ð -CÀ5È6Á>ÐUZÐ]^ÑU^ÐbhÑThÐ,iÐ)Ü,.¯G©GÐ4MÐP^Ð`aÐObÓ,cÐ)à(2°5¸EÀA¹IÐ3FÊÐ3IÑ(JÐ%Ü(*¯©Ð0EÈÐXYÐGZÓ([Ð%áØ"Ø&:Ø+DØ4Ø+Ø&*ô�ô ŸG™GŸM™M¨G°F©OÐ+;Ð@X˜MÓYÐZ[Ñ\ˆMð �L‰LœŸ™Ð#3°]ÓCÖDði4	Eðl × Ñ  °T·[±[×5JÑ5J×5WÑ5WÐ ÓXÐXùòY 2hs   Å%/K-c                ó$  — t        | D �cg c]  }|j                  d   ‘Œ c}«      t        | D �cg c]  }|j                  d   ‘Œ c}«      f}t        j                  ||«      }t        j
                  |«      }d}| D ]K  }||||j                  d   z   …d |j                  d   …f   j                  |«       ||j                  d   z  }ŒM t        j                  |«      }t        j                  || d   d   d   j                  «      S c c}w c c}w )Nr   r   )
Úsumrš   Úmaxr‚   r  ÚVariableÚassignÚconvert_to_tensorr”   r%  )Útensorsr  Útr  ÚoutputÚinds         r6   r‹  z'TFRagSequenceForGeneration._cat_and_padÏ  sû   € ô ¨WÖ5¨˜Ÿ™ ›Ò5Ó6¼ÐQXÖ<YÈA¸Q¿W¹WÀQ»ZÒ<YÓ8ZÐZˆ	Ü—‘˜ LÓ1ˆô —‘˜VÓ$ˆð ˆØò 	ˆAØ�3˜˜qŸw™w q™zÑ)Ð)¨<¨Q¯W©W°Q©Z¨<Ð7Ñ8×?Ñ?ÀÔBØ�1—7‘7˜1‘:Ñ‰Cð	ô ×%Ñ% fÓ-ˆÜ�w‰w�v˜w q™z¨!™}¨QÑ/×5Ñ5Ó6Ð6ùò 6ùÒ<Ys
   ŠD¯D
c                óú   — | j                   ry d| _         t        | dd «      �Nt        j                  | j                  j
                  «      5  | j                  j                  d «       d d d «       y y # 1 sw Y   y xY wrP  rQ  r°   s     r6   r¯   z TFRagSequenceForGeneration.buildä  rS  rT  rU  rV  rµ   rW  )(r£   r¶   r   r·   r�   r·   r‘   r·   r�   r·   r    z4Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]]r!   r·   r$   r·   r%   r·   r’   úOptional[bool]r¤   r¢  r¥   r¢  r¦   r¢  r…   zOptional[int]rd  r¢  rø   r·   rô   r¢  r€   r¢  r�   r»   rf   z3Union[Tuple[tf.Tensor], TFRetrievAugLMMarginOutput])FrY  FN)	NNNNNNNNNrX  rw   )r/   r0   r1   rI   rq   ry   rZ  rM   rJ   rF   r   r   r¼   r   r   r½   r«   rö   r  r[  r‹  r¯   r¾   r¿   s   @r6   r]  r]  !  s6  ø„ ð @Ðð .2Ø8<Ø15Ø,0ð
à*ð
ð 6ð
ð /ð	
ð
 *õ
ó:'ð ñ"ó ð"ð ñ"ó ð"ð ñ)ó ð)ð Ù*Ð+GÓHÙÐ+EÐTcÔdð .2Ø8<Ø;?Ø@DØ9=ØPTØ48Ø;?Ø@DØ$(Ø,0Ø/3Ø+/Ø $Ø,0Ø04Ø&*Ø&*Øð)R
à*ðR
ð 6ðR
ð 9ð	R
ð
 !>ðR
ð 7ðR
ð NðR
ð 2ðR
ð 9ðR
ð !>ðR
ð "ðR
ð *ðR
ð -ðR
ð )ðR
ð ðR
ð  *ð!R
ð" .ð#R
ð$ $ð%R
ð& $ð'R
ð( ð)R
ð, 
=ò-R
ó eó Ió ðR
ðj osóRðl .2Ø+/ØØ#ØØØ!ØØðLYà*ðLYð )óLYð\ ñ7ó ð7÷(%r5   r]  )rl   r:   r]  rÁ   )0r2   Ú
__future__r   r  Údataclassesr   Útypingr   r   r   r   r“   r  Ú
tensorflowr‚   Úconfiguration_utilsr
   Ú
generationr   Úmodeling_tf_utilsr   r   r   r   r   r   Úutilsr   r   r   r   Úconfiguration_ragr   Úretrieval_ragr   Ú
get_loggerr/   Úloggerr½   r   r8   r:   ÚRAG_START_DOCSTRINGr¼   rl   rÁ   r]  Ú__all__r4   r5   r6   ú<module>r±     sQ  ðñ  "å "ã Ý !ß /Ó /ã Û å 3Ý /÷÷ ÷ lÓ kÝ (Ý 'ð 
ˆ×	Ñ	˜HÓ	%€à€ð ôTB ó TBó ðTBðn ôOB˜;ó OBó ðOBôdhoÐ,ô hoðV&Ð ðR? Ð ñD 'Ð':Ó;ôi.Ð%ó i.ó <ði.ñX 'ðð ó	ô{%Ð2Ð4Pó {%óð{%ñ| 'ðð ó	ôC%Ð!5Ð7Só C%óðC%òL j�r5   