RAG
概述
检索增强生成(“RAG”)模型结合了预训练密集检索(DPR)和序列到序列模型的能力。RAG模型检索文档,将其传递给seq2seq模型,然后通过边缘化生成输出。检索器和seq2seq模块从预训练模型初始化,并联合进行微调,使检索和生成都能适应下游任务。
它基于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的论文Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks。
论文的摘要如下:
大型预训练语言模型已被证明在其参数中存储了事实知识,并在下游NLP任务上进行微调时取得了最先进的结果。然而,它们访问和精确操作知识的能力仍然有限,因此在知识密集型任务上,它们的性能落后于特定任务的架构。此外,为它们的决策提供来源和更新其世界知识仍然是开放的研究问题。具有可微分访问机制的预训练模型可以克服这个问题,但迄今为止仅在抽取式下游任务中进行了研究。我们探索了一种通用的微调方法,用于检索增强生成(RAG)——这些模型结合了预训练的参量和非参量记忆用于语言生成。我们引入了RAG模型,其中参量记忆是一个预训练的seq2seq模型,非参量记忆是维基百科的密集向量索引,通过预训练的神经检索器访问。我们比较了两种RAG公式,一种在整个生成序列中使用相同的检索段落,另一种可以在每个标记上使用不同的段落。我们在广泛的知识密集型NLP任务上微调和评估了我们的模型,并在三个开放领域QA任务上设定了最先进的水平,优于参量seq2seq模型和特定任务的检索和提取架构。对于语言生成任务,我们发现RAG模型生成的文本比最先进的仅参量seq2seq基线更具体、多样和真实。
该模型由ola13贡献。
使用提示
检索增强生成(“RAG”)模型结合了预训练密集检索(DPR)和Seq2Seq模型的能力。 RAG模型检索文档,将其传递给seq2seq模型,然后通过边缘化生成输出。检索器和seq2seq 模块从预训练模型初始化,并联合微调,使检索和生成都能适应 下游任务。
RagConfig
类 transformers.RagConfig
< source >( vocab_size = None is_encoder_decoder = True prefix = None bos_token_id = None pad_token_id = None eos_token_id = None decoder_start_token_id = None title_sep = ' / ' doc_sep = ' // ' n_docs = 5 max_combined_length = 300 retrieval_vector_size = 768 retrieval_batch_size = 8 dataset = 'wiki_dpr' dataset_split = 'train' index_name = 'compressed' index_path = None passages_path = None use_dummy_dataset = False reduce_loss = False label_smoothing = 0.0 do_deduplication = True exclude_bos_score = False do_marginalize = False output_retrieved = False use_cache = True forced_eos_token_id = None dataset_revision = None **kwargs )
参数
- title_sep (
str
, 可选, 默认为" / "
) — 在调用RagRetriever时,插入在检索到的文档标题和文本之间的分隔符。 - doc_sep (
str
, 可选, 默认为" // "
) — 在调用RagRetriever时,插入在检索到的文档文本和原始输入之间的分隔符。 - n_docs (
int
, optional, 默认为 5) — 要检索的文档数量。 - max_combined_length (
int
, 可选, 默认为 300) — 由__call__()
返回的上下文输入的最大长度. - retrieval_vector_size (
int
, 可选, 默认为 768) — 由RagRetriever索引的文档嵌入的维度。 - retrieval_batch_size (
int
, 可选, 默认为 8) — 检索批次大小,定义为同时向封装在 RagRetriever 中的 faiss 索引发出的查询数量。 - dataset (
str
, 可选, 默认为"wiki_dpr"
) — HuggingFace Datasets 中索引数据集的标识符(使用datasets.list_datasets()
列出所有可用数据集及其标识符)。 - dataset_split (
str
, optional, defaults to"train"
) — 加载dataset
的哪个部分. - index_name (
str
, 可选, 默认为"compressed"
) — 与dataset
关联的索引名称。可以选择"legacy"
,"exact"
和"compressed"
. - index_path (
str
, optional) — 磁盘上序列化faiss索引的路径。 - passages_path (
str
, 可选) — 一个与faiss索引兼容的文本段落路径。如果使用LegacyIndex
- use_dummy_dataset (
bool
, 可选, 默认为False
) — 是否加载由dataset
指定的数据集的“虚拟”变体。 - label_smoothing (
float
, 可选, 默认为 0.0) — 仅在return_loss
设置为True
时相关。控制损失计算中标签平滑的epsilon
参数值。如果设置为 0,则不执行标签平滑。 - do_marginalize (
bool
, 可选, 默认为False
) — 如果为True
,则通过使用torch.nn.functional.log_softmax
对所有文档进行边缘化处理来获得 logits。 - reduce_loss (
bool
, optional, defaults toFalse
) — 是否使用torch.Tensor.sum
操作来减少 NLL 损失。 - do_deduplication (
bool
, 可选, 默认为True
) — 是否对来自不同上下文文档的生成结果进行去重。如果在使用分布式后端进行训练时使用,必须设置为False
. - exclude_bos_score (
bool
, optional, defaults toFalse
) — 是否在计算损失时忽略BOS标记。 - output_retrieved(
bool
, 可选, 默认为False
) — 如果设置为True
,将返回retrieved_doc_embeds
、retrieved_doc_ids
、context_input_ids
和context_attention_mask
。有关更多详细信息,请参阅返回的张量。 - use_cache (
bool
, 可选, 默认为True
) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。 - forced_eos_token_id (
int
, 可选) — 当达到max_length
时,强制作为最后生成的令牌的ID。通常设置为eos_token_id
.
RagConfig 存储了 RagModel 的配置。配置对象继承自 PretrainedConfig,并且可以用于控制模型的输出。更多信息请阅读 PretrainedConfig 的文档。
from_question_encoder_generator_configs
< source >( question_encoder_config: PretrainedConfig generator_config: PretrainedConfig **kwargs ) → EncoderDecoderConfig
从预训练的编码器模型配置和解码器模型配置实例化一个EncoderDecoderConfig(或派生类)。
RagTokenizer
Rag 特定输出
类 transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None doc_scores: FloatTensor = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None retrieved_doc_embeds: typing.Optional[torch.FloatTensor] = None retrieved_doc_ids: typing.Optional[torch.LongTensor] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None question_encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None question_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None question_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_enc_last_hidden_state: typing.Optional[torch.FloatTensor] = None generator_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_dec_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_dec_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当提供labels
时返回) — 语言建模损失. - logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。该分数可能针对每个词汇标记在所有文档上进行边缘化。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。 - past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)加速顺序解码。 - retrieved_doc_embeds (
torch.FloatTensor
形状为(batch_size, config.n_docs, hidden_size)
, 可选, 当 output_retrieved=True 时返回) — 由检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起使用以计算doc_scores
. - retrieved_doc_ids (
torch.LongTensor
of shape(batch_size, config.n_docs)
, optional, returned when output_retrieved=True) — 检索器检索到的嵌入文档的索引。 - context_input_ids (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器输入ID中后处理的输入ID,由检索器返回。 - context_attention_mask (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的注意力掩码,由检索器生成。 - question_encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型最后一层问题编码器输出的隐藏状态序列的池化输出。 - question_enc_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.问题编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- question_enc_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.问题编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- generator_enc_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型生成器编码器最后一层输出的隐藏状态序列。 - generator_enc_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.生成器编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- generator_enc_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.生成器编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- generator_dec_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
- generator_dec_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.生成器解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- generator_cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.生成器解码器的交叉注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
检索增强边缘化模型输出的基类。
类 transformers.models.rag.modeling_rag.RetrievAugLMOutput
< source >( logits: FloatTensor = None doc_scores: FloatTensor = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None retrieved_doc_embeds: typing.Optional[torch.FloatTensor] = None retrieved_doc_ids: typing.Optional[torch.LongTensor] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None question_encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None question_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None question_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_enc_last_hidden_state: typing.Optional[torch.FloatTensor] = None generator_enc_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_enc_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_dec_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_dec_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None generator_cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。该分数可能针对每个词汇标记在所有文档上进行边缘化。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。 - past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)加速顺序解码。 - retrieved_doc_embeds (
torch.FloatTensor
形状为(batch_size, config.n_docs, hidden_size)
, 可选, 当 output_retrieved=True 时返回) — 由检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起用于计算doc_scores
. - retrieved_doc_ids (
torch.LongTensor
of shape(batch_size, config.n_docs)
, optional, returned when output_retrieved=True) — 检索器检索到的嵌入文档的索引。 - context_input_ids (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器输入ID中后处理的输入ID,由检索器返回。 - context_attention_mask (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器input_ids
由检索器后处理的注意力掩码。 - question_encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型最后一层问题编码器输出的隐藏状态序列的池化输出。 - question_enc_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.问题编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- question_enc_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.问题编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- generator_enc_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型生成器编码器最后一层输出的隐藏状态序列。 - generator_enc_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.生成器编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- generator_enc_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.生成器编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- generator_dec_hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings and one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
- generator_dec_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.生成器解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- generator_cross_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, sequence_length)
.生成器解码器的交叉注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
RagRetriever
类 transformers.RagRetriever
< source >( config question_encoder_tokenizer generator_tokenizer index = 无 init_retrieval = 真 )
参数
- config (RagConfig) —
此检索器使用的RAG模型的配置。包含指示构建哪个
Index
的参数。您可以使用config.index_name="custom"
加载您自己的自定义数据集,或者使用数据集库中的规范数据集(默认),例如config.index_name="wiki_dpr"
。 - question_encoder_tokenizer (PreTrainedTokenizer) — 用于对问题进行分词的标记器。它用于解码问题,然后使用generator_tokenizer.
- generator_tokenizer (PreTrainedTokenizer) — 用于RagModel生成器部分的标记器。
- index (
Index
, 可选, 默认为配置中定义的) — 如果指定,则使用此索引而不是使用配置构建的索引
用于从向量查询中获取文档的检索器。它检索文档嵌入以及文档内容,并将其格式化为与RagModel一起使用。
示例:
>>> # To load the default "wiki_dpr" dataset with 21M passages from wikipedia (index name is 'compressed' or 'exact')
>>> from transformers import RagRetriever
>>> retriever = RagRetriever.from_pretrained(
... "facebook/dpr-ctx_encoder-single-nq-base", dataset="wiki_dpr", index_name="compressed"
... )
>>> # To load your own indexed dataset built with the datasets library. More info on how to build the indexed dataset in examples/rag/use_own_knowledge_dataset.py
>>> from transformers import RagRetriever
>>> dataset = (
... ...
... ) # dataset must be a datasets.Datasets object with columns "title", "text" and "embeddings", and it must have a faiss index
>>> retriever = RagRetriever.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", indexed_dataset=dataset)
>>> # To load your own indexed dataset built with the datasets library that was saved on disk. More info in examples/rag/use_own_knowledge_dataset.py
>>> from transformers import RagRetriever
>>> dataset_path = "path/to/my/dataset" # dataset saved via *dataset.save_to_disk(...)*
>>> index_path = "path/to/my/index.faiss" # faiss index saved via *dataset.get_index("embeddings").save(...)*
>>> retriever = RagRetriever.from_pretrained(
... "facebook/dpr-ctx_encoder-single-nq-base",
... index_name="custom",
... passages_path=dataset_path,
... index_path=index_path,
... )
>>> # To load the legacy index built originally for Rag's paper
>>> from transformers import RagRetriever
>>> retriever = RagRetriever.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", index_name="legacy")
检索器初始化函数。它将索引加载到内存中。
postprocess_docs
< source >( docs input_strings prefix n_docs return_tensors = None ) → tuple(tensors)
对检索到的docs
进行后处理,并将其与input_strings
结合。
检索
< source >( question_hidden_states: ndarray n_docs: int ) → Tuple[np.ndarray, np.ndarray, List[dict]]
参数
- question_hidden_states (
np.ndarray
of shape(batch_size, vector_size)
) — 用于检索的一批查询向量。 - n_docs (
int
) — 每次查询检索的文档数量。
返回
Tuple[np.ndarray, np.ndarray, List[dict]]
包含以下对象的元组:
- retrieved_doc_embeds (
np.ndarray
形状为(batch_size, n_docs, dim)
) — 每个查询的检索文档的检索嵌入。 - doc_ids (
np.ndarray
形状为(batch_size, n_docs)
) — 索引中文档的ID - doc_dicts (
List[dict]
): 每个查询的retrieved_doc_embeds
示例。
检索指定question_hidden_states
的文档。
RagModel
类 transformers.RagModel
< source >( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None question_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None generator: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None retriever: typing.Optional[transformers.models.rag.retrieval_rag.RagRetriever] = None **kwargs )
参数
- config (RagConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化时不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- question_encoder (PreTrainedModel) —
一个与
retriever
封装的faiss索引兼容的编码器模型。 - generator (PreTrainedModel) — 在RAG架构中用作生成器的seq2seq模型。
- retriever (RagRetriever) — 一个检索器类,封装了一个faiss索引,用于查询以获取当前输入的上下文文档。
RagModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
RAG 是一个 seq2seq 模型,它封装了两个核心组件:问题编码器和生成器。在前向传递过程中,我们使用问题编码器对输入进行编码,并将其传递给检索器以提取相关的上下文文档。然后将这些文档附加到输入之前。这种上下文化的输入被传递给生成器。
问题编码器可以是任何自编码模型,最好是DPRQuestionEncoder,生成器可以是任何序列到序列模型,最好是BartForConditionalGeneration。
该模型可以使用RagRetriever进行端到端生成初始化,也可以与检索器的输出结合使用,分多个步骤进行---更多详情请参见示例。该模型兼容任何自动编码模型作为question_encoder
,以及任何带有语言模型头的序列到序列模型作为generator
。它已经使用DPRQuestionEncoder作为question_encoder
,以及BartForConditionalGeneration或T5ForConditionalGeneration作为generator
进行了测试。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None doc_scores: typing.Optional[torch.FloatTensor] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_retrieved: typing.Optional[bool] = None n_docs: typing.Optional[int] = None ) → transformers.models.rag.modeling_rag.RetrievAugLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. RagConfig, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices. - attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — Tuple consists of (generator_enc_last_hidden_state
, optional:generator_enc_hidden_states
, optional:generator_enc_attentions
).generator_enc_last_hidden_state
of shape(batch_size, n_docs * sequence_length, hidden_size)
is a sequence of hidden-states at the output of the last layer of the generator’s encoder.由(RagModel)模型在解码期间使用。
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — 为生成任务提供。默认情况下为None
,根据您使用的RAG实例的生成器模型的说明进行构建。 - decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, 可选) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - past_key_values (
tuple(tuple(torch.FloatTensor))
) — 元组由两个元素组成:RAG模型的encoder_outputs
(参见encoder_outputs
)和 底层生成器的past_key_values
。可用于加速解码。past_key_values
在 (RagTokenForGeneration) 模型的解码过程中使用。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化,则必须在 forward 过程中提供doc_scores
。doc_scores
可以通过question_encoder_last_hidden_state
和retrieved_doc_embeds
计算,更多信息请参见示例。 - context_input_ids (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器input_ids
后处理的输入 ID。如果模型没有使用retriever
初始化,则必须在前向传递中提供context_input_ids
。context_input_ids
由__call__()
返回。 - context_attention_mask (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
,optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器input_ids
由检索器后处理的注意力掩码。如果模型没有使用retriever
初始化,则必须在前向传递中提供context_attention_mask
。context_attention_mask
由__call__()
返回。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - output_retrieved(
bool
, 可选) — 是否返回retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
和context_attention_mask
。有关更多详细信息,请参见返回的张量。 - n_docs (
int
, 可选, 默认为 `config.n_docs“) — 要检索的文档数量和/或为其生成答案的文档数量。
返回
transformers.models.rag.modeling_rag.RetrievAugLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.rag.modeling_rag.RetrievAugLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(RagConfig)和输入。
-
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。分数可能针对每个词汇标记在所有文档上进行边缘化。 -
doc_scores (
torch.FloatTensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)与question_encoder_last_hidden_state
之间的分数。 -
past_key_values (
List[torch.FloatTensor]
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的torch.FloatTensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可用于 (参见
past_key_values
输入)以加速顺序解码。 -
retrieved_doc_embeds (
torch.FloatTensor
形状为(batch_size, config.n_docs, hidden_size)
, 可选, 当 output_retrieved=True 时返回) — 由检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起使用以计算doc_scores
。 -
retrieved_doc_ids (
torch.LongTensor
形状为(batch_size, config.n_docs)
, 可选, 当 output_retrieved=True 时返回) — 由检索器检索到的嵌入文档的索引。 -
context_input_ids (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 由检索器从检索到的文档和问题编码器input_ids
后处理的输入 ID。 -
context_attention_mask (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 由检索器从检索到的文档和问题编码器input_ids
后处理的注意力掩码。 -
question_encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 问题编码器最后一层的隐藏状态序列,模型池化输出。 -
question_enc_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入的输出,一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。问题编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
question_enc_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。问题编码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
generator_enc_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 生成器编码器最后一层的隐藏状态序列,模型池化输出。 -
generator_enc_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入的输出,一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。生成器编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_enc_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器编码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
generator_dec_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入的输出,一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_dec_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
generator_cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的交叉注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。
RagModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> 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
类 transformers.RagSequenceForGeneration
< source >( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None question_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None generator: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None retriever: typing.Optional[transformers.models.rag.retrieval_rag.RagRetriever] = None **kwargs )
参数
- config (RagConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
- question_encoder (PreTrainedModel) —
一个与
retriever
封装的faiss索引兼容的编码器模型。 - generator (PreTrainedModel) — 在RAG架构中用作生成器的seq2seq模型。
- retriever (RagRetriever) — 一个检索器类,封装了一个faiss索引,用于查询以获取当前输入的上下文文档。
RagSequenceForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
一个RAG序列模型的实现。它在前向传播中执行RAG序列特定的边缘化。
RAG 是一个 seq2seq 模型,它封装了两个核心组件:问题编码器和生成器。在前向传递过程中,我们使用问题编码器对输入进行编码,并将其传递给检索器以提取相关的上下文文档。然后将这些文档附加到输入之前。这种上下文化的输入被传递给生成器。
问题编码器可以是任何自编码模型,最好是DPRQuestionEncoder,生成器可以是任何序列到序列模型,最好是BartForConditionalGeneration。
该模型可以使用RagRetriever进行端到端生成初始化,也可以与检索器的输出结合使用,分多个步骤进行---更多详情请参见示例。该模型兼容任何自动编码模型作为question_encoder
,以及任何带有语言模型头的序列到序列模型作为generator
。它已经使用DPRQuestionEncoder作为question_encoder
,以及BartForConditionalGeneration或T5ForConditionalGeneration作为generator
进行了测试。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None doc_scores: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_retrieved: typing.Optional[bool] = None exclude_bos_score: typing.Optional[bool] = None reduce_loss: typing.Optional[bool] = None labels: typing.Optional[torch.LongTensor] = None n_docs: typing.Optional[int] = None **kwargs ) → transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. RagConfig, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices. - attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — Tuple consists of (generator_enc_last_hidden_state
, optional:generator_enc_hidden_states
, optional:generator_enc_attentions
).generator_enc_last_hidden_state
of shape(batch_size, n_docs * sequence_length, hidden_size)
is a sequence of hidden-states at the output of the last layer of the generator’s encoder.由(RagModel)模型在解码期间使用。
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — 为生成任务提供。默认情况下为None
,根据您使用的RAG实例的生成器模型的说明进行构建。 - decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, 可选) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - past_key_values (
tuple(tuple(torch.FloatTensor))
) — 元组由两个元素组成:RAG模型的encoder_outputs
(参见encoder_outputs
)和 底层生成器的past_key_values
。可用于加速解码。past_key_values
在 (RagTokenForGeneration) 模型的解码过程中使用。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化,则必须在前向传递中提供doc_scores
。doc_scores
可以通过question_encoder_last_hidden_state
和retrieved_doc_embeds
计算,更多信息请参见示例。 - context_input_ids (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
经过检索器后处理的输入 ID。如果模型没有使用retriever
初始化,则必须在正向传递中提供context_input_ids
。context_input_ids
由__call__()
返回。 - context_attention_mask (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
,optional, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的注意力掩码。如果模型没有使用retriever
初始化,则必须在前向传递中提供context_attention_mask
。context_attention_mask
由__call__()
返回。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - output_retrieved(
bool
, 可选) — 是否返回retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
和context_attention_mask
。有关更多详细信息,请参见返回的张量。 - n_docs (
int
, optional, defaults to `config.n_docs“) — 要检索的文档数量和/或为其生成答案的文档数量。 - exclude_bos_score (
bool
, optional) — 仅在传递了labels
时相关。如果为True
,则在计算损失时忽略BOS令牌的分数。 - reduce_loss (
bool
, 可选) — 仅在传递了labels
时相关。如果为True
,则使用torch.Tensor.sum
操作减少 NLL 损失。 - kwargs (
Dict[str, any]
, 可选, 默认为{}
) — 遗留字典,这是必需的,以便模型可以使用 generate() 函数。
返回
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(RagConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。分数可能针对每个词汇标记在所有文档上进行边缘化。 -
doc_scores (
torch.FloatTensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)与question_encoder_last_hidden_state
之间的分数。 -
past_key_values (
List[torch.FloatTensor]
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的torch.FloatTensor
列表,每个张量形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可用于 (见
past_key_values
输入)加速顺序解码。 -
retrieved_doc_embeds (
torch.FloatTensor
形状为(batch_size, config.n_docs, hidden_size)
,可选,当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起用于计算doc_scores
。 -
retrieved_doc_ids (
torch.LongTensor
形状为(batch_size, config.n_docs)
,可选,当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档的索引。 -
context_input_ids (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
,可选,当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的输入 ID。 -
context_attention_mask (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
,可选,当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的注意力掩码。 -
question_encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 问题编码器最后一层的隐藏状态序列,模型池化输出。 -
question_enc_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出,一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。问题编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
question_enc_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。问题编码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
generator_enc_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 生成器编码器最后一层的隐藏状态序列,模型池化输出。 -
generator_enc_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出,一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。生成器编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_enc_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器编码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
generator_dec_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出,一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_dec_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
generator_cross_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的交叉注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。
RagSequenceForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> 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,
... )
生成
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None doc_scores: typing.Optional[torch.FloatTensor] = None do_deduplication: typing.Optional[bool] = None num_return_sequences: typing.Optional[int] = None num_beams: typing.Optional[int] = None n_docs: typing.Optional[int] = None **model_kwargs ) → torch.LongTensor
形状为 (batch_size * num_return_sequences, sequence_length)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于生成提示的序列。如果未传递input_ids
,则必须提供context_input_ids
。 - attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- context_input_ids (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器输入ID中后处理的输入ID,由检索器生成。 - context_attention_mask (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — Attention mask post-processed from the retrieved documents and the question encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化或未提供input_ids
,则必须向forward传递提供context_input_ids
和context_attention_mask
。它们由__call__()
返回。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.如果模型没有使用
retriever
初始化或未提供input_ids
,则必须向前向传递提供doc_scores
。doc_scores
由__call__()
返回。 - do_deduplication (
bool
, 可选) — 是否对来自不同上下文文档的生成结果进行去重。如果在使用分布式后端进行训练时使用,必须设置为False
。 - num_return_sequences(
int
, 可选, 默认为 1) — 批次中每个元素独立计算的返回序列的数量。请注意,这不是我们传递给generator
的[generate()](/docs/transformers/v4.47.1/en/main_classes/text_generation#transformers.GenerationMixin.generate)
函数的值, 在那里我们将num_return_sequences
设置为num_beams
. - num_beams (
int
, 可选, 默认为 1) — 用于束搜索的束数量。1 表示不进行束搜索。 - n_docs (
int
, 可选, 默认为config.n_docs
) — 要检索的文档数量和/或为其生成答案的文档数量。 - kwargs (
Dict[str, Any]
, 可选) — 额外的 kwargs 将被传递给 generate().
返回
torch.LongTensor
的形状为 (batch_size * num_return_sequences, sequence_length)
生成的序列。第二维度(序列长度)要么等于max_length
,要么如果所有批次由于eos_token_id
提前结束则较短。
实现RAG序列“彻底”解码。阅读generate()文档以获取有关如何设置其他生成输入参数的更多信息。
RagTokenForGeneration
类 transformers.RagTokenForGeneration
< source >( config: typing.Optional[transformers.configuration_utils.PretrainedConfig] = None question_encoder: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None generator: typing.Optional[transformers.modeling_utils.PreTrainedModel] = None retriever: typing.Optional[transformers.models.rag.retrieval_rag.RagRetriever] = None **kwargs )
参数
- config (RagConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化时不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- question_encoder (PreTrainedModel) —
一个与
retriever
封装的faiss索引兼容的编码器模型。 - generator (PreTrainedModel) — 在RAG架构中用作生成器的seq2seq模型。
- retriever (RagRetriever) — 一个检索器类,封装了一个faiss索引,用于查询以获取当前输入的上下文文档。
RagTokenForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
一个RAG-token模型的实现。它在前向传播中执行RAG-token特定的边缘化。
RAG 是一个 seq2seq 模型,它封装了两个核心组件:问题编码器和生成器。在前向传递过程中,我们使用问题编码器对输入进行编码,并将其传递给检索器以提取相关的上下文文档。然后将这些文档附加到输入之前。这种上下文化的输入被传递给生成器。
问题编码器可以是任何自编码模型,最好是DPRQuestionEncoder,生成器可以是任何序列到序列模型,最好是BartForConditionalGeneration。
该模型可以使用RagRetriever进行端到端生成初始化,也可以与检索器的输出结合使用,分多个步骤进行---更多详情请参见示例。该模型兼容任何自动编码模型作为question_encoder
,以及任何带有语言模型头的序列到序列模型作为generator
。它已经使用DPRQuestionEncoder作为question_encoder
,以及BartForConditionalGeneration或T5ForConditionalGeneration作为generator
进行了测试。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None doc_scores: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_retrieved: typing.Optional[bool] = None do_marginalize: typing.Optional[bool] = None reduce_loss: typing.Optional[bool] = None labels: typing.Optional[torch.LongTensor] = None n_docs: typing.Optional[int] = None **kwargs ) → transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput or tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. RagConfig, used to initialize the model, specifies which generator to use, it also specifies a compatible generator tokenizer. Use that tokenizer class to obtain the indices. - attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, optional) — Tuple consists of (generator_enc_last_hidden_state
, optional:generator_enc_hidden_states
, optional:generator_enc_attentions
).generator_enc_last_hidden_state
of shape(batch_size, n_docs * sequence_length, hidden_size)
is a sequence of hidden-states at the output of the last layer of the generator’s encoder.由(RagModel)模型在解码期间使用。
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — 为生成任务提供。默认情况下为None
,根据您使用的RAG实例的生成器模型的说明进行构建。 - decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, 可选) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - past_key_values (
tuple(tuple(torch.FloatTensor))
) — 元组由两个元素组成:RAG模型的encoder_outputs
(参见encoder_outputs
)和 底层生成器的past_key_values
。可用于加速解码。past_key_values
在 (RagTokenForGeneration) 模型的解码过程中使用。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化,则必须在前向传递中提供doc_scores
。doc_scores
可以通过question_encoder_last_hidden_state
和retrieved_doc_embeds
计算,更多信息请参见示例。 - context_input_ids (
torch.LongTensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 从检索到的文档和问题编码器input_ids
后处理的输入 ID。如果模型没有使用retriever
初始化,则必须在前向传递中提供context_input_ids
。context_input_ids
由__call__()
返回。 - context_attention_mask (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
,可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
通过检索器后处理的注意力掩码。如果模型没有使用retriever
初始化,则必须在前向传递中提供context_attention_mask
。context_attention_mask
由__call__()
返回。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,将返回past_key_values
键值状态,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - output_retrieved(
bool
, 可选) — 是否返回retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
和context_attention_mask
。有关更多详细信息,请参见返回的张量。 - n_docs (
int
, 可选, 默认为 `config.n_docs“) — 要检索的文档数量和/或为其生成答案的文档数量。 - do_marginalize (
bool
, 可选) — 如果为True
,则通过使用torch.nn.functional.log_softmax
对所有文档进行边缘化处理来获得 logits。 - reduce_loss (
bool
, 可选) — 仅在传递了labels
时相关。如果为True
,则使用torch.Tensor.sum
操作减少NLL损失。 - kwargs (
Dict[str, any]
, 可选, 默认为{}
) — 遗留字典,这是必需的,以便模型可以使用 generate() 函数。
返回
transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.rag.modeling_rag.RetrievAugLMMarginOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(RagConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。分数可能针对每个词汇标记在所有文档上进行边缘化。 -
doc_scores (
torch.FloatTensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。 -
past_key_values (
List[torch.FloatTensor]
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的torch.FloatTensor
列表,每个张量形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可用于 (见
past_key_values
输入)加速顺序解码。 -
retrieved_doc_embeds (
torch.FloatTensor
形状为(batch_size, config.n_docs, hidden_size)
,可选,当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起用于计算doc_scores
。 -
retrieved_doc_ids (
torch.LongTensor
形状为(batch_size, config.n_docs)
,可选,当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档的索引。 -
context_input_ids (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
,可选,当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的输入 ID。 -
context_attention_mask (
torch.LongTensor
形状为(batch_size * config.n_docs, config.max_combined_length)
,可选,当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的注意力掩码。 -
question_encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 问题编码器最后一层的隐藏状态序列,模型池化输出。 -
question_enc_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出,一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。问题编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
question_enc_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。问题编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_enc_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 生成器编码器最后一层的隐藏状态序列。 -
generator_enc_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出,一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。生成器编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_enc_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_dec_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入输出,一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_dec_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_cross_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的交叉注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
RagTokenForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> 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)
生成
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.LongTensor] = None context_input_ids: typing.Optional[torch.LongTensor] = None context_attention_mask: typing.Optional[torch.LongTensor] = None doc_scores: typing.Optional[torch.FloatTensor] = None n_docs: typing.Optional[int] = None generation_config: typing.Optional[transformers.generation.configuration_utils.GenerationConfig] = None prefix_allowed_tokens_fn: typing.Callable[[int, torch.Tensor], typing.List[int]] = None logits_processor: typing.Optional[transformers.generation.logits_process.LogitsProcessorList] = [] stopping_criteria: typing.Optional[transformers.generation.stopping_criteria.StoppingCriteriaList] = [] **kwargs ) → torch.LongTensor
的形状为 (batch_size * num_return_sequences, sequence_length)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, 可选) — 用于生成提示的序列。如果未传递input_ids
,则必须提供context_input_ids
。 - attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- 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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。 - doc_scores (
torch.FloatTensor
of shape(batch_size, config.n_docs)
) — Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。 - n_docs (
int
, 可选, 默认为config.n_docs
) — 要检索的文档数量和/或为其生成答案的文档数量。 - 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 ofgeneration_config
will override them. Ifgeneration_config
is not provided, the default will be used, which has the following loading priority: 1) from thegeneration_config.json
model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit GenerationConfig’s default values, whose documentation should be checked to parameterize generation. - prefix_allowed_tokens_fn (
Callable[[int, torch.Tensor], List[int]]
, 可选) — 如果提供,此函数将约束束搜索,使其在每一步仅允许特定的标记。如果未提供,则不应用任何约束。此函数接受2个参数inputs_ids
和批次 IDbatch_id
。它必须返回一个列表,其中包含根据先前生成的标记inputs_ids
和批次 IDbatch_id
条件允许的下一生成步骤的标记。此参数对于基于前缀的条件生成非常有用,如 自回归实体检索 中所述。 - logits_processor (
LogitsProcessorList
, 可选) — 自定义的logits处理器,用于补充从参数和模型配置中构建的默认logits处理器。如果传递了一个已经通过参数或模型配置创建的logit处理器,则会抛出错误。 - stopping_criteria (
StoppingCriteriaList
, 可选) — 自定义的停止标准,用于补充由参数和模型配置构建的默认停止标准。如果传递的停止标准已经由参数或模型配置创建,则会抛出错误。 - kwargs (
Dict[str, Any]
, 可选) —generate_config
的临时参数化和/或额外的模型特定 kwargs,这些参数将被转发到模型的forward
函数中。
返回
torch.LongTensor
的形状为 (batch_size * num_return_sequences, sequence_length)
生成的序列。第二维度(sequence_length)等于max_length
,或者如果所有批次由于eos_token_id
而提前结束,则较短。
实现RAG令牌解码。
TFRagModel
类 transformers.TFRagModel
< source >( config: 可选[PretrainedConfig] = 无 question_encoder: 可选[TFPreTrainedModel] = 无 generator: 可选[TFPreTrainedModel] = 无 retriever: 可选[RagRetriever] = 无 load_weight_prefix: 可选[str] = 无 **kwargs )
参数
- config (RagConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- question_encoder (TFPreTrainedModel) —
一个与
retriever
封装的faiss索引兼容的编码器模型。 - generator (TFPreTrainedModel) — 在RAG架构中用作生成器的seq2seq模型。
- retriever (RagRetriever) — 一个检索器类,封装了一个faiss索引,用于查询以获取当前输入的上下文文档。
TFRagModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
RAG 是一个序列到序列模型,它封装了两个核心组件:问题编码器和生成器。 在前向传播过程中,我们使用问题编码器对输入进行编码,并将其传递给检索器以提取 相关的上下文文档。然后将这些文档附加到输入之前。这种上下文化的输入被传递给 生成器。
问题编码器可以是任何自编码模型,最好是TFDPRQuestionEncoder,而生成器可以是任何序列到序列模型,最好是TFBartForConditionalGeneration。
该模型可以使用RagRetriever进行端到端生成初始化,也可以与检索器的输出结合使用,分多个步骤进行---更多详情请参见示例。该模型兼容任何自编码模型作为question_encoder
,以及任何带有语言模型头的seq2seq模型作为generator
。它已经使用TFDPRQuestionEncoder作为question_encoder
和TFBartForConditionalGeneration作为generator
进行了测试。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是 Tensorflow keras.Model 的子类。将其作为常规的 TF 2.0 Keras 模型使用,并参考 TF 2.0 文档以获取与一般用法和行为相关的所有信息。
该模型目前处于开发状态,因为它现在仅完全支持eager模式,并且可能无法以SavedModel格式导出。
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None past_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = None doc_scores: np.ndarray | tf.Tensor | None = None context_input_ids: np.ndarray | tf.Tensor | None = None context_attention_mask: np.ndarray | tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None output_retrieved: bool | None = None n_docs: int | None = None return_dict: bool | None = None training: bool = False **kwargs ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput
或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — 词汇表中输入序列标记的索引。RagConfig,用于初始化模型,指定使用哪个生成器,它还指定了一个兼容的生成器分词器。使用该分词器类来获取索引。 - 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.由(TFRagModel)模型在解码期间使用。
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 为生成任务提供。默认情况下为None
,根据您使用的RAG实例的生成器模型的说明进行构建。 - decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, optional) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - past_key_values (
tuple(tuple(tf.Tensor))
) — 元组由两个元素组成:RAG模型的encoder_outputs
(参见encoder_outputs
)和 底层生成器的past_key_values
。可用于加速解码。past_key_values
在 (RagTokenForGeneration) 模型的解码过程中使用。 - doc_scores (
tf.Tensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化,则必须在前向传递中提供doc_scores
。doc_scores
可以通过question_encoder_last_hidden_state
和retrieved_doc_embeds
计算,更多信息请参见示例。 - 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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。context_attention_mask (形状为(batch_size * config.n_docs, config.max_combined_length)
的tf.Tensor
,可选,当output_retrieved=True时返回):由检索器和问题编码器input_ids
从检索到的文档中后处理的注意力掩码。如果模型没有使用
retriever
初始化,则必须向forward pass提供context_attention_mask
。context_attention_mask
由__call__()
返回。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - output_retrieved(
bool
, 可选) — 是否返回retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
和context_attention_mask
。有关更多详细信息,请参见返回的张量。 - return_dict (
bool
, 可选) — 是否返回一个TFRetrievAugLMOutput
而不是一个普通的元组。 - n_docs (
int
, optional, defaults to `config.n_docs“) — 要检索的文档数量和/或为其生成答案的文档数量。
返回
transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput
或 tuple(tf.Tensor)
一个 transformers.models.rag.modeling_tf_rag.TFRetrievAugLMOutput
或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置(RagConfig)和输入。
-
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。分数可能针对每个词汇标记在所有文档上进行边缘化。 -
past_key_values (
List[tf.Tensor]
, 可选, 当use_cache=True
被传递或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
doc_scores (
tf.Tensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。 -
retrieved_doc_embeds (
tf.Tensor
形状为(batch_size, config.n_docs, hidden_size)
, 可选, 当 output_retrieved=True 时返回) — 由检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起用于计算doc_scores
。 -
retrieved_doc_ids (
tf.Tensor
形状为(batch_size, config.n_docs)
, 可选, 当 output_retrieved=True 时返回) — 由检索器检索到的嵌入文档的索引。 -
context_input_ids (
tf.Tensor
形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 由检索器从检索到的文档和问题编码器input_ids
后处理的输入 ID。 -
context_attention_mask (
tf.Tensor
形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 由检索器从检索到的文档和问题编码器input_ids
后处理的注意力掩码。 -
question_encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 问题编码器最后一层的隐藏状态序列,模型的池化输出。 -
question_enc_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出,一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。问题编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
question_enc_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。问题编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_enc_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 生成器编码器最后一层的隐藏状态序列,模型的输出。 -
generator_enc_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出,一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。生成器编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_enc_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_dec_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出,一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_dec_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
TFRagModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> 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
类 transformers.TFRagSequenceForGeneration
< source >( config: 可选[PretrainedConfig] = 无 question_encoder: 可选[TFPreTrainedModel] = 无 generator: 可选[TFPreTrainedModel] = 无 retriever: 可选[RagRetriever] = 无 **kwargs )
参数
- config (RagConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- question_encoder (TFPreTrainedModel) —
一个与
retriever
封装的faiss索引兼容的编码器模型。 - generator (TFPreTrainedModel) — 在RAG架构中用作生成器的seq2seq模型。
- retriever (RagRetriever) — 一个检索器类,封装了一个faiss索引,用于查询以获取当前输入的上下文文档。
TFRagSequenceForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
一个TF RAG序列模型的实现。它在前向传播中执行RAG序列特定的边缘化。
RAG 是一个序列到序列模型,它封装了两个核心组件:问题编码器和生成器。 在前向传播过程中,我们使用问题编码器对输入进行编码,并将其传递给检索器以提取 相关的上下文文档。然后将这些文档附加到输入之前。这种上下文化的输入被传递给 生成器。
问题编码器可以是任何自编码模型,最好是TFDPRQuestionEncoder,而生成器可以是任何序列到序列模型,最好是TFBartForConditionalGeneration。
该模型可以使用RagRetriever进行端到端生成初始化,也可以与检索器的输出结合使用,分多个步骤进行---更多详情请参见示例。该模型兼容任何自编码模型作为question_encoder
,以及任何带有语言模型头的seq2seq模型作为generator
。它已经使用TFDPRQuestionEncoder作为question_encoder
和TFBartForConditionalGeneration作为generator
进行了测试。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是 Tensorflow keras.Model 的子类。将其作为常规的 TF 2.0 Keras 模型使用,并参考 TF 2.0 文档以获取与一般用法和行为相关的所有信息。
该模型目前处于开发状态,因为它现在仅完全支持eager模式,并且可能无法以SavedModel格式导出。
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None doc_scores: np.ndarray | tf.Tensor | None = None context_input_ids: np.ndarray | tf.Tensor | None = None context_attention_mask: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None output_retrieved: Optional[bool] = None n_docs: Optional[int] = None exclude_bos_score: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None reduce_loss: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False **kwargs ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput
或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
形状为(batch_size, sequence_length)
) — 词汇表中输入序列标记的索引。RagConfig,用于初始化模型,指定使用哪个生成器,它还指定了一个兼容的生成器分词器。使用该分词器类来获取索引。 - 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.由(TFRagModel)模型在解码期间使用。
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 为生成任务提供。默认情况下为None
,根据您使用的RAG实例的生成器模型的说明进行构建。 - decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, optional) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - past_key_values (
tuple(tuple(tf.Tensor))
) — 元组由两个元素组成:RAG模型的encoder_outputs
(参见encoder_outputs
)和 底层生成器的past_key_values
。可用于加速解码。past_key_values
在 (RagTokenForGeneration) 模型的解码过程中使用。 - doc_scores (
tf.Tensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)与question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化,则必须在前向传递中提供doc_scores
。doc_scores
可以通过question_encoder_last_hidden_state
和retrieved_doc_embeds
计算,更多信息请参见示例。 - 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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。context_attention_mask (形状为(batch_size * config.n_docs, config.max_combined_length)
的tf.Tensor
,可选,当output_retrieved=True时返回):由检索器和问题编码器input_ids
从检索到的文档中后处理的注意力掩码。如果模型没有使用
retriever
初始化,则必须向forward pass提供context_attention_mask
。context_attention_mask
由__call__()
返回。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - output_retrieved(
bool
, 可选) — 是否返回retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
和context_attention_mask
。有关更多详细信息,请参见返回的张量。 - return_dict (
bool
, 可选) — 是否返回一个TFRetrievAugLMOutput
而不是一个普通的元组。 - n_docs (
int
, 可选, 默认为 `config.n_docs“) — 要检索的文档数量和/或为其生成答案的文档数量。 - exclude_bos_score (
bool
, 可选) — 仅在传递了labels
时相关。如果为True
,则在计算损失时忽略BOS标记的分数。 - labels (
tf.Tensor
或np.ndarray
形状为(batch_size, sequence_length)
, 可选) — 用于根据Rag-Sequence模型公式计算交叉熵分类损失的标签。有关Rag-Sequence公式的详细信息,请参见 https://arxiv.org/pdf/2005.11401.pdf 第2.1节。索引应在[0, ..., config.vocab_size - 1]
范围内。 - reduce_loss (
bool
, optional) — 仅在传递了labels
时相关。如果为True
,则使用tf.Tensor.sum
操作减少NLL损失。 - kwargs (
Dict[str, any]
, 可选, 默认为{}
) — 遗留字典,这是必需的,以便模型可以使用 generate() 函数。
返回
transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput
或 tuple(tf.Tensor)
一个 transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput
或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置 (RagConfig) 和输入。
-
loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 语言建模损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。分数可能针对每个词汇标记在所有文档上进行边缘化。 -
past_key_values (
List[tf.Tensor]
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可用于 (参见
past_key_values
输入)加速顺序解码。 -
doc_scores (
tf.Tensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。 -
retrieved_doc_embeds (
tf.Tensor
形状为(batch_size, config.n_docs, hidden_size)
, 可选, 当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起使用以计算doc_scores
。 -
retrieved_doc_ids (
tf.Tensor
(int32) 形状为(batch_size, config.n_docs)
, 可选, 当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档的索引。 -
context_input_ids (
tf.Tensor
(int32) 形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的输入 ID。 -
context_attention_mask (
tf.Tensor
(int32) 形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的注意力掩码。 -
question_encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 问题编码器最后一层的隐藏状态序列,模型的池化输出。 -
question_enc_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出,一个用于每层输出)形状为(batch_size, sequence_length, hidden_size)
。问题编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
question_enc_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。问题编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_enc_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 生成器编码器最后一层的隐藏状态序列,模型的输出。 -
generator_enc_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出,一个用于每层输出)形状为(batch_size, sequence_length, hidden_size)
。生成器编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_enc_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_dec_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出,一个用于每层输出)形状为(batch_size, sequence_length, hidden_size)
。生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_dec_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
TFRagSequenceForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> 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)
生成
< source >( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None context_input_ids = None context_attention_mask = None doc_scores = None do_deduplication = None num_return_sequences = None num_beams = None n_docs = None **model_kwargs ) → tf.Tensor
形状为 (batch_size * num_return_sequences, sequence_length)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, 可选) — 用于生成提示的序列。如果未传递input_ids
,则必须提供context_input_ids
。 - attention_mask (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在填充标记索引上执行注意力的掩码。掩码值在[0, 1]
中选择:- 1 表示 未掩码的标记,- 0 表示掩码的标记。什么是注意力 掩码? - context_input_ids (
tf.Tensor
of shape(batch_size * config.n_docs, config.max_combined_length)
, optional, returned when output_retrieved=True) — 由检索器从检索到的文档和问题编码器输入ID后处理的输入ID。 - context_attention_mask (
tf.Tensor
形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
通过检索器后处理的注意力掩码。如果模型没有使用retriever
初始化或未提供input_ids
, 则必须在前向传递中提供context_input_ids
和context_attention_mask
。它们由__call__()
返回。 - doc_scores (
tf.Tensor
of shape(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化或 没有提供input_ids
,则必须在前向传递中提供doc_scores
。doc_scores
由__call__()
返回。 - do_deduplication (
bool
, 可选) — 是否对来自不同上下文文档的生成结果进行去重。如果在使用分布式后端进行训练时使用,必须设置为False
。 - num_return_sequences(
int
, 可选, 默认为 1) — 批次中每个元素独立计算的返回序列的数量。请注意,这不是我们传递给generator
的[generate()](/docs/transformers/v4.47.1/en/main_classes/text_generation#transformers.GenerationMixin.generate)
函数的值, 在那里我们将num_return_sequences
设置为num_beams
. - num_beams (
int
, 可选, 默认为 1) — 用于束搜索的束数量。1 表示不进行束搜索。 - n_docs (
int
, 可选, 默认为config.n_docs
) — 要检索的文档数量和/或为其生成答案的文档数量。 - kwargs (
Dict[str, Any]
, 可选) — 额外的 kwargs 将被传递给 generate()
返回
tf.Tensor
的形状为 (batch_size * num_return_sequences, sequence_length)
生成的序列。第二维度(序列长度)要么等于max_length
,要么如果所有批次由于eos_token_id
而提前结束,则较短。
实现RAG序列“彻底”解码。阅读generate()文档以获取有关如何设置其他生成输入参数的更多信息。
TFRagTokenForGeneration
类 transformers.TFRagTokenForGeneration
< source >( config: 可选[PretrainedConfig] = 无 question_encoder: 可选[TFPreTrainedModel] = 无 generator: 可选[TFPreTrainedModel] = 无 retriever: 可选[RagRetriever] = 无 **kwargs )
参数
- config (RagConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- question_encoder (TFPreTrainedModel) —
一个与
retriever
封装的faiss索引兼容的编码器模型。 - generator (TFPreTrainedModel) — 在RAG架构中用作生成器的seq2seq模型。
- retriever (RagRetriever) — 一个检索器类,封装了一个faiss索引,用于查询以获取当前输入的上下文文档。
TFRagTokenForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
一个TF RAG-token模型的实现。它在前向传播中执行RAG-token特定的边缘化。
RAG 是一个序列到序列模型,它封装了两个核心组件:问题编码器和生成器。 在前向传播过程中,我们使用问题编码器对输入进行编码,并将其传递给检索器以提取 相关的上下文文档。然后将这些文档附加到输入之前。这种上下文化的输入被传递给 生成器。
问题编码器可以是任何自编码模型,最好是TFDPRQuestionEncoder,而生成器可以是任何序列到序列模型,最好是TFBartForConditionalGeneration。
该模型可以使用RagRetriever进行端到端生成初始化,也可以与检索器的输出结合使用,分多个步骤进行---更多详情请参见示例。该模型兼容任何自编码模型作为question_encoder
,以及任何带有语言模型头的seq2seq模型作为generator
。它已经使用TFDPRQuestionEncoder作为question_encoder
和TFBartForConditionalGeneration作为generator
进行了测试。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是 Tensorflow keras.Model 的子类。将其作为常规的 TF 2.0 Keras 模型使用,并参考 TF 2.0 文档以获取与一般用法和行为相关的所有信息。
该模型目前处于开发状态,因为它现在仅完全支持eager模式,并且可能无法以SavedModel格式导出。
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: np.ndarray | tf.Tensor | None = None past_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = None doc_scores: np.ndarray | tf.Tensor | None = None context_input_ids: np.ndarray | tf.Tensor | None = None context_attention_mask: np.ndarray | tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None output_retrieved: bool | None = None n_docs: int | None = None do_marginalize: bool | None = None labels: np.ndarray | tf.Tensor | None = None reduce_loss: bool | None = None return_dict: bool | None = None training: bool = False **kwargs ) → transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput
或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — 词汇表中输入序列标记的索引。RagConfig,用于初始化模型,指定使用哪个生成器,它还指定了一个兼容的生成器分词器。使用该分词器类来获取索引。 - 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.由(TFRagModel)模型在解码期间使用。
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 为生成任务提供。默认情况下为None
,根据您使用的RAG实例的生成器模型的说明进行构建。 - decoder_attention_mask (
torch.BoolTensor
of shape(batch_size, target_sequence_length)
, 可选) — 默认行为:生成一个忽略decoder_input_ids
中填充标记的张量。默认情况下也会使用因果掩码。 - past_key_values (
tuple(tuple(tf.Tensor))
) — 元组由两个元素组成:RAG模型的encoder_outputs
(参见encoder_outputs
)和 底层生成器的past_key_values
。可用于加速解码。past_key_values
在 (RagTokenForGeneration) 模型的解码过程中使用。 - doc_scores (
tf.Tensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(见retrieved_doc_embeds
)与question_encoder_last_hidden_state
之间的分数。如果模型没有使用retriever
初始化,则必须在前向传递中提供doc_scores
。doc_scores
可以通过question_encoder_last_hidden_state
和retrieved_doc_embeds
计算,更多信息请参见示例。 - 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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。context_attention_mask (形状为(batch_size * config.n_docs, config.max_combined_length)
的tf.Tensor
,可选,当output_retrieved=True时返回):由检索器和问题编码器input_ids
从检索到的文档中后处理的注意力掩码。如果模型没有使用
retriever
初始化,则必须向forward pass提供context_attention_mask
。context_attention_mask
由__call__()
返回。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,将返回past_key_values
键值状态,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - output_retrieved(
bool
, 可选) — 是否返回retrieved_doc_embeds
,retrieved_doc_ids
,context_input_ids
和context_attention_mask
。有关更多详细信息,请参见返回的张量。 - return_dict (
bool
, 可选) — 是否返回一个TFRetrievAugLMOutput
而不是一个普通的元组。 - n_docs (
int
, 可选, 默认为 `config.n_docs“) — 要检索的文档数量和/或为其生成答案的文档数量. - do_marginalize (
bool
, 可选) — 如果为True
,则通过使用torch.nn.functional.log_softmax
对所有文档进行边缘化处理来对 logits 进行边缘化。 - labels (
tf.Tensor
或np.ndarray
形状为(batch_size, sequence_length)
, 可选) — 用于根据Rag-Token模型公式计算交叉熵分类损失的标签。有关Rag-Token公式的详细信息,请参见 https://arxiv.org/pdf/2005.11401.pdf 第2.1节。索引应在[0, ..., config.vocab_size - 1]
范围内。 - reduce_loss (
bool
, optional) — 仅在传递了labels
时相关。如果为True
,则使用tf.Tensor.sum
操作减少NLL损失。 - kwargs (
Dict[str, any]
, 可选, 默认为{}
) — 遗留字典,这是必需的,以便模型可以使用 generate() 函数.
返回
transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput
或 tuple(tf.Tensor)
一个 transformers.models.rag.modeling_tf_rag.TFRetrievAugLMMarginOutput
或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置 (RagConfig) 和输入。
-
loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 语言建模损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数。分数可能针对每个词汇标记在所有文档上进行边缘化。 -
past_key_values (
List[tf.Tensor]
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可用于 (参见
past_key_values
输入)加速顺序解码。 -
doc_scores (
tf.Tensor
形状为(batch_size, config.n_docs)
) — 每个检索到的文档嵌入(参见retrieved_doc_embeds
)和question_encoder_last_hidden_state
之间的分数。 -
retrieved_doc_embeds (
tf.Tensor
形状为(batch_size, config.n_docs, hidden_size)
, 可选, 当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档。与question_encoder_last_hidden_state
一起用于计算doc_scores
。 -
retrieved_doc_ids (
tf.Tensor
(int32) 形状为(batch_size, config.n_docs)
, 可选, 当 output_retrieved=True 时返回) — 检索器检索到的嵌入文档的索引。 -
context_input_ids (
tf.Tensor
(int32) 形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的输入 ID。 -
context_attention_mask (
tf.Tensor
(int32) 形状为(batch_size * config.n_docs, config.max_combined_length)
, 可选, 当 output_retrieved=True 时返回) — 从检索到的文档和问题编码器input_ids
后处理的注意力掩码。 -
question_encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 问题编码器最后一层的隐藏状态序列,模型的池化输出。 -
question_enc_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出,一个用于每层输出)形状为(batch_size, sequence_length, hidden_size)
。问题编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
question_enc_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。问题编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_enc_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 生成器编码器最后一层的隐藏状态序列,模型的输出。 -
generator_enc_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出,一个用于每层输出)形状为(batch_size, sequence_length, hidden_size)
。生成器编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_enc_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
generator_dec_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入输出,一个用于每层输出)形状为(batch_size, sequence_length, hidden_size)
。生成器解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
generator_dec_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。生成器解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
TFRagTokenForGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> 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)
生成
< source >( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None context_input_ids = None context_attention_mask = None doc_scores = None n_docs = None generation_config = None logits_processor = [] **kwargs ) → tf.Tensor
的形状为 (batch_size * num_return_sequences, sequence_length)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于生成提示的序列。如果未传递input_ids
,则必须提供context_input_ids
。 - 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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__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 encoderinput_ids
by the retriever.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。 - doc_scores (
tf.Tensor
of shape(batch_size, config.n_docs)
) — Score between each retrieved document embeddings (seeretrieved_doc_embeds
) andquestion_encoder_last_hidden_state
.如果模型没有使用
retriever
初始化,则必须向forward pass提供context_input_ids
。context_input_ids
由__call__()
返回。 - n_docs (
int
, 可选, 默认为config.n_docs
) — 要检索的文档数量和/或为其生成答案的文档数量。 - 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 ofgeneration_config
will override them. Ifgeneration_config
is not provided, the default will be used, which had the following loading priority: 1) from thegeneration_config.json
model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit GenerationConfig’s default values, whose documentation should be checked to parameterize generation. - logits_processor (
TFLogitsProcessorList
, 可选) — 自定义的logits处理器,用于补充从参数和模型配置中构建的默认logits处理器。如果传递了一个已经通过参数或模型配置创建的logit处理器,则会抛出错误。 - kwargs (
Dict[str, Any]
, 可选) —generate_config
的临时参数化和/或额外的模型特定 kwargs,这些参数将被转发到模型的forward
函数中。
返回
tf.Tensor
的形状为 (batch_size * num_return_sequences, sequence_length)
生成的序列。第二维度(sequence_length)要么等于max_length
,要么如果所有批次由于eos_token_id
提前结束,则较短。
实现TFRAG令牌解码。