Transformers
  • 🌍GET STARTED
    • Transformers
    • Quick tour
    • Installation
  • 🌍TUTORIALS
    • Run inference with pipelines
    • Write portable code with AutoClass
    • Preprocess data
    • Fine-tune a pretrained model
    • Train with a script
    • Set up distributed training with BOINC AI Accelerate
    • Load and train adapters with BOINC AI PEFT
    • Share your model
    • Agents
    • Generation with LLMs
  • 🌍TASK GUIDES
    • 🌍NATURAL LANGUAGE PROCESSING
      • Text classification
      • Token classification
      • Question answering
      • Causal language modeling
      • Masked language modeling
      • Translation
      • Summarization
      • Multiple choice
    • 🌍AUDIO
      • Audio classification
      • Automatic speech recognition
    • 🌍COMPUTER VISION
      • Image classification
      • Semantic segmentation
      • Video classification
      • Object detection
      • Zero-shot object detection
      • Zero-shot image classification
      • Depth estimation
    • 🌍MULTIMODAL
      • Image captioning
      • Document Question Answering
      • Visual Question Answering
      • Text to speech
    • 🌍GENERATION
      • Customize the generation strategy
    • 🌍PROMPTING
      • Image tasks with IDEFICS
  • 🌍DEVELOPER GUIDES
    • Use fast tokenizers from BOINC AI Tokenizers
    • Run inference with multilingual models
    • Use model-specific APIs
    • Share a custom model
    • Templates for chat models
    • Run training on Amazon SageMaker
    • Export to ONNX
    • Export to TFLite
    • Export to TorchScript
    • Benchmarks
    • Notebooks with examples
    • Community resources
    • Custom Tools and Prompts
    • Troubleshoot
  • 🌍PERFORMANCE AND SCALABILITY
    • Overview
    • 🌍EFFICIENT TRAINING TECHNIQUES
      • Methods and tools for efficient training on a single GPU
      • Multiple GPUs and parallelism
      • Efficient training on CPU
      • Distributed CPU training
      • Training on TPUs
      • Training on TPU with TensorFlow
      • Training on Specialized Hardware
      • Custom hardware for training
      • Hyperparameter Search using Trainer API
    • 🌍OPTIMIZING INFERENCE
      • Inference on CPU
      • Inference on one GPU
      • Inference on many GPUs
      • Inference on Specialized Hardware
    • Instantiating a big model
    • Troubleshooting
    • XLA Integration for TensorFlow Models
    • Optimize inference using `torch.compile()`
  • 🌍CONTRIBUTE
    • How to contribute to transformers?
    • How to add a model to BOINC AI Transformers?
    • How to convert a BOINC AI Transformers model to TensorFlow?
    • How to add a pipeline to BOINC AI Transformers?
    • Testing
    • Checks on a Pull Request
  • 🌍CONCEPTUAL GUIDES
    • Philosophy
    • Glossary
    • What BOINC AI Transformers can do
    • How BOINC AI Transformers solve tasks
    • The Transformer model family
    • Summary of the tokenizers
    • Attention mechanisms
    • Padding and truncation
    • BERTology
    • Perplexity of fixed-length models
    • Pipelines for webserver inference
    • Model training anatomy
  • 🌍API
    • 🌍MAIN CLASSES
      • Agents and Tools
      • 🌍Auto Classes
        • Extending the Auto Classes
        • AutoConfig
        • AutoTokenizer
        • AutoFeatureExtractor
        • AutoImageProcessor
        • AutoProcessor
        • Generic model classes
          • AutoModel
          • TFAutoModel
          • FlaxAutoModel
        • Generic pretraining classes
          • AutoModelForPreTraining
          • TFAutoModelForPreTraining
          • FlaxAutoModelForPreTraining
        • Natural Language Processing
          • AutoModelForCausalLM
          • TFAutoModelForCausalLM
          • FlaxAutoModelForCausalLM
          • AutoModelForMaskedLM
          • TFAutoModelForMaskedLM
          • FlaxAutoModelForMaskedLM
          • AutoModelForMaskGenerationge
          • TFAutoModelForMaskGeneration
          • AutoModelForSeq2SeqLM
          • TFAutoModelForSeq2SeqLM
          • FlaxAutoModelForSeq2SeqLM
          • AutoModelForSequenceClassification
          • TFAutoModelForSequenceClassification
          • FlaxAutoModelForSequenceClassification
          • AutoModelForMultipleChoice
          • TFAutoModelForMultipleChoice
          • FlaxAutoModelForMultipleChoice
          • AutoModelForNextSentencePrediction
          • TFAutoModelForNextSentencePrediction
          • FlaxAutoModelForNextSentencePrediction
          • AutoModelForTokenClassification
          • TFAutoModelForTokenClassification
          • FlaxAutoModelForTokenClassification
          • AutoModelForQuestionAnswering
          • TFAutoModelForQuestionAnswering
          • FlaxAutoModelForQuestionAnswering
          • AutoModelForTextEncoding
          • TFAutoModelForTextEncoding
        • Computer vision
          • AutoModelForDepthEstimation
          • AutoModelForImageClassification
          • TFAutoModelForImageClassification
          • FlaxAutoModelForImageClassification
          • AutoModelForVideoClassification
          • AutoModelForMaskedImageModeling
          • TFAutoModelForMaskedImageModeling
          • AutoModelForObjectDetection
          • AutoModelForImageSegmentation
          • AutoModelForImageToImage
          • AutoModelForSemanticSegmentation
          • TFAutoModelForSemanticSegmentation
          • AutoModelForInstanceSegmentation
          • AutoModelForUniversalSegmentation
          • AutoModelForZeroShotImageClassification
          • TFAutoModelForZeroShotImageClassification
          • AutoModelForZeroShotObjectDetection
        • Audio
          • AutoModelForAudioClassification
          • AutoModelForAudioFrameClassification
          • TFAutoModelForAudioFrameClassification
          • AutoModelForCTC
          • AutoModelForSpeechSeq2Seq
          • TFAutoModelForSpeechSeq2Seq
          • FlaxAutoModelForSpeechSeq2Seq
          • AutoModelForAudioXVector
          • AutoModelForTextToSpectrogram
          • AutoModelForTextToWaveform
        • Multimodal
          • AutoModelForTableQuestionAnswering
          • TFAutoModelForTableQuestionAnswering
          • AutoModelForDocumentQuestionAnswering
          • TFAutoModelForDocumentQuestionAnswering
          • AutoModelForVisualQuestionAnswering
          • AutoModelForVision2Seq
          • TFAutoModelForVision2Seq
          • FlaxAutoModelForVision2Seq
      • Callbacks
      • Configuration
      • Data Collator
      • Keras callbacks
      • Logging
      • Models
      • Text Generation
      • ONNX
      • Optimization
      • Model outputs
      • Pipelines
      • Processors
      • Quantization
      • Tokenizer
      • Trainer
      • DeepSpeed Integration
      • Feature Extractor
      • Image Processor
    • 🌍MODELS
      • 🌍TEXT MODELS
        • ALBERT
        • BART
        • BARThez
        • BARTpho
        • BERT
        • BertGeneration
        • BertJapanese
        • Bertweet
        • BigBird
        • BigBirdPegasus
        • BioGpt
        • Blenderbot
        • Blenderbot Small
        • BLOOM
        • BORT
        • ByT5
        • CamemBERT
        • CANINE
        • CodeGen
        • CodeLlama
        • ConvBERT
        • CPM
        • CPMANT
        • CTRL
        • DeBERTa
        • DeBERTa-v2
        • DialoGPT
        • DistilBERT
        • DPR
        • ELECTRA
        • Encoder Decoder Models
        • ERNIE
        • ErnieM
        • ESM
        • Falcon
        • FLAN-T5
        • FLAN-UL2
        • FlauBERT
        • FNet
        • FSMT
        • Funnel Transformer
        • GPT
        • GPT Neo
        • GPT NeoX
        • GPT NeoX Japanese
        • GPT-J
        • GPT2
        • GPTBigCode
        • GPTSAN Japanese
        • GPTSw3
        • HerBERT
        • I-BERT
        • Jukebox
        • LED
        • LLaMA
        • LLama2
        • Longformer
        • LongT5
        • LUKE
        • M2M100
        • MarianMT
        • MarkupLM
        • MBart and MBart-50
        • MEGA
        • MegatronBERT
        • MegatronGPT2
        • Mistral
        • mLUKE
        • MobileBERT
        • MPNet
        • MPT
        • MRA
        • MT5
        • MVP
        • NEZHA
        • NLLB
        • NLLB-MoE
        • Nyströmformer
        • Open-Llama
        • OPT
        • Pegasus
        • PEGASUS-X
        • Persimmon
        • PhoBERT
        • PLBart
        • ProphetNet
        • QDQBert
        • RAG
        • REALM
        • Reformer
        • RemBERT
        • RetriBERT
        • RoBERTa
        • RoBERTa-PreLayerNorm
        • RoCBert
        • RoFormer
        • RWKV
        • Splinter
        • SqueezeBERT
        • SwitchTransformers
        • T5
        • T5v1.1
        • TAPEX
        • Transformer XL
        • UL2
        • UMT5
        • X-MOD
        • XGLM
        • XLM
        • XLM-ProphetNet
        • XLM-RoBERTa
        • XLM-RoBERTa-XL
        • XLM-V
        • XLNet
        • YOSO
      • 🌍VISION MODELS
        • BEiT
        • BiT
        • Conditional DETR
        • ConvNeXT
        • ConvNeXTV2
        • CvT
        • Deformable DETR
        • DeiT
        • DETA
        • DETR
        • DiNAT
        • DINO V2
        • DiT
        • DPT
        • EfficientFormer
        • EfficientNet
        • FocalNet
        • GLPN
        • ImageGPT
        • LeViT
        • Mask2Former
        • MaskFormer
        • MobileNetV1
        • MobileNetV2
        • MobileViT
        • MobileViTV2
        • NAT
        • PoolFormer
        • Pyramid Vision Transformer (PVT)
        • RegNet
        • ResNet
        • SegFormer
        • SwiftFormer
        • Swin Transformer
        • Swin Transformer V2
        • Swin2SR
        • Table Transformer
        • TimeSformer
        • UperNet
        • VAN
        • VideoMAE
        • Vision Transformer (ViT)
        • ViT Hybrid
        • ViTDet
        • ViTMAE
        • ViTMatte
        • ViTMSN
        • ViViT
        • YOLOS
      • 🌍AUDIO MODELS
        • Audio Spectrogram Transformer
        • Bark
        • CLAP
        • EnCodec
        • Hubert
        • MCTCT
        • MMS
        • MusicGen
        • Pop2Piano
        • SEW
        • SEW-D
        • Speech2Text
        • Speech2Text2
        • SpeechT5
        • UniSpeech
        • UniSpeech-SAT
        • VITS
        • Wav2Vec2
        • Wav2Vec2-Conformer
        • Wav2Vec2Phoneme
        • WavLM
        • Whisper
        • XLS-R
        • XLSR-Wav2Vec2
      • 🌍MULTIMODAL MODELS
        • ALIGN
        • AltCLIP
        • BLIP
        • BLIP-2
        • BridgeTower
        • BROS
        • Chinese-CLIP
        • CLIP
        • CLIPSeg
        • Data2Vec
        • DePlot
        • Donut
        • FLAVA
        • GIT
        • GroupViT
        • IDEFICS
        • InstructBLIP
        • LayoutLM
        • LayoutLMV2
        • LayoutLMV3
        • LayoutXLM
        • LiLT
        • LXMERT
        • MatCha
        • MGP-STR
        • Nougat
        • OneFormer
        • OWL-ViT
        • Perceiver
        • Pix2Struct
        • Segment Anything
        • Speech Encoder Decoder Models
        • TAPAS
        • TrOCR
        • TVLT
        • ViLT
        • Vision Encoder Decoder Models
        • Vision Text Dual Encoder
        • VisualBERT
        • X-CLIP
      • 🌍REINFORCEMENT LEARNING MODELS
        • Decision Transformer
        • Trajectory Transformer
      • 🌍TIME SERIES MODELS
        • Autoformer
        • Informer
        • Time Series Transformer
      • 🌍GRAPH MODELS
        • Graphormer
  • 🌍INTERNAL HELPERS
    • Custom Layers and Utilities
    • Utilities for pipelines
    • Utilities for Tokenizers
    • Utilities for Trainer
    • Utilities for Generation
    • Utilities for Image Processors
    • Utilities for Audio processing
    • General Utilities
    • Utilities for Time Series
