---
local: rag
sections:
- local: overview
  title: Overview
- local: transformers.RagConfig
  title: RagConfig
- local: transformers.RagTokenizer
  title: RagTokenizer
- local: transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
  title: Rag specific outputs
- local: transformers.RagRetriever
  title: RagRetriever
- local: transformers.RagModel
  title: RagModel
- local: transformers.RagSequenceForGeneration
  title: RagSequenceForGeneration
- local: transformers.RagTokenForGeneration
  title: RagTokenForGeneration
- local: transformers.TFRagModel
  title: TFRagModel
- local: transformers.TFRagSequenceForGeneration
  title: TFRagSequenceForGeneration
- local: transformers.TFRagTokenForGeneration
  title: TFRagTokenForGeneration
title: RAG
---
<script>
import Tip from "./Tip.svelte";
import Youtube from "./Youtube.svelte";
import Docstring from "./Docstring.svelte";
import CodeBlock from "./CodeBlock.svelte";
import CodeBlockFw from "./CodeBlockFw.svelte";
import DocNotebookDropdown from "./DocNotebookDropdown.svelte";
import IconCopyLink from "./IconCopyLink.svelte";
export let fw: "pt" | "tf"
</script>
<!--Copyright 2020 The HuggingFace Team. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
-->

<h1 id="rag">RAG</h1>

<h2 id="overview">Overview</h2>

Retrieval-augmented generation ("RAG") models combine the powers of pretrained dense retrieval (DPR) and
sequence-to-sequence models. RAG models retrieve documents, pass them to a seq2seq model, then marginalize to generate
outputs. The retriever and seq2seq modules are initialized from pretrained models, and fine-tuned jointly, allowing
both retrieval and generation to adapt to downstream tasks.

It is based on the paper [Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks](https://arxiv.org/abs/2005.11401) by Patrick Lewis, Ethan Perez, Aleksandara Piktus, Fabio Petroni, Vladimir
Karpukhin, Naman Goyal, Heinrich Küttler, Mike Lewis, Wen-tau Yih, Tim Rocktäschel, Sebastian Riedel, Douwe Kiela.

The abstract from the paper is the following:

*Large pre-trained language models have been shown to store factual knowledge in their parameters, and achieve
state-of-the-art results when fine-tuned on downstream NLP tasks. However, their ability to access and precisely
manipulate knowledge is still limited, and hence on knowledge-intensive tasks, their performance lags behind
task-specific architectures. Additionally, providing provenance for their decisions and updating their world knowledge
remain open research problems. Pre-trained models with a differentiable access mechanism to explicit nonparametric
memory can overcome this issue, but have so far been only investigated for extractive downstream tasks. We explore a
general-purpose fine-tuning recipe for retrieval-augmented generation (RAG) — models which combine pre-trained
parametric and non-parametric memory for language generation. We introduce RAG models where the parametric memory is a
pre-trained seq2seq model and the non-parametric memory is a dense vector index of Wikipedia, accessed with a
pre-trained neural retriever. We compare two RAG formulations, one which conditions on the same retrieved passages
across the whole generated sequence, the other can use different passages per token. We fine-tune and evaluate our
models on a wide range of knowledge-intensive NLP tasks and set the state-of-the-art on three open domain QA tasks,
outperforming parametric seq2seq models and task-specific retrieve-and-extract architectures. For language generation
tasks, we find that RAG models generate more specific, diverse and factual language than a state-of-the-art
parametric-only seq2seq baseline.*

This model was contributed by [ola13](https://huggingface.co/ola13).


<h2 id="transformers.RagConfig">RagConfig</h2>

<div class="docstring">

<docstring><name>class transformers.RagConfig</name><anchor>transformers.RagConfig</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/configuration_rag.py#L82</source><parameters>[{"name": "vocab_size", "val": " = None"}, {"name": "is_encoder_decoder", "val": " = True"}, {"name": "prefix", "val": " = None"}, {"name": "bos_token_id", "val": " = None"}, {"name": "pad_token_id", "val": " = None"}, {"name": "eos_token_id", "val": " = None"}, {"name": "decoder_start_token_id", "val": " = None"}, {"name": "title_sep", "val": " = ' / '"}, {"name": "doc_sep", "val": " = ' // '"}, {"name": "n_docs", "val": " = 5"}, {"name": "max_combined_length", "val": " = 300"}, {"name": "retrieval_vector_size", "val": " = 768"}, {"name": "retrieval_batch_size", "val": " = 8"}, {"name": "dataset", "val": " = 'wiki_dpr'"}, {"name": "dataset_split", "val": " = 'train'"}, {"name": "index_name", "val": " = 'compressed'"}, {"name": "index_path", "val": " = None"}, {"name": "passages_path", "val": " = None"}, {"name": "use_dummy_dataset", "val": " = False"}, {"name": "reduce_loss", "val": " = False"}, {"name": "label_smoothing", "val": " = 0.0"}, {"name": "do_deduplication", "val": " = True"}, {"name": "exclude_bos_score", "val": " = False"}, {"name": "do_marginalize", "val": " = False"}, {"name": "output_retrieved", "val": " = False"}, {"name": "use_cache", "val": " = True"}, {"name": "forced_eos_token_id", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **title_sep** (`str`, *optional*, defaults to  `" / "`) --
  Separator inserted between the title and the text of the retrieved document when calling [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever).
- **doc_sep** (`str`, *optional*, defaults to  `" // "`) --
  Separator inserted between the the text of the retrieved document and the original input when calling
  [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever).
- **n_docs** (`int`, *optional*, defaults to 5) --
  Number of documents to retrieve.
- **max_combined_length** (`int`, *optional*, defaults to 300) --
  Max length of contextualized input returned by `__call__()`
- **retrieval_vector_size** (`int`, *optional*, defaults to 768) --
  Dimensionality of the document embeddings indexed by [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever).
- **retrieval_batch_size** (`int`, *optional*, defaults to 8) --
  Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated
  [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever).
- **dataset** (`str`, *optional*, defaults to `"wiki_dpr"`) --
  A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids
  using `datasets.list_datasets()`).
- **dataset_split** (`str`, *optional*, defaults to `"train"`) --
  Which split of the `dataset` to load.
- **index_name** (`str`, *optional*, defaults to `"compressed"`) --
  The index name of the index associated with the `dataset`. One can choose between `"legacy"`, `"exact"` and
  `"compressed"`.
- **index_path** (`str`, *optional*) --
  The path to the serialized faiss index on disk.
  passages_path -- (`str`, *optional*):
  A path to text passages compatible with the faiss index. Required if using
  `LegacyIndex`- **use_dummy_dataset** (`bool`, *optional*, defaults to `False`) --
  Whether to load a "dummy" variant of the dataset specified by `dataset`.
- **label_smoothing** (`float`, *optional*, defaults to 0.0) --
  Only relevant if `return_loss` is set to `True`. Controls the `epsilon` parameter value for label smoothing
  in the loss calculation. If set to 0, no label smoothing is performed.
- **do_marginalize** (`bool`, *optional*, defaults to `False`) --
  If `True`, the logits are marginalized over all documents by making use of
  `torch.nn.functional.log_softmax`.
- **reduce_loss** (`bool`, *optional*, defaults to `False`) --
  Whether or not to reduce the NLL loss using the `torch.Tensor.sum` operation.
- **do_deduplication** (`bool`, *optional*, defaults to `True`) --
  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.
- **exclude_bos_score** (`bool`, *optional*, defaults to `False`) --
  Whether or not to disregard the BOS token when computing the loss.
- **output_retrieved(`bool`,** *optional*, defaults to `False`) --
  If set to `True`, `retrieved_doc_embeds`, `retrieved_doc_ids`, `context_input_ids` and
  `context_attention_mask` are returned. See returned tensors for more detail.
- **use_cache** (`bool`, *optional*, defaults to `True`) --
  Whether or not the model should return the last key/values attentions (not used by all models).
- **forced_eos_token_id** (`int`, *optional*) --
  The id of the token to force as the last generated token when `max_length` is reached. Usually set to
  `eos_token_id`.</paramsdesc><paramgroups>0</paramgroups></docstring>

[RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig) stores the configuration of a *RagModel*. Configuration objects inherit from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) and
can be used to control the model outputs. Read the documentation from [PretrainedConfig](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig) for more information.





