RAGΒΆ
OverviewΒΆ
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 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.
RagConfigΒΆ
-
class
transformers.
RagConfig
(vocab_size=None, is_encoder_decoder=True, prefix=None, bos_token_id=None, pad_token_id=None, eos_token_id=None, decoder_start_token_id=None, title_sep=' / ', doc_sep=' // ', n_docs=5, max_combined_length=300, retrieval_vector_size=768, retrieval_batch_size=8, dataset='wiki_dpr', dataset_split='train', index_name='compressed', index_path=None, passages_path=None, use_dummy_dataset=False, reduce_loss=False, label_smoothing=0.0, do_deduplication=True, exclude_bos_score=False, do_marginalize=False, output_retrieved=False, use_cache=True, forced_eos_token_id=None, **kwargs)[source]ΒΆ RagConfig
stores the configuration of a RagModel. Configuration objects inherit fromPretrainedConfig
and can be used to control the model outputs. Read the documentation fromPretrainedConfig
for more information.- Parameters
title_sep (
str
, optional, defaults to" / "
) β Separator inserted between the title and the text of the retrieved document when callingRagRetriever
.doc_sep (
str
, optional, defaults to" // "
) β Separator inserted between the the text of the retrieved document and the original input when callingRagRetriever
.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 byRagRetriever
.retrieval_batch_size (
int
, optional, defaults to 8) β Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulatedRagRetriever
.dataset (
str
, optional, defaults to"wiki_dpr"
) β A dataset identifier of the indexed dataset in HuggingFace Datasets (list all available datasets and ids usingdatasets.list_datasets()
).dataset_split (
str
, optional, defaults to"train"
) β Which split of thedataset
to load.index_name (
str
, optional, defaults to"compressed"
) β The index name of the index associated with thedataset
. 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 usingLegacyIndex
use_dummy_dataset (
bool
, optional, defaults toFalse
) β Whether to load a βdummyβ variant of the dataset specified bydataset
.label_smoothing (
float
, optional, defaults to 0.0) β Only relevant ifreturn_loss
is set toTrue
. Controls theepsilon
parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed.do_marginalize (
bool
, optional, defaults toFalse
) β IfTrue
, the logits are marginalized over all documents by making use oftorch.nn.functional.log_softmax
.reduce_loss (
bool
, optional, defaults toFalse
) β Whether or not to reduce the NLL loss using thetorch.Tensor.sum
operation.do_deduplication (
bool
, optional, defaults toTrue
) β Whether or not to deduplicate the generations from different context documents for a given input. Has to be set toFalse
if used while training with distributed backend.exclude_bos_score (
bool
, optional, defaults toFalse
) β Whether or not to disregard the BOS token when computing the loss.output_retrieved (
bool
, optional, defaults toFalse
) β If set toTrue
,retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
are returned. See returned tensors for more detail.use_cache (
bool
, optional, defaults toTrue
) β 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 whenmax_length
is reached. Usually set toeos_token_id
.
-
classmethod
from_question_encoder_generator_configs
(question_encoder_config: transformers.configuration_utils.PretrainedConfig, generator_config: transformers.configuration_utils.PretrainedConfig, **kwargs) → transformers.configuration_utils.PretrainedConfig[source]ΒΆ Instantiate a
EncoderDecoderConfig
(or a derived class) from a pre-trained encoder model configuration and decoder model configuration.- Returns
An instance of a configuration object
- Return type
RagTokenizerΒΆ
Rag specific outputsΒΆ
-
class
transformers.models.rag.modeling_rag.
RetrievAugLMMarginOutput
(loss: Optional[torch.FloatTensor] = None, logits: torch.FloatTensor = None, doc_scores: torch.FloatTensor = None, past_key_values: Optional[List[torch.FloatTensor]] = None, retrieved_doc_embeds: Optional[torch.FloatTensor] = None, retrieved_doc_ids: Optional[torch.LongTensor] = None, context_input_ids: Optional[torch.LongTensor] = None, context_attention_mask: Optional[torch.LongTensor] = None, question_encoder_last_hidden_state: Optional[torch.FloatTensor] = None, question_enc_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, question_enc_attentions: Optional[Tuple[torch.FloatTensor]] = None, generator_enc_last_hidden_state: Optional[torch.FloatTensor] = None, generator_enc_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, generator_enc_attentions: Optional[Tuple[torch.FloatTensor]] = None, generator_dec_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, generator_dec_attentions: Optional[Tuple[torch.FloatTensor]] = None, generator_cross_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ Base class for retriever augmented marginalized models outputs.
- Parameters
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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 (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) βList of
torch.FloatTensor
of lengthconfig.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 withquestion_encoder_last_hidden_state
to compute thedoc_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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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.
-
class
transformers.models.rag.modeling_rag.
RetrievAugLMOutput
(logits: torch.FloatTensor = None, doc_scores: torch.FloatTensor = None, past_key_values: Optional[List[torch.FloatTensor]] = None, retrieved_doc_embeds: Optional[torch.FloatTensor] = None, retrieved_doc_ids: Optional[torch.LongTensor] = None, context_input_ids: Optional[torch.LongTensor] = None, context_attention_mask: Optional[torch.LongTensor] = None, question_encoder_last_hidden_state: Optional[torch.FloatTensor] = None, question_enc_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, question_enc_attentions: Optional[Tuple[torch.FloatTensor]] = None, generator_enc_last_hidden_state: Optional[torch.FloatTensor] = None, generator_enc_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, generator_enc_attentions: Optional[Tuple[torch.FloatTensor]] = None, generator_dec_hidden_states: Optional[Tuple[torch.FloatTensor]] = None, generator_dec_attentions: Optional[Tuple[torch.FloatTensor]] = None, generator_cross_attentions: Optional[Tuple[torch.FloatTensor]] = None)[source]ΒΆ - Parameters
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 (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) βList of
torch.FloatTensor
of lengthconfig.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 withquestion_encoder_last_hidden_state
to compute thedoc_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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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 whenoutput_hidden_states=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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 whenoutput_attentions=True
is passed or whenconfig.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.
RagRetrieverΒΆ
-
class
transformers.
RagRetriever
(config, question_encoder_tokenizer, generator_tokenizer, index=None, init_retrieval=True)[source]ΒΆ 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.
- Parameters
config (
RagConfig
) β The configuration of the RAG model this Retriever is used with. Contains parameters indicating whichIndex
to build. You can load your own custom dataset withconfig.index_name="custom"
or use a canonical one (default) from the datasets library withconfig.index_name="wiki_dpr"
for example.question_encoder_tokenizer (
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
) β 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
Examples:
>>> # 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')
-
postprocess_docs
(docs, input_strings, prefix, n_docs, return_tensors=None)[source]ΒΆ Postprocessing retrieved
docs
and combining them withinput_strings
.- Parameters
docs (
dict
) β Retrieved documents.input_strings (
str
) β Input strings decoded bypreprocess_query
.prefix (
str
) β Prefix added at the beginning of each input, typically used with T5-based models.
- Returns
a tuple consisting of two elements: contextualized
input_ids
and a compatibleattention_mask
.- Return type
tuple(tensors)
-
retrieve
(question_hidden_states: numpy.ndarray, n_docs: int) → Tuple[numpy.ndarray, List[dict]][source]ΒΆ Retrieves documents for specified
question_hidden_states
.- Parameters
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.
- Returns
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 indexdoc_dicts (
List[dict]
): Theretrieved_doc_embeds
examples per query.
- Return type
Tuple[np.ndarray, np.ndarray, List[dict]]
RagModelΒΆ
-
class
transformers.
RagModel
(config: Optional[transformers.configuration_utils.PretrainedConfig] = None, question_encoder: Optional[transformers.modeling_utils.PreTrainedModel] = None, generator: Optional[transformers.modeling_utils.PreTrainedModel] = None, retriever: Optional = None, **kwargs)[source]ΒΆ The
RagModel
forward method, overrides the__call__()
special method.Note
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.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
, and the generator can be any seq2seq model, preferablyBartForConditionalGeneration
.The model can be initialized with a
RagRetriever
for end-to-end generation or used in combination with the outputs of a retriever in multiple stepsβsee examples for more details. The model is compatible any autoencoding model as thequestion_encoder
and any seq2seq model with language model head as thegenerator
. It has been tested withDPRQuestionEncoder
as thequestion_encoder
andBartForConditionalGeneration
orT5ForConditionalGeneration
as thegenerator
.This model inherits from
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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
RagConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.question_encoder (
transformers.PreTrainedModel
) β An encoder model compatible with the faiss index encapsulated by theretriever
.generator (
transformers.PreTrainedModel
) β A seq2seq model used as the generator in the RAG architecture.retriever (
RagRetriever
) β A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
-
forward
(input_ids=None, attention_mask=None, encoder_outputs=None, decoder_input_ids=None, decoder_attention_mask=None, past_key_values=None, doc_scores=None, context_input_ids=None, context_attention_mask=None, use_cache=None, output_attentions=None, output_hidden_states=None, output_retrieved=None, n_docs=None)[source]ΒΆ The
RagModel
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
RagConfig
, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices.attention_mask (
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.
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
) 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 indecoder_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 (seeencoder_outputs
) andpast_key_values
of the underlying generator. Can be used to speed up decoding.past_key_values
are used in the (RagTokenForGeneration
) model during decoding.doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) β Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
doc_scores
has to be provided to the forward pass.doc_scores
can be computed viaquestion_encoder_last_hidden_state
andretrieved_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 toTrue
) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.output_retrieved (
bool
, optional) β Whether or not to return theretrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
. See returned tensors for more detail.n_docs (
int
, optional, defaults toconfig.n_docs
) β Number of documents to retrieve and/or number of documents for which to generate an answer.
- Returns
A
RetrievAugLMOutput
or a tuple oftorch.FloatTensor
(ifreturn_dict=False
is passed or whenconfig.return_dict=False
) comprising various elements depending on the configuration (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 (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.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 withquestion_encoder_last_hidden_state
to compute thedoc_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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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.
Example:
>>> 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"])
- Return type
RetrievAugLMOutput
ortuple(torch.FloatTensor)
RagSequenceForGenerationΒΆ
-
class
transformers.
RagSequenceForGeneration
(config: Optional[transformers.configuration_utils.PretrainedConfig] = None, question_encoder: Optional[transformers.modeling_utils.PreTrainedModel] = None, generator: Optional[transformers.modeling_utils.PreTrainedModel] = None, retriever: Optional = None, **kwargs)[source]ΒΆ The
RagSequenceForGeneration
forward method, overrides the__call__()
special method.Note
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.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
, and the generator can be any seq2seq model, preferablyBartForConditionalGeneration
.The model can be initialized with a
RagRetriever
for end-to-end generation or used in combination with the outputs of a retriever in multiple stepsβsee examples for more details. The model is compatible any autoencoding model as thequestion_encoder
and any seq2seq model with language model head as thegenerator
. It has been tested withDPRQuestionEncoder
as thequestion_encoder
andBartForConditionalGeneration
orT5ForConditionalGeneration
as thegenerator
.This model inherits from
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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
RagConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.question_encoder (
transformers.PreTrainedModel
) β An encoder model compatible with the faiss index encapsulated by theretriever
.generator (
transformers.PreTrainedModel
) β A seq2seq model used as the generator in the RAG architecture.retriever (
RagRetriever
) β A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
-
forward
(input_ids=None, attention_mask=None, encoder_outputs=None, decoder_input_ids=None, decoder_attention_mask=None, past_key_values=None, context_input_ids=None, context_attention_mask=None, doc_scores=None, use_cache=None, output_attentions=None, output_hidden_states=None, output_retrieved=None, exclude_bos_score=None, reduce_loss=None, labels=None, n_docs=None, **kwargs)[source]ΒΆ The
RagSequenceForGeneration
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
RagConfig
, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices.attention_mask (
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.
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
) 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 indecoder_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 (seeencoder_outputs
) andpast_key_values
of the underlying generator. Can be used to speed up decoding.past_key_values
are used in the (RagTokenForGeneration
) model during decoding.doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) β Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
doc_scores
has to be provided to the forward pass.doc_scores
can be computed viaquestion_encoder_last_hidden_state
andretrieved_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 toTrue
) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.output_retrieved (
bool
, optional) β Whether or not to return theretrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
. See returned tensors for more detail.n_docs (
int
, optional, defaults toconfig.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 iflabels
is passed. IfTrue
, the score of the BOS token is disregarded when computing the loss.reduce_loss (
bool
, optional) β Only relevant iflabels
is passed. IfTrue
, the NLL loss is reduced using thetorch.Tensor.sum
operation.kwargs (
Dict[str, any]
, optional, defaults to {}) β Legacy dictionary, which is required so that model can use generate() function.
- Returns
A
RetrievAugLMMarginOutput
or a tuple oftorch.FloatTensor
(ifreturn_dict=False
is passed or whenconfig.return_dict=False
) comprising various elements depending on the configuration (RagConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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 (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.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 withquestion_encoder_last_hidden_state
to compute thedoc_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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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.
Example:
>>> 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)
- Return type
RetrievAugLMMarginOutput
ortuple(torch.FloatTensor)
-
generate
(input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, context_input_ids=None, context_attention_mask=None, doc_scores=None, do_deduplication=None, num_return_sequences=None, num_beams=None, n_docs=None, **model_kwargs)[source]ΒΆ Implements RAG sequence βthoroughβ decoding. Read the
generate`()
documentation for more information on how to set other generate input parameters.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β The sequence used as a prompt for the generation. Ifinput_ids
is not passed, thencontext_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.
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
orinput_ids
is not given,context_input_ids
andcontext_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
) andquestion_encoder_last_hidden_state
.If the model is not initialized with a
retriever
orinput_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 toFalse
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 thegenerator
βs :func:`~transformers.generation_utils.GenerationMixin.generate` function, where we setnum_return_sequences
tonum_beams
.num_beams (
int
, optional, defaults to 1) β Number of beams for beam search. 1 means no beam search.n_docs (
int
, optional, defaults toconfig.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()
.
- Returns
The generated sequences. The second dimension (sequence length) is either equal to
max_length
or shorter if all batches finished early due to theeos_token_id
.- Return type
torch.LongTensor
of shape(batch_size * num_return_sequences, sequence_length)
RagTokenForGenerationΒΆ
-
class
transformers.
RagTokenForGeneration
(config: Optional[transformers.configuration_utils.PretrainedConfig] = None, question_encoder: Optional[transformers.modeling_utils.PreTrainedModel] = None, generator: Optional[transformers.modeling_utils.PreTrainedModel] = None, retriever: Optional = None, **kwargs)[source]ΒΆ The
RagTokenForGeneration
forward method, overrides the__call__()
special method.Note
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.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
, and the generator can be any seq2seq model, preferablyBartForConditionalGeneration
.The model can be initialized with a
RagRetriever
for end-to-end generation or used in combination with the outputs of a retriever in multiple stepsβsee examples for more details. The model is compatible any autoencoding model as thequestion_encoder
and any seq2seq model with language model head as thegenerator
. It has been tested withDPRQuestionEncoder
as thequestion_encoder
andBartForConditionalGeneration
orT5ForConditionalGeneration
as thegenerator
.This model inherits from
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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
- Parameters
config (
RagConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.question_encoder (
transformers.PreTrainedModel
) β An encoder model compatible with the faiss index encapsulated by theretriever
.generator (
transformers.PreTrainedModel
) β A seq2seq model used as the generator in the RAG architecture.retriever (
RagRetriever
) β A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
-
forward
(input_ids=None, attention_mask=None, encoder_outputs=None, decoder_input_ids=None, decoder_attention_mask=None, past_key_values=None, context_input_ids=None, context_attention_mask=None, doc_scores=None, use_cache=None, output_attentions=None, output_hidden_states=None, output_retrieved=None, do_marginalize=None, reduce_loss=None, labels=None, n_docs=None, **kwargs)[source]ΒΆ The
RagTokenForGeneration
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) βIndices of input sequence tokens in the vocabulary.
RagConfig
, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices.attention_mask (
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.
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
) 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 indecoder_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 (seeencoder_outputs
) andpast_key_values
of the underlying generator. Can be used to speed up decoding.past_key_values
are used in the (RagTokenForGeneration
) model during decoding.doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) β Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
doc_scores
has to be provided to the forward pass.doc_scores
can be computed viaquestion_encoder_last_hidden_state
andretrieved_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 toTrue
) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.output_retrieved (
bool
, optional) β Whether or not to return theretrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
. See returned tensors for more detail.n_docs (
int
, optional, defaults toconfig.n_docs
) β Number of documents to retrieve and/or number of documents for which to generate an answer.do_marginalize (
bool
, optional) β IfTrue
, the logits are marginalized over all documents by making use oftorch.nn.functional.log_softmax
.reduce_loss (
bool
, optional) β Only relevant iflabels
is passed. IfTrue
, the NLL loss is reduced using thetorch.Tensor.sum
operation.kwargs (
Dict[str, any]
, optional, defaults to {}) β Legacy dictionary, which is required so that model can use generate() function.
- Returns
A
RetrievAugLMMarginOutput
or a tuple oftorch.FloatTensor
(ifreturn_dict=False
is passed or whenconfig.return_dict=False
) comprising various elements depending on the configuration (RagConfig
) and inputs.loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
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 (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftorch.FloatTensor
of lengthconfig.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 withquestion_encoder_last_hidden_state
to compute thedoc_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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftorch.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.
Example:
>>> 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)
- Return type
RetrievAugLMMarginOutput
ortuple(torch.FloatTensor)
-
generate
(input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.LongTensor] = None, context_input_ids=None, context_attention_mask=None, doc_scores=None, max_length=None, min_length=None, early_stopping=None, use_cache=None, num_beams=None, num_beam_groups=None, diversity_penalty=None, bos_token_id=None, pad_token_id=None, eos_token_id=None, length_penalty=None, no_repeat_ngram_size=None, encoder_no_repeat_ngram_size=None, repetition_penalty=None, bad_words_ids=None, num_return_sequences=None, decoder_start_token_id=None, n_docs=None, prefix_allowed_tokens_fn: Callable[[int, torch.Tensor], List[int]] = None, forced_bos_token_id: Optional[int] = None, forced_eos_token_id: Optional[int] = None, remove_invalid_values: Optional[bool] = None, **model_kwargs)[source]ΒΆ Implements RAG token decoding.
- Parameters
input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) β The sequence used as a prompt for the generation. Ifinput_ids
is not passed, thencontext_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.
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
) andquestion_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 toFalse
) β Whether or not to stop the beam search when at leastnum_beams
sentences are finished per batch or not.use_cache β (
bool
, optional, defaults toTrue
): 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 < 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 theencoder_input_ids
cannot occur in thedecoder_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, usetokenizer.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 dividenum_beams
into in order to ensure diversity among different groups of beams. this paper 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 thatdiversity_penalty
is only effective ifgroup 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 thegenerator
βs :func:`~transformers.generation_utils.GenerationMixin.generate function, where we setnum_return_sequences
tonum_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 toconfig.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 argumentsinputs_ids
and the batch IDbatch_id
. It has to return a list with the allowed tokens for the next generation step conditioned on the previously generated tokensinputs_ids
and the batch IDbatch_id
. This argument is useful for constrained generation conditioned on the prefix, as described in Autoregressive Entity Retrieval.forced_bos_token_id (
int
, optional) β The id of the token to force as the first generated token after thedecoder_start_token_id
. Useful for multilingual models like 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 whenmax_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 usingremove_invalid_values
can slow down generation.
- Returns
The generated sequences. The second dimension (sequence_length) is either equal to
max_length
or shorter if all batches finished early due to theeos_token_id
.- Return type
torch.LongTensor
of shape(batch_size * num_return_sequences, sequence_length)
TFRagModelΒΆ
-
class
transformers.
TFRagModel
(*args, **kwargs)[source]ΒΆ The
TFRagModel
forward method, overrides the__call__()
special method.Note
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.RAG is a sequence-to-sequence model which encapsulates two core components: a question encoder and a generator. During a forward pass, we encode the input with the question encoder and pass it to the retriever to extract relevant context documents. The documents are then prepended to the input. Such contextualized inputs is passed to the generator.
The question encoder can be any autoencoding model, preferably
TFDPRQuestionEncoder
, and the generator can be any seq2seq model, preferablyTFBartForConditionalGeneration
.The model can be initialized with a
RagRetriever
for end-to-end generation or used in combination with the outputs of a retriever in multiple stepsβsee examples for more details. The model is compatible any autoencoding model as thequestion_encoder
and any seq2seq model with language model head as thegenerator
. It has been tested withTFDPRQuestionEncoder
as thequestion_encoder
andTFBartForConditionalGeneration
as thegenerator
.This model inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a Tensorflow 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.
- Parameters
config (
RagConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.question_encoder (
transformers.TFPreTrainedModel
) β An encoder model compatible with the faiss index encapsulated by theretriever
.generator (
transformers.TFPreTrainedModel
) β A seq2seq model used as the generator in the RAG architecture.retriever (
RagRetriever
) β A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
-
call
(input_ids=None, attention_mask=None, encoder_outputs=None, decoder_input_ids=None, decoder_attention_mask=None, past_key_values=None, doc_scores=None, context_input_ids=None, context_attention_mask=None, use_cache=None, output_attentions=None, output_hidden_states=None, output_retrieved=None, n_docs=None, return_dict=None, training=False, **kwargs)[source]ΒΆ The
TFRagModel
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) β Indices of input sequence tokens in the vocabulary.RagConfig
, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices.attention_mask (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) βMask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
encoder_outputs (
tuple(tuple(tf.Tensor)
, optional) βTuple consists of (
generator_enc_last_hidden_state
, optional:generator_enc_hidden_states
, optional:generator_enc_attentions
).generator_enc_last_hidden_state
of shape(batch_size, n_docs * sequence_length, hidden_size)
is a sequence of hidden-states at the output of the last layer of the generatorβs encoder.Used by the (
TFRagModel
) model during decoding.decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) β Provide for generation tasks. None by default, construct as per instructions for the generator model youβre using with your RAG instance.decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens indecoder_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 (seeencoder_outputs
) andpast_key_values
of the underlying generator. Can be used to speed up decoding.past_key_values
are used in the (RagTokenForGeneration
) model during decoding.doc_scores (
tf.Tensor
of shape(batch_size, config.n_docs)
) β Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
doc_scores
has to be provided to the forward pass.doc_scores
can be computed viaquestion_encoder_last_hidden_state
andretrieved_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 toTrue
) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.output_retrieved (
bool
, optional) β Whether or not to return theretrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
. See returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aTFRetrievAugLMOutput
instead of a plain tuple.n_docs (
int
, optional, defaults toconfig.n_docs
) β Number of documents to retrieve and/or number of documents for which to generate an answer.
- Returns
A
TFRetrievAugLMOutput
or a tuple oftf.Tensor
(ifreturn_dict=False
is passed or whenconfig.return_dict=False
) comprising various elements depending on the configuration (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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftf.Tensor
of lengthconfig.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 (seeretrieved_doc_embeds
) andquestion_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 withquestion_encoder_last_hidden_state
to compute thedoc_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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
Example:
>>> 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 = 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)
- Return type
TFRetrievAugLMOutput
ortuple(tf.Tensor)
TFRagSequenceForGenerationΒΆ
-
class
transformers.
TFRagSequenceForGeneration
(*args, **kwargs)[source]ΒΆ The
TFRagSequenceForGeneration
forward method, overrides the__call__()
special method.Note
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.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
, and the generator can be any seq2seq model, preferablyTFBartForConditionalGeneration
.The model can be initialized with a
RagRetriever
for end-to-end generation or used in combination with the outputs of a retriever in multiple stepsβsee examples for more details. The model is compatible any autoencoding model as thequestion_encoder
and any seq2seq model with language model head as thegenerator
. It has been tested withTFDPRQuestionEncoder
as thequestion_encoder
andTFBartForConditionalGeneration
as thegenerator
.This model inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a Tensorflow 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.
- Parameters
config (
RagConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.question_encoder (
transformers.TFPreTrainedModel
) β An encoder model compatible with the faiss index encapsulated by theretriever
.generator (
transformers.TFPreTrainedModel
) β A seq2seq model used as the generator in the RAG architecture.retriever (
RagRetriever
) β A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
-
call
(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, encoder_outputs=None, past_key_values=None, doc_scores=None, context_input_ids=None, context_attention_mask=None, use_cache=None, output_attentions=None, output_hidden_states=None, output_retrieved=None, n_docs=None, exclude_bos_score=None, labels=None, reduce_loss=None, return_dict=None, training=False, **kwargs)[source]ΒΆ The
TFRagSequenceForGeneration
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) β Indices of input sequence tokens in the vocabulary.RagConfig
, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices.attention_mask (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) βMask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
encoder_outputs (
tuple(tuple(tf.Tensor)
, optional) βTuple consists of (
generator_enc_last_hidden_state
, optional:generator_enc_hidden_states
, optional:generator_enc_attentions
).generator_enc_last_hidden_state
of shape(batch_size, n_docs * sequence_length, hidden_size)
is a sequence of hidden-states at the output of the last layer of the generatorβs encoder.Used by the (
TFRagModel
) model during decoding.decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) β Provide for generation tasks. None by default, construct as per instructions for the generator model youβre using with your RAG instance.decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens indecoder_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 (seeencoder_outputs
) andpast_key_values
of the underlying generator. Can be used to speed up decoding.past_key_values
are used in the (RagTokenForGeneration
) model during decoding.doc_scores (
tf.Tensor
of shape(batch_size, config.n_docs)
) β Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
doc_scores
has to be provided to the forward pass.doc_scores
can be computed viaquestion_encoder_last_hidden_state
andretrieved_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 toTrue
) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.output_retrieved (
bool
, optional) β Whether or not to return theretrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
. See returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aTFRetrievAugLMOutput
instead of a plain tuple.n_docs (
int
, optional, defaults toconfig.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 iflabels
is passed. IfTrue
, the score of the BOS token is disregarded when computing the loss.labels (
tf.Tensor
ornp.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 iflabels
is passed. IfTrue
, the NLL loss is reduced using thetf.Tensor.sum
operation.kwargs (
Dict[str, any]
, optional, defaults to {}) β Legacy dictionary, which is required so that model can use generate() function.
- Returns
A
TFRetrievAugLMMarginOutput
or a tuple oftf.Tensor
(ifreturn_dict=False
is passed or whenconfig.return_dict=False
) comprising various elements depending on the configuration (RagConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftf.Tensor
of lengthconfig.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 (seeretrieved_doc_embeds
) andquestion_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 withquestion_encoder_last_hidden_state
to compute thedoc_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 :obj:`(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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
Example:
>>> 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 = TFRagRagSequenceForGeneration.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)
- Return type
TFRetrievAugLMMarginOutput
ortuple(tf.Tensor)
-
generate
(input_ids: Optional[tensorflow.python.framework.ops.Tensor] = None, attention_mask: Optional[tensorflow.python.framework.ops.Tensor] = None, context_input_ids=None, context_attention_mask=None, doc_scores=None, do_deduplication=None, num_return_sequences=None, num_beams=None, n_docs=None, **model_kwargs)[source]ΒΆ Implements RAG sequence βthoroughβ decoding. Read the
generate`()
documentation for more information on how to set other generate input parameters- Parameters
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) β The sequence used as a prompt for the generation. Ifinput_ids
is not passed, thencontext_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?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 encoderinput_ids
by the retriever. If the model has is not initialized with aretriever
orinput_ids
is not given,context_input_ids
andcontext_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 (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
orinput_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 toFalse
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 thegenerator
βs :func:`~transformers.generation_utils.GenerationMixin.generate` function, where we setnum_return_sequences
tonum_beams
.num_beams (
int
, optional, defaults to 1) β Number of beams for beam search. 1 means no beam search.n_docs (
int
, optional, defaults toconfig.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()
- Returns
The generated sequences. The second dimension (sequence length) is either equal to
max_length
or shorter if all batches finished early due to theeos_token_id
.- Return type
tf.Tensor
of shape(batch_size * num_return_sequences, sequence_length)
TFRagTokenForGenerationΒΆ
-
class
transformers.
TFRagTokenForGeneration
(*args, **kwargs)[source]ΒΆ The
TFRagTokenForGeneration
forward method, overrides the__call__()
special method.Note
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.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
, and the generator can be any seq2seq model, preferablyTFBartForConditionalGeneration
.The model can be initialized with a
RagRetriever
for end-to-end generation or used in combination with the outputs of a retriever in multiple stepsβsee examples for more details. The model is compatible any autoencoding model as thequestion_encoder
and any seq2seq model with language model head as thegenerator
. It has been tested withTFDPRQuestionEncoder
as thequestion_encoder
andTFBartForConditionalGeneration
as thegenerator
.This model inherits from
TFPreTrainedModel
. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.)This model is also a Tensorflow 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.
- Parameters
config (
RagConfig
) β Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out thefrom_pretrained()
method to load the model weights.question_encoder (
transformers.TFPreTrainedModel
) β An encoder model compatible with the faiss index encapsulated by theretriever
.generator (
transformers.TFPreTrainedModel
) β A seq2seq model used as the generator in the RAG architecture.retriever (
RagRetriever
) β A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.
-
call
(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, encoder_outputs=None, past_key_values=None, doc_scores=None, context_input_ids=None, context_attention_mask=None, use_cache=None, output_attentions=None, output_hidden_states=None, output_retrieved=None, n_docs=None, do_marginalize=None, labels=None, reduce_loss=None, return_dict=None, training=False, **kwargs)[source]ΒΆ The
TFRagTokenForGeneration
forward method, overrides the__call__()
special method.Note
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.- Parameters
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) β Indices of input sequence tokens in the vocabulary.RagConfig
, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices.attention_mask (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) βMask to avoid performing attention on padding token indices. Mask values selected in
[0, 1]
:1 for tokens that are not masked,
0 for tokens that are masked.
encoder_outputs (
tuple(tuple(tf.Tensor)
, optional) βTuple consists of (
generator_enc_last_hidden_state
, optional:generator_enc_hidden_states
, optional:generator_enc_attentions
).generator_enc_last_hidden_state
of shape(batch_size, n_docs * sequence_length, hidden_size)
is a sequence of hidden-states at the output of the last layer of the generatorβs encoder.Used by the (
TFRagModel
) model during decoding.decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) β Provide for generation tasks. None by default, construct as per instructions for the generator model youβre using with your RAG instance.decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, optional) β Default behavior: generate a tensor that ignores pad tokens indecoder_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 (seeencoder_outputs
) andpast_key_values
of the underlying generator. Can be used to speed up decoding.past_key_values
are used in the (RagTokenForGeneration
) model during decoding.doc_scores (
tf.Tensor
of shape(batch_size, config.n_docs)
) β Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
. If the model has is not initialized with aretriever
doc_scores
has to be provided to the forward pass.doc_scores
can be computed viaquestion_encoder_last_hidden_state
andretrieved_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 toTrue
) β If set toTrue
,past_key_values
key value states are returned and can be used to speed up decoding (seepast_key_values
).output_attentions (
bool
, optional) β Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail.output_hidden_states (
bool
, optional) β Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail.output_retrieved (
bool
, optional) β Whether or not to return theretrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
andcontext_attention_mask
. See returned tensors for more detail.return_dict (
bool
, optional) β Whether or not to return aTFRetrievAugLMOutput
instead of a plain tuple.n_docs (
int
, optional, defaults toconfig.n_docs
) β Number of documents to retrieve and/or number of documents for which to generate an answer.do_marginalize (
bool
, optional) β IfTrue
, the logits are marginalized over all documents by making use oftorch.nn.functional.log_softmax
.labels (
tf.Tensor
ornp.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 iflabels
is passed. IfTrue
, the NLL loss is reduced using thetf.Tensor.sum
operation.kwargs (
Dict[str, any]
, optional, defaults to {}) β Legacy dictionary, which is required so that model can use generate() function.
- Returns
A
TFRetrievAugLMMarginOutput
or a tuple oftf.Tensor
(ifreturn_dict=False
is passed or whenconfig.return_dict=False
) comprising various elements depending on the configuration (RagConfig
) and inputs.loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
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 whenuse_cache=True
is passed or whenconfig.use_cache=True
) β List oftf.Tensor
of lengthconfig.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 (seeretrieved_doc_embeds
) andquestion_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 withquestion_encoder_last_hidden_state
to compute thedoc_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 :obj:`(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 encoderinput_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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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 whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) β Tuple oftf.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 whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) β Tuple oftf.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.
Example:
>>> 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)
- Return type
TFRetrievAugLMMarginOutput
ortuple(tf.Tensor)
-
generate
(input_ids: Optional[tensorflow.python.framework.ops.Tensor] = None, attention_mask: Optional[tensorflow.python.framework.ops.Tensor] = None, context_input_ids=None, context_attention_mask=None, doc_scores=None, max_length=None, min_length=None, early_stopping=None, use_cache=None, num_beams=None, bos_token_id=None, pad_token_id=None, eos_token_id=None, length_penalty=None, no_repeat_ngram_size=None, bad_words_ids=None, num_return_sequences=None, decoder_start_token_id=None, n_docs=None, output_scores=None, output_attentions=None, output_hidden_states=None, return_dict_in_generate=None, **model_kwargs)[source]ΒΆ Implements TFRAG token decoding.
- Parameters
input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) β The sequence used as a prompt for the generation. Ifinput_ids
is not passed, thencontext_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.
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
) andquestion_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 toFalse
) β Whether or not to stop the beam search when at leastnum_beams
sentences are finished per batch or not.use_cache β (
bool
, optional, defaults toTrue
): 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 < 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, usetokenizer.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 thegenerator
βs :func:`~transformers.generation_utils.GenerationMixin.generate function, where we setnum_return_sequences
tonum_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 toconfig.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. Seeattentions
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. Seehidden_states
under returned tensors for more details.output_scores (
bool
, optional, defaults to False) β Whether or not to return the prediction scores. Seescores
under returned tensors for more details.return_dict_in_generate (
bool
, optional, defaults to False) β Whether or not to return aModelOutput
instead of a plain tuple.model_specific_kwargs β Additional model specific kwargs will be forwarded to the
forward
function of the model.
- Returns
The generated sequences. The second dimension (sequence_length) is either equal to
max_length
or shorter if all batches finished early due to theeos_token_id
.- Return type
tf.Tensor
of shape(batch_size * num_return_sequences, sequence_length)