Powered by GitBook
On this page
  • RAG
  • Overview
  • RagConfig
  • RagTokenizer
  • Rag specific outputs
  • RagRetriever
  • RagModel
  • RagSequenceForGeneration
  • RagTokenForGeneration
  • TFRagModel
  • TFRagSequenceForGeneration
  • TFRagTokenForGeneration
  1. API
  2. MODELS
  3. TEXT MODELS

RAG

PreviousQDQBertNextREALM

Last updated 1 year ago

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 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 .

Tips:

  • Retrieval-augmented generation (“RAG”) models combine the powers of pretrained dense retrieval (DPR) and Seq2Seq models. RAG models retrieve docs, 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.

RagConfig

class transformers.RagConfig

( vocab_size = Noneis_encoder_decoder = Trueprefix = Nonebos_token_id = Nonepad_token_id = Noneeos_token_id = Nonedecoder_start_token_id = Nonetitle_sep = ' / 'doc_sep = ' // 'n_docs = 5max_combined_length = 300retrieval_vector_size = 768retrieval_batch_size = 8dataset = 'wiki_dpr'dataset_split = 'train'index_name = 'compressed'index_path = Nonepassages_path = Noneuse_dummy_dataset = Falsereduce_loss = Falselabel_smoothing = 0.0do_deduplication = Trueexclude_bos_score = Falsedo_marginalize = Falseoutput_retrieved = Falseuse_cache = Trueforced_eos_token_id = None**kwargs )