<div class="docstring">
<docstring><name>from\_question\_encoder\_generator\_configs</name><anchor>transformers.RagConfig.from_question_encoder_generator_configs</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/configuration_rag.py#L170</source><parameters>[{"name": "question_encoder_config", "val": ": PretrainedConfig"}, {"name": "generator_config", "val": ": PretrainedConfig"}, {"name": "**kwargs", "val": ""}]</parameters><rettype>[EncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/encoder-decoder#transformers.EncoderDecoderConfig)</rettype><retdesc>An instance of a configuration object</retdesc></docstring>

Instantiate a [EncoderDecoderConfig](/docs/transformers/pr_15592/en/model_doc/encoder-decoder#transformers.EncoderDecoderConfig) (or a derived class) from a pre-trained encoder model configuration and
decoder model configuration.






</div>
<div class="docstring">
<docstring><name>to\_dict</name><anchor>transformers.RagConfig.to_dict</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/configuration_rag.py#L183</source><parameters>[]</parameters><rettype>`Dict[str, any]`</rettype><retdesc>Dictionary of all the attributes that make up this configuration instance,</retdesc></docstring>

Serializes this instance to a Python dictionary. Override the default [to_dict()](/docs/transformers/pr_15592/en/main_classes/configuration#transformers.PretrainedConfig.to_dict).






</div></div>

<h2 id="transformers.RagTokenizer">RagTokenizer</h2>

<div class="docstring">

<div class="docstring">
<docstring><name>as\_target\_tokenizer</name><anchor>transformers.RagTokenizer.as_target_tokenizer</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/tokenization_rag.py#L71</source><parameters>[]</parameters></docstring>

Temporarily sets the tokenizer for encoding the targets. Useful for tokenizer associated to
sequence-to-sequence models that need a slightly different processing for the labels.


</div></div>

<h2 id="transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput">Rag specific outputs</h2>

<div class="docstring">

<docstring><name>class transformers.models.rag.modeling\_rag.RetrievAugLMMarginOutput</name><anchor>transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L41</source><parameters>[{"name": "loss", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "logits", "val": ": FloatTensor = None"}, {"name": "doc_scores", "val": ": FloatTensor = None"}, {"name": "past_key_values", "val": ": typing.Optional[typing.List[torch.FloatTensor]] = None"}, {"name": "retrieved_doc_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "retrieved_doc_ids", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "context_input_ids", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "context_attention_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "question_encoder_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "question_enc_hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "question_enc_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_enc_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "generator_enc_hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_enc_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_dec_hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_dec_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_cross_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}]</parameters><paramsdesc>- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) --
  Language modeling loss.
- **logits** (`torch.FloatTensor` 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.
- **doc_scores** (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`) --
  Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
  `question_encoder_last_hidden_state`.
- **past_key_values** (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) --
  List of `torch.FloatTensor` 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.
- **retrieved_doc_embeds** (`torch.FloatTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (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.
- **generator_cross_attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</paramsdesc><paramgroups>0</paramgroups></docstring>

Base class for retriever augmented marginalized models outputs.




</div>

<div class="docstring">

<docstring><name>class transformers.models.rag.modeling\_rag.RetrievAugLMOutput</name><anchor>transformers.models.rag.modeling_rag.RetrievAugLMOutput</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L136</source><parameters>[{"name": "logits", "val": ": FloatTensor = None"}, {"name": "doc_scores", "val": ": FloatTensor = None"}, {"name": "past_key_values", "val": ": typing.Optional[typing.List[torch.FloatTensor]] = None"}, {"name": "retrieved_doc_embeds", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "retrieved_doc_ids", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "context_input_ids", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "context_attention_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "question_encoder_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "question_enc_hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "question_enc_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_enc_last_hidden_state", "val": ": typing.Optional[torch.FloatTensor] = None"}, {"name": "generator_enc_hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_enc_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_dec_hidden_states", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_dec_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}, {"name": "generator_cross_attentions", "val": ": typing.Optional[typing.Tuple[torch.FloatTensor]] = None"}]</parameters><paramsdesc>- **logits** (`torch.FloatTensor` 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.
- **doc_scores** (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`) --
  Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
  `question_encoder_last_hidden_state`.
- **past_key_values** (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) --
  List of `torch.FloatTensor` 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.
- **retrieved_doc_embeds** (`torch.FloatTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) --
  Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (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.
- **generator_cross_attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) --
  Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</paramsdesc><paramgroups>0</paramgroups></docstring>




</div>

<h2 id="transformers.RagRetriever">RagRetriever</h2>

<div class="docstring">

<docstring><name>class transformers.RagRetriever</name><anchor>transformers.RagRetriever</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/retrieval_rag.py#L325</source><parameters>[{"name": "config", "val": ""}, {"name": "question_encoder_tokenizer", "val": ""}, {"name": "generator_tokenizer", "val": ""}, {"name": "index", "val": " = None"}, {"name": "init_retrieval", "val": " = True"}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) --
  The configuration of the RAG model this Retriever is used with. Contains parameters indicating which
  `Index` to build. You can load your own custom dataset with `config.index_name="custom"` or use a canonical
  one (default) from the datasets library with `config.index_name="wiki_dpr"` for example.
- **question_encoder_tokenizer** ([PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer)) --
  The tokenizer that was used to tokenize the question. It is used to decode the question and then use the
  generator_tokenizer.
- **generator_tokenizer** ([PreTrainedTokenizer](/docs/transformers/pr_15592/en/main_classes/tokenizer#transformers.PreTrainedTokenizer)) --
  The tokenizer used for the generator part of the RagModel.
- **index** (`Index` optional, defaults to the one defined by the configuration) --
  If specified, use this index instead of the one built using the configuration</paramsdesc><paramgroups>0</paramgroups></docstring>

Retriever used to get documents from vector queries. It retrieves the documents embeddings as well as the documents
contents, and it formats them to be used with a RagModel.



Examples:

```python
>>> # To load the default "wiki_dpr" dataset with 21M passages from wikipedia (index name is 'compressed' or 'exact')
>>> from transformers import RagRetriever

>>> retriever = RagRetriever.from_pretrained(
...     "facebook/dpr-ctx_encoder-single-nq-base", dataset="wiki_dpr", index_name="compressed"
... )

>>> # To load your own indexed dataset built with the datasets library. More info on how to build the indexed dataset in examples/rag/use_own_knowledge_dataset.py
>>> from transformers import RagRetriever

>>> dataset = (
...     ...
>>> )  # dataset must be a datasets.Datasets object with columns "title", "text" and "embeddings", and it must have a faiss index
>>> retriever = RagRetriever.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", indexed_dataset=dataset)

>>> # To load your own indexed dataset built with the datasets library that was saved on disk. More info in examples/rag/use_own_knowledge_dataset.py
>>> from transformers import RagRetriever

>>> dataset_path = "path/to/my/dataset"  # dataset saved via *dataset.save_to_disk(...)*
>>> index_path = "path/to/my/index.faiss"  # faiss index saved via *dataset.get_index("embeddings").save(...)*
>>> retriever = RagRetriever.from_pretrained(
...     "facebook/dpr-ctx_encoder-single-nq-base",
...     index_name="custom",
...     passages_path=dataset_path,
...     index_path=index_path,
... )

>>> # To load the legacy index built originally for Rag's paper
>>> from transformers import RagRetriever

>>> retriever = RagRetriever.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", index_name="legacy")
```


<div class="docstring">
<docstring><name>init\_retrieval</name><anchor>transformers.RagRetriever.init_retrieval</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/retrieval_rag.py#L459</source><parameters>[]</parameters></docstring>

Retriever initialization function. It loads the index into memory.


</div>
<div class="docstring">
<docstring><name>postprocess\_docs</name><anchor>transformers.RagRetriever.postprocess_docs</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/retrieval_rag.py#L467</source><parameters>[{"name": "docs", "val": ""}, {"name": "input_strings", "val": ""}, {"name": "prefix", "val": ""}, {"name": "n_docs", "val": ""}, {"name": "return_tensors", "val": " = None"}]</parameters><paramsdesc>- **docs**  (`dict`) --
  Retrieved documents.
- **input_strings** (`str`) --
  Input strings decoded by `preprocess_query`.
- **prefix** (`str`) --
  Prefix added at the beginning of each input, typically used with T5-based models.</paramsdesc><paramgroups>0</paramgroups><rettype>`tuple(tensors)`</rettype><retdesc>a tuple consisting of two elements: contextualized `input_ids` and a compatible
`attention_mask`.</retdesc></docstring>

Postprocessing retrieved `docs` and combining them with `input_strings`.








</div>
<div class="docstring">
<docstring><name>retrieve</name><anchor>transformers.RagRetriever.retrieve</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/retrieval_rag.py#L539</source><parameters>[{"name": "question_hidden_states", "val": ": ndarray"}, {"name": "n_docs", "val": ": int"}]</parameters><paramsdesc>- **question_hidden_states** (`np.ndarray` of shape `(batch_size, vector_size)`) --
  A batch of query vectors to retrieve with.
- **n_docs** (`int`) --
  The number of docs retrieved per query.</paramsdesc><paramgroups>0</paramgroups><rettype>`Tuple[np.ndarray, np.ndarray, List[dict]]`</rettype><retdesc>A tuple with the following objects:

- **retrieved_doc_embeds** (`np.ndarray` of shape `(batch_size, n_docs, dim)`) -- The retrieval embeddings
  of the retrieved docs per query.
- **doc_ids** (`np.ndarray` of shape `(batch_size, n_docs)`) -- The ids of the documents in the index
- **doc_dicts** (`List[dict]`): The `retrieved_doc_embeds` examples per query.</retdesc></docstring>

Retrieves documents for specified `question_hidden_states`.








</div></div>

<h2 id="transformers.RagModel">RagModel</h2>

<div class="docstring">

<docstring><name>class transformers.RagModel</name><anchor>transformers.RagModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L494</source><parameters>[{"name": "config", "val": ": typing.Optional[transformers.configuration_utils.PretrainedConfig] = None"}, {"name": "question_encoder", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "generator", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "retriever", "val": ": typing.Optional = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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
  [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.
- **question_encoder** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)) --
  An encoder model compatible with the faiss index encapsulated by the `retriever`.
- **generator** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)) --
  A seq2seq model used as the generator in the RAG architecture.
- **retriever** ([RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever)) --
  A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.</paramsdesc><paramgroups>0</paramgroups></docstring>
The [RagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagModel) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>


RAG is a seq2seq 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 [DPRQuestionEncoder](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.DPRQuestionEncoder), and the generator can be
any *seq2seq* model, preferably [BartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.BartForConditionalGeneration).

The model can be initialized with a [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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 [DPRQuestionEncoder](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.DPRQuestionEncoder) as the `question_encoder` and [BartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.BartForConditionalGeneration) or
[T5ForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/t5#transformers.T5ForConditionalGeneration) as the `generator`.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel). 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 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.






<div class="docstring">
<docstring><name>forward</name><anchor>transformers.RagModel.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L537</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_retrieved", "val": " = None"}, {"name": "n_docs", "val": " = None"}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary. [RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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.

  [What are input IDs?](../glossary#input-ids)
- **attention_mask** (`torch.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(torch.FloatTensor)`, *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 ([RagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagModel)) model during decoding.
- **decoder_input_ids** (`torch.LongTensor` 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(torch.FloatTensor))`) --
  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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagTokenForGeneration)) model during decoding.
- **doc_scores** (`torch.FloatTensor` 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** (`torch.LongTensor` 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 `__call__()` context_attention_mask
  (`torch.LongTensor` 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 `__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.
- **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.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.rag.modeling_rag.RetrievAugLMOutput](/docs/transformers/pr_15592/en/model_doc/rag#transformers.models.rag.modeling_rag.RetrievAugLMOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.rag.modeling_rag.RetrievAugLMOutput](/docs/transformers/pr_15592/en/model_doc/rag#transformers.models.rag.modeling_rag.RetrievAugLMOutput) or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) and inputs.

- **logits** (`torch.FloatTensor` 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.
- **doc_scores** (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`) -- Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
  `question_encoder_last_hidden_state`.
- **past_key_values** (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `torch.FloatTensor` 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.
- **retrieved_doc_embeds** (`torch.FloatTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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.
- **generator_cross_attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</retdesc></docstring>
The [RagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagModel) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

```python
>>> from transformers import RagTokenizer, RagRetriever, RagModel
>>> import torch

>>> tokenizer = RagTokenizer.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 = RagModel.from_pretrained("facebook/rag-token-base", retriever=retriever)

>>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
>>> outputs = model(input_ids=inputs["input_ids"])
```

</div></div>

<h2 id="transformers.RagSequenceForGeneration">RagSequenceForGeneration</h2>

<div class="docstring">

<docstring><name>class transformers.RagSequenceForGeneration</name><anchor>transformers.RagSequenceForGeneration</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L738</source><parameters>[{"name": "config", "val": ": typing.Optional[transformers.configuration_utils.PretrainedConfig] = None"}, {"name": "question_encoder", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "generator", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "retriever", "val": ": typing.Optional = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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
  [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.
- **question_encoder** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)) --
  An encoder model compatible with the faiss index encapsulated by the `retriever`.
- **generator** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)) --
  A seq2seq model used as the generator in the RAG architecture.
- **retriever** ([RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever)) --
  A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.</paramsdesc><paramgroups>0</paramgroups></docstring>
The [RagSequenceForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagSequenceForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>

A RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.


RAG is a seq2seq 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 [DPRQuestionEncoder](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.DPRQuestionEncoder), and the generator can be
any *seq2seq* model, preferably [BartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.BartForConditionalGeneration).

The model can be initialized with a [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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 [DPRQuestionEncoder](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.DPRQuestionEncoder) as the `question_encoder` and [BartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.BartForConditionalGeneration) or
[T5ForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/t5#transformers.T5ForConditionalGeneration) as the `generator`.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel). 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 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.






<div class="docstring">
<docstring><name>forward</name><anchor>transformers.RagSequenceForGeneration.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L767</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_retrieved", "val": " = None"}, {"name": "exclude_bos_score", "val": " = None"}, {"name": "reduce_loss", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary. [RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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.

  [What are input IDs?](../glossary#input-ids)
- **attention_mask** (`torch.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(torch.FloatTensor)`, *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 ([RagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagModel)) model during decoding.
- **decoder_input_ids** (`torch.LongTensor` 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(torch.FloatTensor))`) --
  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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagTokenForGeneration)) model during decoding.
- **doc_scores** (`torch.FloatTensor` 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** (`torch.LongTensor` 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 `__call__()` context_attention_mask
  (`torch.LongTensor` 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 `__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.
- **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.

- **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.
- **reduce_loss** (`bool`, *optional*) --
  Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`
  operation.
- **kwargs** (`Dict[str, any]`, optional, defaults to *&amp;lcub;}*) --
  Legacy dictionary, which is required so that model can use *generate()* function.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput](/docs/transformers/pr_15592/en/model_doc/rag#transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput](/docs/transformers/pr_15592/en/model_doc/rag#transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput) or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss.
- **logits** (`torch.FloatTensor` 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.
- **doc_scores** (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`) -- Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
  `question_encoder_last_hidden_state`.
- **past_key_values** (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `torch.FloatTensor` 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.
- **retrieved_doc_embeds** (`torch.FloatTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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.
- **generator_cross_attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</retdesc></docstring>
The [RagSequenceForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagSequenceForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

```python
>>> from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration
>>> import torch

>>> tokenizer = RagTokenizer.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 = RagSequenceForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)

>>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
>>> with tokenizer.as_target_tokenizer():
...     targets = tokenizer("In Paris, there are 10 million people.", return_tensors="pt")
>>> input_ids = inputs["input_ids"]
>>> labels = targets["input_ids"]
>>> outputs = model(input_ids=input_ids, labels=labels)

>>> # or use retriever separately
>>> model = RagSequenceForGeneration.from_pretrained("facebook/rag-sequence-nq", use_dummy_dataset=True)
>>> # 1. Encode
>>> question_hidden_states = model.question_encoder(input_ids)[0]
>>> # 2. Retrieve
>>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors="pt")
>>> doc_scores = torch.bmm(
...     question_hidden_states.unsqueeze(1), docs_dict["retrieved_doc_embeds"].float().transpose(1, 2)
>>> ).squeeze(1)
>>> # 3. Forward to generator
>>> outputs = model(
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
...     decoder_input_ids=labels,
... )
```

</div>
<div class="docstring">
<docstring><name>generate</name><anchor>transformers.RagSequenceForGeneration.generate</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L909</source><parameters>[{"name": "input_ids", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "attention_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "do_deduplication", "val": " = None"}, {"name": "num_return_sequences", "val": " = None"}, {"name": "num_beams", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "**model_kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` 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** (`torch.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** (`torch.LongTensor` 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** (`torch.LongTensor` 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 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
  `__call__()`
- **doc_scores** (`torch.FloatTensor` 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 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 `__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 `[generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.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 --
  Additional kwargs will be passed to [generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate).</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`</rettype><retdesc>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`.</retdesc></docstring>

Implements RAG sequence "thorough" decoding. Read the [generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate)`
documentation for more information on how to set other generate input parameters.








</div></div>

<h2 id="transformers.RagTokenForGeneration">RagTokenForGeneration</h2>

<div class="docstring">

<docstring><name>class transformers.RagTokenForGeneration</name><anchor>transformers.RagTokenForGeneration</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L1135</source><parameters>[{"name": "config", "val": ": typing.Optional[transformers.configuration_utils.PretrainedConfig] = None"}, {"name": "question_encoder", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "generator", "val": ": typing.Optional[transformers.modeling_utils.PreTrainedModel] = None"}, {"name": "retriever", "val": ": typing.Optional = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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
  [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.
- **question_encoder** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)) --
  An encoder model compatible with the faiss index encapsulated by the `retriever`.
- **generator** ([PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel)) --
  A seq2seq model used as the generator in the RAG architecture.
- **retriever** ([RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever)) --
  A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.</paramsdesc><paramgroups>0</paramgroups></docstring>
The [RagTokenForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagTokenForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>

A RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass.


RAG is a seq2seq 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 [DPRQuestionEncoder](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.DPRQuestionEncoder), and the generator can be
any *seq2seq* model, preferably [BartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.BartForConditionalGeneration).

The model can be initialized with a [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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 [DPRQuestionEncoder](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.DPRQuestionEncoder) as the `question_encoder` and [BartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.BartForConditionalGeneration) or
[T5ForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/t5#transformers.T5ForConditionalGeneration) as the `generator`.

This model inherits from [PreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.PreTrainedModel). 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 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.






<div class="docstring">
<docstring><name>forward</name><anchor>transformers.RagTokenForGeneration.forward</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L1234</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_retrieved", "val": " = None"}, {"name": "do_marginalize", "val": " = None"}, {"name": "reduce_loss", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` of shape `(batch_size, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary. [RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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.

  [What are input IDs?](../glossary#input-ids)
- **attention_mask** (`torch.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(torch.FloatTensor)`, *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 ([RagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagModel)) model during decoding.
- **decoder_input_ids** (`torch.LongTensor` 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(torch.FloatTensor))`) --
  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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagTokenForGeneration)) model during decoding.
- **doc_scores** (`torch.FloatTensor` 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** (`torch.LongTensor` 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 `__call__()` context_attention_mask
  (`torch.LongTensor` 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 `__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.
- **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.

- **do_marginalize** (`bool`, *optional*) --
  If `True`, the logits are marginalized over all documents by making use of
  `torch.nn.functional.log_softmax`.
- **reduce_loss** (`bool`, *optional*) --
  Only relevant if `labels` is passed. If `True`, the NLL loss is reduced using the `torch.Tensor.sum`
  operation.
- **kwargs** (`Dict[str, any]`, optional, defaults to *&amp;lcub;}*) --
  Legacy dictionary, which is required so that model can use *generate()* function.</paramsdesc><paramgroups>0</paramgroups><rettype>[transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput](/docs/transformers/pr_15592/en/model_doc/rag#transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput) or `tuple(torch.FloatTensor)`</rettype><retdesc>A [transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput](/docs/transformers/pr_15592/en/model_doc/rag#transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput) or a tuple of
`torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
elements depending on the configuration ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) and inputs.

- **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss.
- **logits** (`torch.FloatTensor` 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.
- **doc_scores** (`torch.FloatTensor` of shape `(batch_size, config.n_docs)`) -- Score between each retrieved document embeddings (see `retrieved_doc_embeds`) and
  `question_encoder_last_hidden_state`.
- **past_key_values** (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- List of `torch.FloatTensor` 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.
- **retrieved_doc_embeds** (`torch.FloatTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.LongTensor` 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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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** (`torch.FloatTensor` 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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (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(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (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.
- **generator_cross_attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  sequence_length)`.

  Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the
  weighted average in the cross-attention heads.</retdesc></docstring>
The [RagTokenForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagTokenForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

```python
>>> from transformers import RagTokenizer, RagRetriever, RagTokenForGeneration
>>> import torch

>>> tokenizer = RagTokenizer.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 = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", retriever=retriever)

>>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
>>> with tokenizer.as_target_tokenizer():
...     targets = tokenizer("In Paris, there are 10 million people.", return_tensors="pt")
>>> input_ids = inputs["input_ids"]
>>> labels = targets["input_ids"]
>>> outputs = model(input_ids=input_ids, labels=labels)

>>> # or use retriever separately
>>> model = RagTokenForGeneration.from_pretrained("facebook/rag-token-nq", use_dummy_dataset=True)
>>> # 1. Encode
>>> question_hidden_states = model.question_encoder(input_ids)[0]
>>> # 2. Retrieve
>>> docs_dict = retriever(input_ids.numpy(), question_hidden_states.detach().numpy(), return_tensors="pt")
>>> doc_scores = torch.bmm(
...     question_hidden_states.unsqueeze(1), docs_dict["retrieved_doc_embeds"].float().transpose(1, 2)
>>> ).squeeze(1)
>>> # 3. Forward to generator
>>> outputs = model(
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
...     decoder_input_ids=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)
```

</div>
<div class="docstring">
<docstring><name>generate</name><anchor>transformers.RagTokenForGeneration.generate</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_rag.py#L1376</source><parameters>[{"name": "input_ids", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "attention_mask", "val": ": typing.Optional[torch.LongTensor] = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "max_length", "val": " = None"}, {"name": "min_length", "val": " = None"}, {"name": "early_stopping", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "num_beams", "val": " = None"}, {"name": "num_beam_groups", "val": " = None"}, {"name": "diversity_penalty", "val": " = None"}, {"name": "bos_token_id", "val": " = None"}, {"name": "pad_token_id", "val": " = None"}, {"name": "eos_token_id", "val": " = None"}, {"name": "length_penalty", "val": " = None"}, {"name": "no_repeat_ngram_size", "val": " = None"}, {"name": "encoder_no_repeat_ngram_size", "val": " = None"}, {"name": "repetition_penalty", "val": " = None"}, {"name": "bad_words_ids", "val": " = None"}, {"name": "num_return_sequences", "val": " = None"}, {"name": "decoder_start_token_id", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "prefix_allowed_tokens_fn", "val": ": typing.Callable[[int, torch.Tensor], typing.List[int]] = None"}, {"name": "logits_processor", "val": ": typing.Optional[transformers.generation_logits_process.LogitsProcessorList] = []"}, {"name": "stopping_criteria", "val": ": typing.Optional[transformers.generation_stopping_criteria.StoppingCriteriaList] = []"}, {"name": "forced_bos_token_id", "val": ": typing.Optional[int] = None"}, {"name": "forced_eos_token_id", "val": ": typing.Optional[int] = None"}, {"name": "remove_invalid_values", "val": ": typing.Optional[bool] = None"}, {"name": "**model_kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`torch.LongTensor` 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** (`torch.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** (`torch.LongTensor` 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 `__call__()`
- **context_attention_mask** (`torch.LongTensor` 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 `__call__()`
- **doc_scores** (`torch.FloatTensor` 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 `__call__()`
- **max_length** (`int`, *optional*, defaults to 20) --
  The maximum length of the sequence to be generated.
- **min_length** (`int`, *optional*, defaults to 10) --
  The minimum length of the sequence to be generated.
- **early_stopping** (`bool`, *optional*, defaults to `False`) --
  Whether or not to stop the beam search when at least `num_beams` sentences are finished per batch or
  not.
  use_cache -- (`bool`, *optional*, defaults to `True`):
  Whether or not the model should use the past last key/values attentions (if applicable to the model) to
  speed up decoding.
- **pad_token_id** (`int`, *optional*) --
  The id of the *padding* token.
- **bos_token_id** (`int`, *optional*) --
  The id of the *beginning-of-sequence* token.
- **eos_token_id** (`int`, *optional*) --
  The id of the *end-of-sequence* token.
- **length_penalty** (`float`, *optional*, defaults to 1.0) --
  Exponential penalty to the length. 1.0 means no penalty.

  Set to values &amp;lt; 1.0 in order to encourage the model to generate shorter sequences, to a value > 1.0 in
  order to encourage the model to produce longer sequences.
- **no_repeat_ngram_size** (`int`, *optional*, defaults to 0) --
  If set to int > 0, all ngrams of that size can only occur once.
- **encoder_no_repeat_ngram_size** (`int`, *optional*, defaults to 0) --
  If set to int > 0, all ngrams of that size that occur in the `encoder_input_ids` cannot occur in the
  `decoder_input_ids`.
- **bad_words_ids(`List[int]`,** *optional*) --
  List of token ids that are not allowed to be generated. In order to get the tokens of the words that
  should not appear in the generated text, use `tokenizer.encode(bad_word, add_prefix_space=True)`.
- **num_beams** (`int`, *optional*, defaults to 1) --
  Number of beams for beam search. 1 means no beam search.
- **num_beam_groups** (`int`, *optional*, defaults to 1) --
  Number of groups to divide `num_beams` into in order to ensure diversity among different groups of
  beams. [this paper](https://arxiv.org/pdf/1610.02424.pdf) for more details.
- **diversity_penalty** (`float`, *optional*, defaults to 0.0) --
  This value is subtracted from a beam's score if it generates a token same as any beam from other group
  at a particular time. Note that `diversity_penalty` is only effective if `group beam search` is
  enabled.
- **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 `[generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate) function,
  where we set `num_return_sequences` to `num_beams`. decoder_start_token_id (`int`, *optional*): If an
  encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
- **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.
  prefix_allowed_tokens_fn -- (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
  If provided, this function constraints the beam search to allowed tokens only at each step. If not
  provided no constraint is applied. This function takes 2 arguments `inputs_ids` and the batch ID
  `batch_id`. It has to return a list with the allowed tokens for the next generation step conditioned on
  the previously generated tokens `inputs_ids` and the batch ID `batch_id`. This argument is useful for
  constrained generation conditioned on the prefix, as described in [Autoregressive Entity
  Retrieval](https://arxiv.org/abs/2010.00904).
- **logits_processor** (`LogitsProcessorList`, *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.
- **stopping_criteria** (`StoppingCriteriaList`, *optional*) --
  Custom stopping criteria that complement the default stopping criteria built from arguments and a
  model's config. If a stopping criteria is passed that is already created with the arguments or a
  model's config an error is thrown.
- **forced_bos_token_id** (`int`, *optional*) --
  The id of the token to force as the first generated token after the `decoder_start_token_id`. Useful
  for multilingual models like [mBART](../model_doc/mbart) where the first generated token needs to be
  the target language token.
- **forced_eos_token_id** (`int`, *optional*) --
  The id of the token to force as the last generated token when `max_length` is reached.
- **remove_invalid_values** (`bool`, *optional*) --
  Whether to remove possible *nan* and *inf* outputs of the model to prevent the generation method to
  crash. Note that using `remove_invalid_values` can slow down generation.</paramsdesc><paramgroups>0</paramgroups><rettype>`torch.LongTensor` of shape `(batch_size * num_return_sequences, sequence_length)`</rettype><retdesc>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`.</retdesc></docstring>

Implements RAG token decoding.








</div></div>

<h2 id="transformers.TFRagModel">TFRagModel</h2>

<div class="docstring">

<docstring><name>class transformers.TFRagModel</name><anchor>transformers.TFRagModel</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L485</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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
  [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.
- **question_encoder** ([TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel)) --
  An encoder model compatible with the faiss index encapsulated by the `retriever`.
- **generator** ([TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel)) --
  A seq2seq model used as the generator in the RAG architecture.
- **retriever** ([RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever)) --
  A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.</paramsdesc><paramgroups>0</paramgroups></docstring>
The [TFRagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.TFRagModel) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>


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](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.TFDPRQuestionEncoder), and the generator can be
any *seq2seq* model, preferably [TFBartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.TFBartForConditionalGeneration).

The model can be initialized with a [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.TFDPRQuestionEncoder) as the `question_encoder` and [TFBartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.TFBartForConditionalGeneration)
as the `generator`.

This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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 [tf.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.





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFRagModel.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L536</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_retrieved", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`tf.Tensor` of shape `(batch_size, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary. [RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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 `__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 `__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.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput`or `tuple(tf.Tensor)`</rettype><retdesc>A `transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput`or a tuple of `tf.Tensor` (if
`return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the
configuration ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) and inputs.

- **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.</retdesc></docstring>
The [TFRagModel](/docs/transformers/pr_15592/en/model_doc/rag#transformers.TFRagModel) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

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

>>> tokenizer = RagTokenizer.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)
```

</div></div>

<h2 id="transformers.TFRagSequenceForGeneration">TFRagSequenceForGeneration</h2>

<div class="docstring">

<docstring><name>class transformers.TFRagSequenceForGeneration</name><anchor>transformers.TFRagSequenceForGeneration</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L1470</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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
  [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.
- **question_encoder** ([TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel)) --
  An encoder model compatible with the faiss index encapsulated by the `retriever`.
- **generator** ([TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel)) --
  A seq2seq model used as the generator in the RAG architecture.
- **retriever** ([RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever)) --
  A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.</paramsdesc><paramgroups>0</paramgroups></docstring>
The [TFRagSequenceForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.TFRagSequenceForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>

A TF RAG-sequence model implementation. It performs RAG-sequence specific marginalization in the forward pass.


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](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.TFDPRQuestionEncoder), and the generator can be
any *seq2seq* model, preferably [TFBartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.TFBartForConditionalGeneration).

The model can be initialized with a [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.TFDPRQuestionEncoder) as the `question_encoder` and [TFBartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.TFBartForConditionalGeneration)
as the `generator`.

This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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 [tf.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.





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFRagSequenceForGeneration.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L1518</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_retrieved", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "exclude_bos_score", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "reduce_loss", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`tf.Tensor` of shape `(batch_size, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary. [RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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 `__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 `__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.

- **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 *&amp;lcub;}*) --
  Legacy dictionary, which is required so that model can use *generate()* function.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput`or `tuple(tf.Tensor)`</rettype><retdesc>A `transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput`or a tuple of `tf.Tensor` (if
`return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the
configuration ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) and inputs.

- **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.</retdesc></docstring>
The [TFRagSequenceForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.TFRagSequenceForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

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

>>> tokenizer = RagTokenizer.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)
```

</div>
<div class="docstring">
<docstring><name>generate</name><anchor>transformers.TFRagSequenceForGeneration.generate</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L1776</source><parameters>[{"name": "input_ids", "val": ": typing.Optional[tensorflow.python.framework.ops.Tensor] = None"}, {"name": "attention_mask", "val": ": typing.Optional[tensorflow.python.framework.ops.Tensor] = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "do_deduplication", "val": " = None"}, {"name": "num_return_sequences", "val": " = None"}, {"name": "num_beams", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "**model_kwargs", "val": ""}]</parameters><paramsdesc>- **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 `__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 `__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 `[generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.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 --
  Additional kwargs will be passed to [generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate)</paramsdesc><paramgroups>0</paramgroups><rettype>`tf.Tensor` of shape `(batch_size * num_return_sequences, sequence_length)`</rettype><retdesc>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`.</retdesc></docstring>

Implements RAG sequence "thorough" decoding. Read the [generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate)`
documentation for more information on how to set other generate input parameters








</div></div>

<h2 id="transformers.TFRagTokenForGeneration">TFRagTokenForGeneration</h2>

<div class="docstring">

<docstring><name>class transformers.TFRagTokenForGeneration</name><anchor>transformers.TFRagTokenForGeneration</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L753</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **config** ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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
  [from_pretrained()](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel.from_pretrained) method to load the model weights.
- **question_encoder** ([TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel)) --
  An encoder model compatible with the faiss index encapsulated by the `retriever`.
- **generator** ([TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.TFPreTrainedModel)) --
  A seq2seq model used as the generator in the RAG architecture.
- **retriever** ([RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagRetriever)) --
  A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.</paramsdesc><paramgroups>0</paramgroups></docstring>
The [TFRagTokenForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.TFRagTokenForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>

A TF RAG-token model implementation. It performs RAG-token specific marginalization in the forward pass.


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](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.TFDPRQuestionEncoder), and the generator can be
any *seq2seq* model, preferably [TFBartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.TFBartForConditionalGeneration).

The model can be initialized with a [RagRetriever](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/dpr#transformers.TFDPRQuestionEncoder) as the `question_encoder` and [TFBartForConditionalGeneration](/docs/transformers/pr_15592/en/model_doc/bart#transformers.TFBartForConditionalGeneration)
as the `generator`.

This model inherits from [TFPreTrainedModel](/docs/transformers/pr_15592/en/main_classes/model#transformers.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 [tf.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.





<div class="docstring">
<docstring><name>call</name><anchor>transformers.TFRagTokenForGeneration.call</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L900</source><parameters>[{"name": "input_ids", "val": " = None"}, {"name": "attention_mask", "val": " = None"}, {"name": "decoder_input_ids", "val": " = None"}, {"name": "decoder_attention_mask", "val": " = None"}, {"name": "encoder_outputs", "val": " = None"}, {"name": "past_key_values", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "output_retrieved", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "do_marginalize", "val": " = None"}, {"name": "labels", "val": " = None"}, {"name": "reduce_loss", "val": " = None"}, {"name": "return_dict", "val": " = None"}, {"name": "training", "val": " = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **input_ids** (`tf.Tensor` of shape `(batch_size, sequence_length)`) --
  Indices of input sequence tokens in the vocabulary. [RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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](/docs/transformers/pr_15592/en/model_doc/rag#transformers.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 `__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 `__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.

- **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 *&amp;lcub;}*) --
  Legacy dictionary, which is required so that model can use *generate()* function.</paramsdesc><paramgroups>0</paramgroups><rettype>`transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput`or `tuple(tf.Tensor)`</rettype><retdesc>A `transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput`or a tuple of `tf.Tensor` (if
`return_dict=False` is passed or when `config.return_dict=False`) comprising various elements depending on the
configuration ([RagConfig](/docs/transformers/pr_15592/en/model_doc/rag#transformers.RagConfig)) and inputs.

- **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.</retdesc></docstring>
The [TFRagTokenForGeneration](/docs/transformers/pr_15592/en/model_doc/rag#transformers.TFRagTokenForGeneration) forward method, overrides the `__call__` special method.

<Tip>

Although the recipe for forward pass needs to be defined within this function, one should call the `Module`
instance afterwards instead of this since the former takes care of running the pre and post processing steps while
the latter silently ignores them.

</Tip>







Example:

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

>>> tokenizer = RagTokenizer.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)
```

</div>
<div class="docstring">
<docstring><name>generate</name><anchor>transformers.TFRagTokenForGeneration.generate</anchor><source>https://github.com/huggingface/transformers/blob/pr_15592/src/transformers/models/rag/modeling_tf_rag.py#L1079</source><parameters>[{"name": "input_ids", "val": ": typing.Optional[tensorflow.python.framework.ops.Tensor] = None"}, {"name": "attention_mask", "val": ": typing.Optional[tensorflow.python.framework.ops.Tensor] = None"}, {"name": "context_input_ids", "val": " = None"}, {"name": "context_attention_mask", "val": " = None"}, {"name": "doc_scores", "val": " = None"}, {"name": "max_length", "val": " = None"}, {"name": "min_length", "val": " = None"}, {"name": "early_stopping", "val": " = None"}, {"name": "use_cache", "val": " = None"}, {"name": "num_beams", "val": " = None"}, {"name": "bos_token_id", "val": " = None"}, {"name": "pad_token_id", "val": " = None"}, {"name": "eos_token_id", "val": " = None"}, {"name": "length_penalty", "val": " = None"}, {"name": "no_repeat_ngram_size", "val": " = None"}, {"name": "bad_words_ids", "val": " = None"}, {"name": "num_return_sequences", "val": " = None"}, {"name": "decoder_start_token_id", "val": " = None"}, {"name": "n_docs", "val": " = None"}, {"name": "output_scores", "val": " = None"}, {"name": "output_attentions", "val": " = None"}, {"name": "output_hidden_states", "val": " = None"}, {"name": "return_dict_in_generate", "val": " = None"}, {"name": "**model_kwargs", "val": ""}]</parameters><paramsdesc>- **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 `__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 `__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 `__call__()`
- **max_length** (`int`, *optional*, defaults to 20) --
  The maximum length of the sequence to be generated.
- **min_length** (`int`, *optional*, defaults to 10) --
  The minimum length of the sequence to be generated.
- **early_stopping** (`bool`, *optional*, defaults to `False`) --
  Whether or not to stop the beam search when at least `num_beams` sentences are finished per batch or
  not.
  use_cache -- (`bool`, *optional*, defaults to `True`):
  Whether or not the model should use the past last key/values attentions (if applicable to the model) to
  speed up decoding.
- **pad_token_id** (`int`, *optional*) --
  The id of the *padding* token.
- **bos_token_id** (`int`, *optional*) --
  The id of the *beginning-of-sequence* token.
- **eos_token_id** (`int`, *optional*) --
  The id of the *end-of-sequence* token.
- **length_penalty** (`float`, *optional*, defaults to 1.0) --
  Exponential penalty to the length. 1.0 means no penalty.

  Set to values &amp;lt; 1.0 in order to encourage the model to generate shorter sequences, to a value > 1.0 in
  order to encourage the model to produce longer sequences.
- **no_repeat_ngram_size** (`int`, *optional*, defaults to 0) --
  If set to int > 0, all ngrams of that size can only occur once.
- **bad_words_ids(`List[int]`,** *optional*) --
  List of token ids that are not allowed to be generated. In order to get the tokens of the words that
  should not appear in the generated text, use `tokenizer.encode(bad_word, add_prefix_space=True)`.
- **num_beams** (`int`, *optional*, defaults to 1) --
  Number of beams for beam search. 1 means no beam search.
- **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 `[generate()](/docs/transformers/pr_15592/en/main_classes/model#transformers.generation_utils.GenerationMixin.generate) function,
  where we set `num_return_sequences` to `num_beams`. decoder_start_token_id (`int`, *optional*): If an
  encoder-decoder model starts decoding with a different token than *bos*, the id of that token.
- **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.
- **output_attentions** (`bool`, *optional*, defaults to `False`) --
  Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  returned tensors for more details.
- **output_hidden_states** (`bool`, *optional*, defaults to `False`) --
  Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  for more details.
- **output_scores** (`bool`, *optional*, defaults to `False`) --
  Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
- **return_dict_in_generate** (`bool`, *optional*, defaults to `False`) --
  Whether or not to return a [ModelOutput](/docs/transformers/pr_15592/en/main_classes/output#transformers.file_utils.ModelOutput) instead of a plain tuple.
  model_specific_kwargs --
  Additional model specific kwargs will be forwarded to the `forward` function of the model.</paramsdesc><paramgroups>0</paramgroups><rettype>`tf.Tensor` of shape `(batch_size * num_return_sequences, sequence_length)`</rettype><retdesc>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`.</retdesc></docstring>

Implements TFRAG token decoding.








</div></div>