Parameters

  • 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__().

  • dataset (str, optional, defaults to "wiki_dpr") — A dataset identifier of the indexed dataset in BOINC AI Datasets (list all available datasets and ids using datasets.list_datasets()).

  • dataset_split (str, optional, defaults to "train") — Which split of the dataset to load.

  • index_name (str, optional, defaults to "compressed") — The index name of the index associated with the dataset. One can choose between "legacy", "exact" and "compressed".

  • index_path (str, optional) — The path to the serialized faiss index on disk.

  • passages_path (str, optional) — A path to text passages compatible with the faiss index. Required if using LegacyIndex

  • use_dummy_dataset (bool, optional, defaults to False) — Whether to load a “dummy” variant of the dataset specified by dataset.

  • label_smoothing (float, optional, defaults to 0.0) — Only relevant if return_loss is set to True. Controls the epsilon parameter value for label smoothing in the loss calculation. If set to 0, no label smoothing is performed.

  • do_marginalize (bool, optional, defaults to False) — If True, the logits are marginalized over all documents by making use of torch.nn.functional.log_softmax.

  • reduce_loss (bool, optional, defaults to False) — Whether or not to reduce the NLL loss using the torch.Tensor.sum operation.

  • do_deduplication (bool, optional, defaults to True) — Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to False if used while training with distributed backend.

  • exclude_bos_score (bool, optional, defaults to False) — Whether or not to disregard the BOS token when computing the loss.

  • output_retrieved(bool, optional, defaults to False) — If set to True, retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask are returned. See returned tensors for more detail.

  • use_cache (bool, optional, defaults to True) — Whether or not the model should return the last key/values attentions (not used by all models).

  • forced_eos_token_id (int, optional) — The id of the token to force as the last generated token when max_length is reached. Usually set to eos_token_id.

from_question_encoder_generator_configs

Returns

An instance of a configuration object

RagTokenizer

class transformers.RagTokenizer

( question_encodergenerator )

Rag specific outputs

class transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput

( loss: typing.Optional[torch.FloatTensor] = Nonelogits: FloatTensor = Nonedoc_scores: FloatTensor = Nonepast_key_values: typing.Optional[typing.List[torch.FloatTensor]] = Noneretrieved_doc_embeds: typing.Optional[torch.FloatTensor] = Noneretrieved_doc_ids: typing.Optional[torch.LongTensor] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Nonequestion_encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = Nonequestion_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonequestion_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_enc_last_hidden_state: typing.Optional[torch.FloatTensor] = Nonegenerator_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_dec_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_dec_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

Parameters

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • past_key_values (List[torch.FloatTensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of torch.FloatTensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • retrieved_doc_embeds (torch.FloatTensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (torch.LongTensor of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the cross-attention heads.

Base class for retriever augmented marginalized models outputs.

class transformers.models.rag.modeling_rag.RetrievAugLMOutput

( logits: FloatTensor = Nonedoc_scores: FloatTensor = Nonepast_key_values: typing.Optional[typing.List[torch.FloatTensor]] = Noneretrieved_doc_embeds: typing.Optional[torch.FloatTensor] = Noneretrieved_doc_ids: typing.Optional[torch.LongTensor] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Nonequestion_encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = Nonequestion_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonequestion_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_enc_last_hidden_state: typing.Optional[torch.FloatTensor] = Nonegenerator_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_dec_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_dec_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = Nonegenerator_cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor]] = None )

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 (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • past_key_values (List[torch.FloatTensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of torch.FloatTensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • retrieved_doc_embeds (torch.FloatTensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (torch.LongTensor of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the cross-attention heads.

RagRetriever

class transformers.RagRetriever

( configquestion_encoder_tokenizergenerator_tokenizerindex = Noneinit_retrieval = True )

Parameters

  • index (Index, optional, defaults to the one defined by the configuration) — If specified, use this index instead of the one built using the configuration

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

Examples:

Copied

>>> # 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")

init_retrieval

( )

Retriever initialization function. It loads the index into memory.

postprocess_docs

( docsinput_stringsprefixn_docsreturn_tensors = None ) → tuple(tensors)

Parameters

  • docs (dict) — Retrieved documents.

  • input_strings (str) — Input strings decoded by preprocess_query.

  • prefix (str) — Prefix added at the beginning of each input, typically used with T5-based models.

Returns

tuple(tensors)

a tuple consisting of two elements: contextualized input_ids and a compatible attention_mask.

Postprocessing retrieved docs and combining them with input_strings.

retrieve

( question_hidden_states: ndarrayn_docs: int ) → Tuple[np.ndarray, np.ndarray, List[dict]]

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

Tuple[np.ndarray, np.ndarray, List[dict]]

A tuple with the following objects:

  • retrieved_doc_embeds (np.ndarray of shape (batch_size, n_docs, dim)) — The retrieval embeddings of the retrieved docs per query.

  • doc_ids (np.ndarray of shape (batch_size, n_docs)) — The ids of the documents in the index

  • doc_dicts (List[dict]): The retrieved_doc_embeds examples per query.

Retrieves documents for specified question_hidden_states.

RagModel

class transformers.RagModel

( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = Nonequestion_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Nonegenerator: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Noneretriever: typing.Optional[transformers.models.rag.retrieval_rag.RagRetriever] = None**kwargs )

Parameters

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.

forward

Parameters

  • 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.

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Provide for generation tasks. None by default, construct as per instructions for the generator model you’re using with your RAG instance.

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores has to be provided to the forward pass. doc_scores can be computed via question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever. If the model was not initialized with a retriever `context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length),optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever. If the model has is not initialized with a retriever context_attention_mask has to be provided to the forward pass. context_attention_mask are returned by __call__().

  • use_cache (bool, optional, defaults to True) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • output_retrieved(bool, optional) — Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask. See returned tensors for more detail.

  • n_docs (int, optional, defaults to `config.n_docs“) — Number of documents to retrieve and/or number of documents for which to generate an answer.

Returns

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • past_key_values (List[torch.FloatTensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of torch.FloatTensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • retrieved_doc_embeds (torch.FloatTensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (torch.LongTensor of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the cross-attention heads.

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.

Example:

Copied

>>> from transformers import AutoTokenizer, RagRetriever, RagModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("facebook/rag-token-base")
>>> retriever = RagRetriever.from_pretrained(
...     "facebook/rag-token-base", index_name="exact", use_dummy_dataset=True
... )
>>> # initialize with RagRetriever to do everything in one forward call
>>> model = 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"])

RagSequenceForGeneration

class transformers.RagSequenceForGeneration

( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = Nonequestion_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Nonegenerator: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Noneretriever: typing.Optional[transformers.models.rag.retrieval_rag.RagRetriever] = None**kwargs )

Parameters

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.

forward

Parameters

  • 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.

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Provide for generation tasks. None by default, construct as per instructions for the generator model you’re using with your RAG instance.

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores has to be provided to the forward pass. doc_scores can be computed via question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever. If the model was not initialized with a retriever `context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length),optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever. If the model has is not initialized with a retriever context_attention_mask has to be provided to the forward pass. context_attention_mask are returned by __call__().

  • use_cache (bool, optional, defaults to True) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • output_retrieved(bool, optional) — Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask. See returned tensors for more detail.

  • n_docs (int, optional, defaults to `config.n_docs“) — Number of documents to retrieve and/or number of documents for which to generate an answer.

  • exclude_bos_score (bool, optional) — Only relevant if labels is passed. If True, the score of the BOS token is disregarded when computing the loss.

  • reduce_loss (bool, optional) — Only relevant if labels is passed. If True, the NLL loss is reduced using the torch.Tensor.sum operation.

  • kwargs (Dict[str, any], optional, defaults to {}) — Legacy dictionary, which is required so that model can use generate() function.

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • past_key_values (List[torch.FloatTensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of torch.FloatTensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • retrieved_doc_embeds (torch.FloatTensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (torch.LongTensor of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the cross-attention heads.

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.

Example:

Copied

>>> from transformers import AutoTokenizer, RagRetriever, RagSequenceForGeneration
>>> import torch

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

>>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
>>> targets = tokenizer(text_target="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,
... )

generate

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Nonedoc_scores: typing.Optional[torch.FloatTensor] = Nonedo_deduplication: typing.Optional[bool] = Nonenum_return_sequences: typing.Optional[int] = Nonenum_beams: typing.Optional[int] = Nonen_docs: typing.Optional[int] = None**model_kwargs ) → torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — The sequence used as a prompt for the generation. If input_ids is not passed, then context_input_ids has to be provided.

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

    If the model is not initialized with a retriever or input_ids is not given, context_input_ids and context_attention_mask have to be provided to the forward pass. They are returned by __call__().

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

    If the model is not initialized with a retriever or input_ids is not given, doc_scores has to be provided to the forward pass. doc_scores are returned by __call__().

  • do_deduplication (bool, optional) — Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to False if used while training with distributed backend.

  • num_return_sequences(int, optional, defaults to 1) — The number of independently computed returned sequences for each element in the batch. Note that this is not the value we pass to the generator’s [generate()](/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.generate) function, where we set num_return_sequences to num_beams.

  • num_beams (int, optional, defaults to 1) — Number of beams for beam search. 1 means no beam search.

  • n_docs (int, optional, defaults to config.n_docs) — Number of documents to retrieve and/or number of documents for which to generate an answer.

Returns

torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

The generated sequences. The second dimension (sequence length) is either equal to max_length or shorter if all batches finished early due to the eos_token_id.

RagTokenForGeneration

class transformers.RagTokenForGeneration

( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = Nonequestion_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Nonegenerator: typing.Optional[transformers.modeling_utils.PreTrainedModel] = Noneretriever: typing.Optional[transformers.models.rag.retrieval_rag.RagRetriever] = None**kwargs )

Parameters

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.

forward

Parameters

  • 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.

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Provide for generation tasks. None by default, construct as per instructions for the generator model you’re using with your RAG instance.

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores has to be provided to the forward pass. doc_scores can be computed via question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever. If the model was not initialized with a retriever `context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length),optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever. If the model has is not initialized with a retriever context_attention_mask has to be provided to the forward pass. context_attention_mask are returned by __call__().

  • use_cache (bool, optional, defaults to True) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • output_retrieved(bool, optional) — Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask. See returned tensors for more detail.

  • n_docs (int, optional, defaults to `config.n_docs“) — Number of documents to retrieve and/or number of documents for which to generate an answer.

  • do_marginalize (bool, optional) — If True, the logits are marginalized over all documents by making use of torch.nn.functional.log_softmax.

  • reduce_loss (bool, optional) — Only relevant if labels is passed. If True, the NLL loss is reduced using the torch.Tensor.sum operation.

  • kwargs (Dict[str, any], optional, defaults to {}) — Legacy dictionary, which is required so that model can use generate() function.

Returns

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.

  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • past_key_values (List[torch.FloatTensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of torch.FloatTensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • retrieved_doc_embeds (torch.FloatTensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (torch.LongTensor of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(torch.FloatTensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of torch.FloatTensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Cross-attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the cross-attention heads.

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.

Example:

Copied

>>> from transformers import AutoTokenizer, RagRetriever, RagTokenForGeneration
>>> import torch

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

>>> inputs = tokenizer("How many people live in Paris?", return_tensors="pt")
>>> targets = tokenizer(text_target="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)

generate

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.LongTensor] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Nonedoc_scores: typing.Optional[torch.FloatTensor] = Nonen_docs: typing.Optional[int] = Nonegeneration_config: typing.Optional[transformers.generation.configuration_utils.GenerationConfig] = Noneprefix_allowed_tokens_fn: typing.Callable[[int, torch.Tensor], typing.List[int]] = Nonelogits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = []stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = []**kwargs ) → torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

Parameters

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — The sequence used as a prompt for the generation. If input_ids is not passed, then context_input_ids has to be provided.

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • context_input_ids (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

    If the model has is not initialized with a retriever, context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • context_attention_mask (torch.LongTensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

    If the model has is not initialized with a retriever, context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • doc_scores (torch.FloatTensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

    If the model has is not initialized with a retriever, context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • n_docs (int, optional, defaults to config.n_docs) — Number of documents to retrieve and/or number of documents for which to generate an answer.

  • logits_processor (LogitsProcessorList, optional) — Custom logits processors that complement the default logits processors built from arguments and a model’s config. If a logit processor is passed that is already created with the arguments or a model’s config an error is thrown.

  • stopping_criteria (StoppingCriteriaList, optional) — Custom stopping criteria that complement the default stopping criteria built from arguments and a model’s config. If a stopping criteria is passed that is already created with the arguments or a model’s config an error is thrown.

  • kwargs (Dict[str, Any], optional) — Ad hoc parametrization of generate_config and/or additional model-specific kwargs that will be forwarded to the forward function of the model.

Returns

torch.LongTensor of shape (batch_size * num_return_sequences, sequence_length)

The generated sequences. The second dimension (sequence_length) is either equal to max_length or shorter if all batches finished early due to the eos_token_id.

Implements RAG token decoding.

TFRagModel

class transformers.TFRagModel

( *args**kwargs )

Parameters

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 model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in SavedModel format.

call

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Noneencoder_outputs: np.ndarray | tf.Tensor | None = Nonedecoder_input_ids: np.ndarray | tf.Tensor | None = Nonedecoder_attention_mask: np.ndarray | tf.Tensor | None = Nonepast_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = Nonedoc_scores: np.ndarray | tf.Tensor | None = Nonecontext_input_ids: np.ndarray | tf.Tensor | None = Nonecontext_attention_mask: np.ndarray | tf.Tensor | None = Noneuse_cache: bool | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneoutput_retrieved: bool | None = Nonen_docs: int | None = Nonereturn_dict: bool | None = Nonetraining: bool = False**kwargs ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput or tuple(tf.Tensor)

Parameters

  • 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.

  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Provide for generation tasks. None by default, construct as per instructions for the generator model you’re using with your RAG instance.

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores has to be provided to the forward pass. doc_scores can be computed via question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.

  • context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

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

    If the model has is not initialized with a retriever context_attention_mask has to be provided to the forward pass. context_attention_mask are returned by __call__().

  • use_cache (bool, optional, defaults to True) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • output_retrieved(bool, optional) — Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask. See returned tensors for more detail.

  • return_dict (bool, optional) — Whether or not to return a TFRetrievAugLMOutput instead of a plain tuple.

  • n_docs (int, optional, defaults to `config.n_docs“) — Number of documents to retrieve and/or number of documents for which to generate an answer.

Returns

transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput or tuple(tf.Tensor)

  • logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • past_key_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • retrieved_doc_embeds (tf.Tensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (tf.Tensor of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

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.

Example:

Copied

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

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

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

TFRagSequenceForGeneration

class transformers.TFRagSequenceForGeneration

( *args**kwargs )

Parameters

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 model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in SavedModel format.

call

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonedecoder_input_ids: np.ndarray | tf.Tensor | None = Nonedecoder_attention_mask: np.ndarray | tf.Tensor | None = Noneencoder_outputs: np.ndarray | tf.Tensor | None = Nonepast_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = Nonedoc_scores: np.ndarray | tf.Tensor | None = Nonecontext_input_ids: np.ndarray | tf.Tensor | None = Nonecontext_attention_mask: np.ndarray | tf.Tensor | None = Noneuse_cache: Optional[bool] = Noneoutput_attentions: Optional[bool] = Noneoutput_hidden_states: Optional[bool] = Noneoutput_retrieved: Optional[bool] = Nonen_docs: Optional[int] = Noneexclude_bos_score: Optional[bool] = Nonelabels: np.ndarray | tf.Tensor | None = Nonereduce_loss: Optional[bool] = Nonereturn_dict: Optional[bool] = Nonetraining: bool = False**kwargs ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)

Parameters

  • 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.

  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Provide for generation tasks. None by default, construct as per instructions for the generator model you’re using with your RAG instance.

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores has to be provided to the forward pass. doc_scores can be computed via question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.

  • context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

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

    If the model has is not initialized with a retriever context_attention_mask has to be provided to the forward pass. context_attention_mask are returned by __call__().

  • use_cache (bool, optional, defaults to True) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • output_retrieved(bool, optional) — Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask. See returned tensors for more detail.

  • return_dict (bool, optional) — Whether or not to return a TFRetrievAugLMOutput instead of a plain tuple.

  • n_docs (int, optional, defaults to `config.n_docs“) — Number of documents to retrieve and/or number of documents for which to generate an answer.

  • exclude_bos_score (bool, optional) — Only relevant if labels is passed. If True, the score of the BOS token is disregarded when computing the loss.

  • reduce_loss (bool, optional) — Only relevant if labels is passed. If True, the NLL loss is reduced using the tf.Tensor.sum operation.

  • kwargs (Dict[str, any], optional, defaults to {}) — Legacy dictionary, which is required so that model can use generate() function.

Returns

transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.

  • logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • past_key_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • retrieved_doc_embeds (tf.Tensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (tf.Tensor (int32) of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (tf.Tensor(int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (tf.Tensor (int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

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.

Example:

Copied

>>> from transformers import AutoTokenizer, RagRetriever, TFRagSequenceForGeneration

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

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

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

>>> # or directly generate
>>> generated = model.generate(
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
... )
>>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)

generate

( input_ids: TFModelInputType | None = Noneattention_mask: tf.Tensor | None = Nonecontext_input_ids = Nonecontext_attention_mask = Nonedoc_scores = Nonedo_deduplication = Nonenum_return_sequences = Nonenum_beams = Nonen_docs = None**model_kwargs ) → tf.Tensor of shape (batch_size * num_return_sequences, sequence_length)

Parameters

  • input_ids (tf.Tensor of shape (batch_size, sequence_length), optional) — The sequence used as a prompt for the generation. If input_ids is not passed, then context_input_ids has to be provided.

  • context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

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

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever or input_ids is not given, doc_scores has to be provided to the forward pass. doc_scores are returned by __call__().

  • do_deduplication (bool, optional) — Whether or not to deduplicate the generations from different context documents for a given input. Has to be set to False if used while training with distributed backend.

  • num_return_sequences(int, optional, defaults to 1) — The number of independently computed returned sequences for each element in the batch. Note that this is not the value we pass to the generator’s [generate()](/docs/transformers/v4.34.1/en/main_classes/text_generation#transformers.GenerationMixin.generate) function, where we set num_return_sequences to num_beams.

  • num_beams (int, optional, defaults to 1) — Number of beams for beam search. 1 means no beam search.

  • n_docs (int, optional, defaults to config.n_docs) — Number of documents to retrieve and/or number of documents for which to generate an answer.

Returns

tf.Tensor of shape (batch_size * num_return_sequences, sequence_length)

The generated sequences. The second dimension (sequence length) is either equal to max_length or shorter if all batches finished early due to the eos_token_id.

TFRagTokenForGeneration

class transformers.TFRagTokenForGeneration

( *args**kwargs )

Parameters

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 model is in a developing state as it is now fully supports in eager-mode only, and may not be exported in SavedModel format.

call

( input_ids: TFModelInputType | None = Noneattention_mask: np.ndarray | tf.Tensor | None = Nonedecoder_input_ids: np.ndarray | tf.Tensor | None = Nonedecoder_attention_mask: np.ndarray | tf.Tensor | None = Noneencoder_outputs: np.ndarray | tf.Tensor | None = Nonepast_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = Nonedoc_scores: np.ndarray | tf.Tensor | None = Nonecontext_input_ids: np.ndarray | tf.Tensor | None = Nonecontext_attention_mask: np.ndarray | tf.Tensor | None = Noneuse_cache: bool | None = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Noneoutput_retrieved: bool | None = Nonen_docs: int | None = Nonedo_marginalize: bool | None = Nonelabels: np.ndarray | tf.Tensor | None = Nonereduce_loss: bool | None = Nonereturn_dict: bool | None = Nonetraining: bool = False**kwargs ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)

Parameters

  • 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.

  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Provide for generation tasks. None by default, construct as per instructions for the generator model you’re using with your RAG instance.

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state. If the model has is not initialized with a retriever doc_scores has to be provided to the forward pass. doc_scores can be computed via question_encoder_last_hidden_state and retrieved_doc_embeds, see examples for more information.

  • context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

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

    If the model has is not initialized with a retriever context_attention_mask has to be provided to the forward pass. context_attention_mask are returned by __call__().

  • use_cache (bool, optional, defaults to True) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

  • output_retrieved(bool, optional) — Whether or not to return the retrieved_doc_embeds, retrieved_doc_ids, context_input_ids and context_attention_mask. See returned tensors for more detail.

  • return_dict (bool, optional) — Whether or not to return a TFRetrievAugLMOutput instead of a plain tuple.

  • n_docs (int, optional, defaults to `config.n_docs“) — Number of documents to retrieve and/or number of documents for which to generate an answer.

  • do_marginalize (bool, optional) — If True, the logits are marginalized over all documents by making use of torch.nn.functional.log_softmax.

  • reduce_loss (bool, optional) — Only relevant if labels is passed. If True, the NLL loss is reduced using the tf.Tensor.sum operation.

  • kwargs (Dict[str, any], optional, defaults to {}) — Legacy dictionary, which is required so that model can use generate() function.

Returns

transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or tuple(tf.Tensor)

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — Language modeling loss.

  • logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — Prediction scores of the language modeling head. The score is possibly marginalized over all documents for each vocabulary token.

  • past_key_values (List[tf.Tensor], optional, returned when use_cache=True is passed or when config.use_cache=True) — List of tf.Tensor of length config.n_layers, with each tensor of shape (2, batch_size, num_heads, sequence_length, embed_size_per_head)).

    Contains precomputed hidden-states (key and values in the attention blocks) of the decoder that can be used (see past_key_values input) to speed up sequential decoding.

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

  • retrieved_doc_embeds (tf.Tensor of shape (batch_size, config.n_docs, hidden_size), optional, returned when output_retrieved=True) — Embedded documents retrieved by the retriever. Is used with question_encoder_last_hidden_state to compute the doc_scores.

  • retrieved_doc_ids (tf.Tensor (int32) of shape (batch_size, config.n_docs), optional, returned when output_retrieved=True) — The indexes of the embedded documents retrieved by the retriever.

  • context_input_ids (tf.Tensor(int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input ids post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • context_attention_mask (tf.Tensor (int32) of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

  • question_encoder_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden states at the output of the last layer of the question encoder pooled output of the model.

  • question_enc_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the question encoder at the output of each layer plus the initial embedding outputs.

  • question_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the question encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_enc_last_hidden_state (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Sequence of hidden-states at the output of the last layer of the generator encoder of the model.

  • generator_enc_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator encoder at the output of each layer plus the initial embedding outputs.

  • generator_enc_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator encoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

  • generator_dec_hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings and one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    Hidden states of the generator decoder at the output of each layer plus the initial embedding outputs.

  • generator_dec_attentions (tuple(tf.Tensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of tf.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

    Attentions weights of the generator decoder, after the attention softmax, used to compute the weighted average in the self-attention heads.

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.

Example:

Copied

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

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

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

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

>>> # or directly generate
>>> generated = model.generate(
...     context_input_ids=docs_dict["context_input_ids"],
...     context_attention_mask=docs_dict["context_attention_mask"],
...     doc_scores=doc_scores,
... )
>>> generated_string = tokenizer.batch_decode(generated, skip_special_tokens=True)

generate

( input_ids: TFModelInputType | None = Noneattention_mask: tf.Tensor | None = Nonecontext_input_ids = Nonecontext_attention_mask = Nonedoc_scores = Nonen_docs = Nonegeneration_config = Nonelogits_processor = []**kwargs ) → tf.Tensor of shape (batch_size * num_return_sequences, sequence_length)

Parameters

  • input_ids (tf.Tensor of shape (batch_size, sequence_length), optional) — The sequence used as a prompt for the generation. If input_ids is not passed, then context_input_ids has to be provided.

  • attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,

    • 0 for tokens that are masked.

  • context_input_ids (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Input IDs post-processed from the retrieved documents and the question encoder input_ids by the retriever.

    If the model has is not initialized with a retriever, context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • context_attention_mask (tf.Tensor of shape (batch_size * config.n_docs, config.max_combined_length), optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoder input_ids by the retriever.

    If the model has is not initialized with a retriever, context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • doc_scores (tf.Tensor of shape (batch_size, config.n_docs)) — Score between each retrieved document embeddings (see retrieved_doc_embeds) and question_encoder_last_hidden_state.

    If the model has is not initialized with a retriever, context_input_ids has to be provided to the forward pass. context_input_ids are returned by __call__().

  • n_docs (int, optional, defaults to config.n_docs) — Number of documents to retrieve and/or number of documents for which to generate an answer.

  • logits_processor (TFLogitsProcessorList, optional) — Custom logits processors that complement the default logits processors built from arguments and a model’s config. If a logit processor is passed that is already created with the arguments or a model’s config an error is thrown.

  • kwargs (Dict[str, Any], optional) — Ad hoc parametrization of generate_config and/or additional model-specific kwargs that will be forwarded to the forward function of the model.

Returns

tf.Tensor of shape (batch_size * num_return_sequences, sequence_length)

The generated sequences. The second dimension (sequence_length) is either equal to max_length or shorter if all batches finished early due to the eos_token_id.

Implements TFRAG token decoding.

title_sep (str, optional, defaults to " / ") — Separator inserted between the title and the text of the retrieved document when calling .

doc_sep (str, optional, defaults to " // ") — Separator inserted between the text of the retrieved document and the original input when calling .

retrieval_vector_size (int, optional, defaults to 768) — Dimensionality of the document embeddings indexed by .

retrieval_batch_size (int, optional, defaults to 8) — Retrieval batch size, defined as the number of queries issues concurrently to the faiss index encapsulated .

stores the configuration of a RagModel. Configuration objects inherit from and can be used to control the model outputs. Read the documentation from for more information.

( question_encoder_config: PretrainedConfiggenerator_config: PretrainedConfig**kwargs ) →

Instantiate a (or a derived class) from a pre-trained encoder model configuration and decoder model configuration.

config () — The configuration of the RAG model this Retriever is used with. Contains parameters indicating which Index to build. You can load your own custom dataset with config.index_name="custom" or use a canonical one (default) from the datasets library with config.index_name="wiki_dpr" for example.

question_encoder_tokenizer () — The tokenizer that was used to tokenize the question. It is used to decode the question and then use the generator_tokenizer.

generator_tokenizer () — The tokenizer used for the generator part of the RagModel.

config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.

question_encoder () — An encoder model compatible with the faiss index encapsulated by the retriever.

generator () — A seq2seq model used as the generator in the RAG architecture.

retriever () — A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.

The forward method, overrides the __call__ special method.

The question encoder can be any autoencoding model, preferably , and the generator can be any seq2seq model, preferably .

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

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Nonepast_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = Nonedoc_scores: typing.Optional[torch.FloatTensor] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneoutput_retrieved: typing.Optional[bool] = Nonen_docs: typing.Optional[int] = None ) → or tuple(torch.FloatTensor)

input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. , 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.

Used by the () model during decoding.

past_key_values (tuple(tuple(torch.FloatTensor))) — Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used in the () model during decoding.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.

question_encoder () — An encoder model compatible with the faiss index encapsulated by the retriever.

generator () — A seq2seq model used as the generator in the RAG architecture.

retriever () — A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.

The forward method, overrides the __call__ special method.

The question encoder can be any autoencoding model, preferably , and the generator can be any seq2seq model, preferably .

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

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Nonepast_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Nonedoc_scores: typing.Optional[torch.FloatTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneoutput_retrieved: typing.Optional[bool] = Noneexclude_bos_score: typing.Optional[bool] = Nonereduce_loss: typing.Optional[bool] = Nonelabels: typing.Optional[torch.LongTensor] = Nonen_docs: typing.Optional[int] = None**kwargs ) → or tuple(torch.FloatTensor)

input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. , 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.

Used by the () model during decoding.

past_key_values (tuple(tuple(torch.FloatTensor))) — Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used in the () model during decoding.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

kwargs (Dict[str, Any], optional) — Additional kwargs will be passed to .

Implements RAG sequence “thorough” decoding. Read the ` documentation for more information on how to set other generate input parameters.

config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.

question_encoder () — An encoder model compatible with the faiss index encapsulated by the retriever.

generator () — A seq2seq model used as the generator in the RAG architecture.

retriever () — A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.

The forward method, overrides the __call__ special method.

The question encoder can be any autoencoding model, preferably , and the generator can be any seq2seq model, preferably .

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

This model inherits from . 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 subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

( input_ids: typing.Optional[torch.LongTensor] = Noneattention_mask: typing.Optional[torch.FloatTensor] = Noneencoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = Nonedecoder_input_ids: typing.Optional[torch.LongTensor] = Nonedecoder_attention_mask: typing.Optional[torch.BoolTensor] = Nonepast_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = Nonecontext_input_ids: typing.Optional[torch.LongTensor] = Nonecontext_attention_mask: typing.Optional[torch.LongTensor] = Nonedoc_scores: typing.Optional[torch.FloatTensor] = Noneuse_cache: typing.Optional[bool] = Noneoutput_attentions: typing.Optional[bool] = Noneoutput_hidden_states: typing.Optional[bool] = Noneoutput_retrieved: typing.Optional[bool] = Nonedo_marginalize: typing.Optional[bool] = Nonereduce_loss: typing.Optional[bool] = Nonelabels: typing.Optional[torch.LongTensor] = Nonen_docs: typing.Optional[int] = None**kwargs ) → or tuple(torch.FloatTensor)

input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. , 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.

Used by the () model during decoding.

past_key_values (tuple(tuple(torch.FloatTensor))) — Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used in the () model during decoding.

or tuple(torch.FloatTensor)

A or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

generation_config (~generation.GenerationConfig, optional) — The generation configuration to be used as base parametrization for the generation call. **kwargs passed to generate matching the attributes of generation_config will override them. If generation_config is not provided, the default will be used, which has the following loading priority: 1) from the generation_config.json model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit ’s default values, whose documentation should be checked to parameterize generation.

prefix_allowed_tokens_fn (Callable[[int, torch.Tensor], List[int]], optional) — If provided, this function constraints the beam search to allowed tokens only at each step. If not provided no constraint is applied. This function takes 2 arguments inputs_ids and the batch ID batch_id. It has to return a list with the allowed tokens for the next generation step conditioned on the previously generated tokens inputs_ids and the batch ID batch_id. This argument is useful for constrained generation conditioned on the prefix, as described in .

config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.

question_encoder () — An encoder model compatible with the faiss index encapsulated by the retriever.

generator () — A seq2seq model used as the generator in the RAG architecture.

retriever () — A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.

The forward method, overrides the __call__ special method.

The question encoder can be any autoencoding model, preferably , and the generator can be any seq2seq model, preferably .

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

This model inherits from . 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 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.

input_ids (tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. , 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.

Used by the () model during decoding.

past_key_values (tuple(tuple(tf.Tensor))) — Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used in the () model during decoding.

A transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.

question_encoder () — An encoder model compatible with the faiss index encapsulated by the retriever.

generator () — A seq2seq model used as the generator in the RAG architecture.

retriever () — A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.

The forward method, overrides the __call__ special method.

The question encoder can be any autoencoding model, preferably , and the generator can be any seq2seq model, preferably .

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

This model inherits from . 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 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.

input_ids (tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. , 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.

Used by the () model during decoding.

past_key_values (tuple(tuple(tf.Tensor))) — Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used in the () model during decoding.

labels (tf.Tensor or np.ndarray of shape (batch_size, sequence_length), optional) — Labels for computing the cross entropy classification loss according to Rag-Sequence model formulation See Section 2.1 for details about Rag-Sequence formulation. Indices should be in [0, ..., config.vocab_size - 1].

A transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

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.

kwargs (Dict[str, Any], optional) — Additional kwargs will be passed to

Implements RAG sequence “thorough” decoding. Read the ` documentation for more information on how to set other generate input parameters

config () — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the method to load the model weights.

question_encoder () — An encoder model compatible with the faiss index encapsulated by the retriever.

generator () — A seq2seq model used as the generator in the RAG architecture.

retriever () — A retriever class encapsulating a faiss index queried to obtain context documents for current inputs.

The forward method, overrides the __call__ special method.

The question encoder can be any autoencoding model, preferably , and the generator can be any seq2seq model, preferably .

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

This model inherits from . 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 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.

input_ids (tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. , 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.

Used by the () model during decoding.

past_key_values (tuple(tuple(tf.Tensor))) — Tuple consists of two elements: encoder_outputs of the RAG model (see encoder_outputs) and past_key_values of the underlying generator. Can be used to speed up decoding. past_key_values are used in the () model during decoding.

labels (tf.Tensor or np.ndarray of shape (batch_size, sequence_length), optional) — Labels for computing the cross entropy classification loss according to Rag-Token model formulation See Section 2.1 for details about Rag-Token formulation. Indices should be in [0, ..., config.vocab_size - 1].

A transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput or a tuple of tf.Tensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration () and inputs.

The forward method, overrides the __call__ special method.

generation_config (~generation.GenerationConfig, optional) — The generation configuration to be used as base parametrization for the generation call. **kwargs passed to generate matching the attributes of generation_config will override them. If generation_config is not provided, the default will be used, which had the following loading priority: 1) from the generation_config.json model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit ’s default values, whose documentation should be checked to parameterize generation.

🌍
🌍
🌍
RagRetriever
RagRetriever
RagRetriever
RagRetriever
RagConfig
PretrainedConfig
PretrainedConfig
<source>
EncoderDecoderConfig
EncoderDecoderConfig
EncoderDecoderConfig
<source>
<source>
<source>
<source>
RagConfig
PreTrainedTokenizer
PreTrainedTokenizer
<source>
<source>
<source>
<source>
RagConfig
from_pretrained()
PreTrainedModel
PreTrainedModel
RagRetriever
RagModel
DPRQuestionEncoder
BartForConditionalGeneration
RagRetriever
DPRQuestionEncoder
BartForConditionalGeneration
T5ForConditionalGeneration
PreTrainedModel
torch.nn.Module
<source>
transformers.models.rag.modeling_rag.RetrievAugLMOutput
RagConfig
What are input IDs?
What are attention masks?
RagModel
RagTokenForGeneration
transformers.models.rag.modeling_rag.RetrievAugLMOutput
transformers.models.rag.modeling_rag.RetrievAugLMOutput
RagConfig
RagModel
<source>
RagConfig
from_pretrained()
PreTrainedModel
PreTrainedModel
RagRetriever
RagSequenceForGeneration
DPRQuestionEncoder
BartForConditionalGeneration
RagRetriever
DPRQuestionEncoder
BartForConditionalGeneration
T5ForConditionalGeneration
PreTrainedModel
torch.nn.Module
<source>
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
RagConfig
What are input IDs?
What are attention masks?
RagModel
RagTokenForGeneration
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
RagConfig
RagSequenceForGeneration
<source>
What are attention masks?
generate()
generate()
<source>
RagConfig
from_pretrained()
PreTrainedModel
PreTrainedModel
RagRetriever
RagTokenForGeneration
DPRQuestionEncoder
BartForConditionalGeneration
RagRetriever
DPRQuestionEncoder
BartForConditionalGeneration
T5ForConditionalGeneration
PreTrainedModel
torch.nn.Module
<source>
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
RagConfig
What are input IDs?
What are attention masks?
RagModel
RagTokenForGeneration
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
RagConfig
RagTokenForGeneration
<source>
What are attention masks?
GenerationConfig
Autoregressive Entity Retrieval
<source>
RagConfig
from_pretrained()
TFPreTrainedModel
TFPreTrainedModel
RagRetriever
TFRagModel
TFDPRQuestionEncoder
TFBartForConditionalGeneration
RagRetriever
TFDPRQuestionEncoder
TFBartForConditionalGeneration
TFPreTrainedModel
tf.keras.Model
<source>
RagConfig
What are attention masks?
TFRagModel
RagTokenForGeneration
RagConfig
TFRagModel
<source>
RagConfig
from_pretrained()
TFPreTrainedModel
TFPreTrainedModel
RagRetriever
TFRagSequenceForGeneration
TFDPRQuestionEncoder
TFBartForConditionalGeneration
RagRetriever
TFDPRQuestionEncoder
TFBartForConditionalGeneration
TFPreTrainedModel
tf.keras.Model
<source>
RagConfig
What are attention masks?
TFRagModel
RagTokenForGeneration
https://arxiv.org/pdf/2005.11401.pdf
RagConfig
TFRagSequenceForGeneration
<source>
What are attention masks?
generate()
generate()
<source>
RagConfig
from_pretrained()
TFPreTrainedModel
TFPreTrainedModel
RagRetriever
TFRagTokenForGeneration
TFDPRQuestionEncoder
TFBartForConditionalGeneration
RagRetriever
TFDPRQuestionEncoder
TFBartForConditionalGeneration
TFPreTrainedModel
tf.keras.Model
<source>
RagConfig
What are attention masks?
TFRagModel
RagTokenForGeneration
https://arxiv.org/pdf/2005.11401.pdf
RagConfig
TFRagTokenForGeneration
<source>
What are attention masks?
GenerationConfig
Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
ola13
<source>