Transformers 文档

DPR

DPR

Models Spaces

概述

密集段落检索(DPR)是一套用于最先进的开放领域问答研究的工具和模型。它由Vladimir Karpukhin、Barlas Oğuz、Sewon Min、Patrick Lewis、Ledell Wu、Sergey Edunov、Danqi Chen和Wen-tau Yih在开放领域问答的密集段落检索中提出。

论文的摘要如下:

开放域问答依赖于高效的段落检索来选择候选上下文,其中传统的稀疏向量空间模型,如TF-IDF或BM25,是事实上的方法。在这项工作中,我们展示了检索可以仅使用密集表示来实际实现,其中嵌入是通过简单的双编码器框架从少量问题和段落中学习的。在广泛的开放域QA数据集上评估时,我们的密集检索器在top-20段落检索准确率方面大幅优于强大的Lucene-BM25系统,绝对提升了9%-19%,并帮助我们的端到端QA系统在多个开放域QA基准上建立了新的最先进水平。

该模型由lhoestq贡献。原始代码可以在这里找到。

使用提示

  • DPR 包含三个模型:

    • Question encoder: encode questions as vectors
    • Context encoder: encode contexts as vectors
    • Reader: extract the answer of the questions inside retrieved contexts, along with a relevance score (high if the inferred span actually answers the question).

DPRConfig

transformers.DPRConfig

< >

( 词汇大小 = 30522 隐藏大小 = 768 隐藏层数 = 12 注意力头数 = 12 中间大小 = 3072 隐藏激活函数 = 'gelu' 隐藏层丢弃概率 = 0.1 注意力概率丢弃概率 = 0.1 最大位置嵌入 = 512 类型词汇大小 = 2 初始化范围 = 0.02 层归一化epsilon = 1e-12 填充标记ID = 0 位置嵌入类型 = 'absolute' 投影维度: int = 0 **kwargs )

参数

  • vocab_size (int, optional, defaults to 30522) — DPR模型的词汇表大小。定义了可以通过传递给BertModel的前向方法的inputs_ids表示的不同令牌。
  • hidden_size (int, optional, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数。
  • intermediate_size (int, optional, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu""relu""silu""gelu_new"
  • hidden_dropout_prob (float, optional, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, 默认为 0.1) — 注意力概率的丢弃比例。
  • max_position_embeddings (int, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • type_vocab_size (int, 可选, 默认为 2) — 传递给BertModeltoken_type_ids的词汇表大小。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • pad_token_id (int, optional, 默认为 0) — 填充标记的ID.
  • position_embedding_type (str, 可选, 默认为 "absolute") — 位置嵌入的类型。选择 "absolute", "relative_key", "relative_key_query" 中的一个。对于 位置嵌入,使用 "absolute"。有关 "relative_key" 的更多信息,请参阅 Self-Attention with Relative Position Representations (Shaw et al.)。 有关 "relative_key_query" 的更多信息,请参阅 Improve Transformer Models with Better Relative Position Embeddings (Huang et al.) 中的 方法 4.
  • projection_dim (int, optional, 默认为 0) — 上下文和问题编码器的投影维度。如果设置为零(默认),则不进行投影。

DPRConfig 是用于存储 DPRModel 配置的配置类。

这是用于存储DPRContextEncoderDPRQuestionEncoderDPRReader配置的配置类。它用于根据指定的参数实例化DPR模型的组件,定义模型组件的架构。使用默认值实例化配置将产生与facebook/dpr-ctx_encoder-single-nq-base架构类似的配置。

这个类是BertConfig的子类。请查看超类以获取所有kwargs的文档。

示例:

>>> from transformers import DPRConfig, DPRContextEncoder

>>> # Initializing a DPR facebook/dpr-ctx_encoder-single-nq-base style configuration
>>> configuration = DPRConfig()

>>> # Initializing a model (with random weights) from the facebook/dpr-ctx_encoder-single-nq-base style configuration
>>> model = DPRContextEncoder(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

DPRContextEncoderTokenizer

transformers.DPRContextEncoderTokenizer

< >

( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None clean_up_tokenization_spaces = True **kwargs )

构建一个DPRContextEncoder分词器。

DPRContextEncoderTokenizerBertTokenizer 相同,并执行端到端的分词:标点符号分割和词片处理。

有关参数的使用示例和文档,请参考超类 BertTokenizer

DPRContextEncoderTokenizerFast

transformers.DPRContextEncoderTokenizerFast

< >

( vocab_file = None tokenizer_file = None do_lower_case = True unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None **kwargs )

构建一个“快速”的DPRContextEncoder分词器(由HuggingFace的tokenizers库支持)。

DPRContextEncoderTokenizerFastBertTokenizerFast 相同,并且运行端到端的分词:标点符号分割和词片段。

请参考超类 BertTokenizerFast 以获取有关参数的使用示例和文档。

DPRQuestionEncoderTokenizer

transformers.DPRQuestionEncoderTokenizer

< >

( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None clean_up_tokenization_spaces = True **kwargs )

构建一个DPRQuestionEncoder分词器。

DPRQuestionEncoderTokenizerBertTokenizer 相同,并运行端到端的分词:标点符号分割和词片。

有关参数的使用示例和文档,请参考超类 BertTokenizer

DPRQuestionEncoderTokenizerFast

transformers.DPRQuestionEncoderTokenizerFast

< >

( vocab_file = None tokenizer_file = None do_lower_case = True unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None **kwargs )

构建一个“快速”的DPRQuestionEncoder分词器(由HuggingFace的tokenizers库支持)。

DPRQuestionEncoderTokenizerFastBertTokenizerFast 相同,并运行端到端的分词: 标点符号分割和词片。

请参考超类 BertTokenizerFast 以获取有关参数的使用示例和文档。

DPRReaderTokenizer

transformers.DPRReaderTokenizer

< >

( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None clean_up_tokenization_spaces = True **kwargs ) Dict[str, List[List[int]]]

参数

  • 问题 (strList[str]) — 要编码的问题。你可以为一个段落指定一个问题。在这种情况下,问题将会像 [questions] * n_passages 那样被复制。否则,你必须指定与 titlestexts 中数量相同的问题。
  • titles (str or List[str]) — 要编码的段落标题。这可以是一个字符串或一个字符串列表,如果有多个段落。
  • 文本 (strList[str]) — 要编码的段落文本。这可以是一个字符串或一个字符串列表,如果有多个段落。
  • padding (bool, str or PaddingStrategy, optional, 默认为 False) — 激活并控制填充。接受以下值:
    • True'longest': 填充到批次中最长的序列(如果只提供一个序列,则不填充)。
    • 'max_length': 填充到由参数 max_length 指定的最大长度,或者如果未提供该参数,则填充到模型可接受的最大输入长度。
    • False'do_not_pad' (默认): 不填充(即可以输出具有不同长度序列的批次)。
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • return_attention_mask (bool, optional) — Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是注意力掩码?

返回

Dict[str, List[List[int]]]

一个包含以下键的字典:

  • input_ids: 要输入模型的标记ID列表。
  • attention_mask: 指定模型应关注哪些标记的索引列表。

构建一个DPRReader分词器。

DPRReaderTokenizerBertTokenizer 几乎相同,并且执行端到端的分词:标点符号分割和词片段。不同之处在于它有三个输入字符串:问题、标题和文本,这些输入被组合起来输入到 DPRReader 模型中。

有关参数的使用示例和文档,请参考超类 BertTokenizer

返回一个包含输入字符串的标记ID和其他信息的字典,以便传递给.decode_best_spans。 它使用分词器和词汇表将问题和不同段落(标题和文本)的字符串转换为ID序列(整数)。 生成的input_ids是一个大小为(n_passages, sequence_length)的矩阵。

格式如下:

[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>

DPRReaderTokenizerFast

transformers.DPRReaderTokenizerFast

< >

( vocab_file = None tokenizer_file = None do_lower_case = True unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None **kwargs ) Dict[str, List[List[int]]]

参数

  • 问题 (strList[str]) — 要编码的问题。你可以为一个段落指定一个问题。在这种情况下,问题将会像 [questions] * n_passages 那样被复制。否则,你必须指定与 titlestexts 中数量相同的问题。
  • titles (strList[str]) — 要编码的段落标题。如果有多段文字,这可以是一个字符串或字符串列表。
  • 文本 (strList[str]) — 要编码的段落文本。这可以是一个字符串或一个字符串列表,如果有多个段落。
  • padding (bool, str or PaddingStrategy, optional, defaults to False) — 激活并控制填充。接受以下值:
    • True'longest': 填充到批次中最长的序列(如果只提供一个序列,则不进行填充)。
    • 'max_length': 填充到由参数 max_length 指定的最大长度,或者如果未提供该参数,则填充到模型可接受的最大输入长度。
    • False'do_not_pad' (默认): 不进行填充(即,可以输出具有不同长度序列的批次)。
  • truncation (bool, str or TruncationStrategy, optional, defaults to False) — Activates and controls truncation. Accepts the following values:
    • True or 'longest_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_first': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • 'only_second': Truncate to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    • False or 'do_not_truncate' (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size).
  • max_length (int, optional) — Controls the maximum length to use by one of the truncation/padding parameters.

    如果未设置或设置为None,则在需要截断/填充参数时,将使用预定义的模型最大长度。如果模型没有特定的最大输入长度(如XLNet),则截断/填充到最大长度的功能将被停用。

  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。
  • return_attention_mask (bool, optional) — Whether or not to return the attention mask. If not set, will return the attention mask according to the specific tokenizer’s default, defined by the return_outputs attribute.

    什么是注意力掩码?

返回

Dict[str, List[List[int]]]

一个包含以下键的字典:

  • input_ids: 要输入模型的标记ID列表。
  • attention_mask: 指定模型应关注哪些标记的索引列表。

构建一个“快速”的DPRReader分词器(由HuggingFace的tokenizers库支持)。

DPRReaderTokenizerFastBertTokenizerFast 几乎相同,并且运行端到端的分词: 标点符号分割和词片。不同之处在于它有三个输入字符串:问题、标题和文本, 这些输入被组合起来输入到 DPRReader 模型中。

请参考超类 BertTokenizerFast 以获取有关参数的使用示例和文档。

返回一个包含输入字符串的标记ID和其他信息的字典,以供.decode_best_spans使用。 它使用分词器和词汇表将问题和不同段落(标题和文本)的字符串转换为ID(整数)序列。 生成的input_ids是一个大小为(n_passages, sequence_length)的矩阵,格式如下:

[CLS] <问题标记ID> [SEP] <标题ID> [SEP] <文本ID>

DPR 特定输出

transformers.models.dpr.modeling_dpr.DPRContextEncoderOutput

< >

( pooler_output: FloatTensor hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • pooler_output (torch.FloatTensor of shape (batch_size, embeddings_size)) — DPR编码器输出的pooler_output对应于上下文表示。序列的第一个标记(分类标记)的最后一层隐藏状态通过线性层进一步处理。 此输出用于嵌入上下文,以便与问题嵌入进行最近邻查询。
  • 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 + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

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

    注意力权重在注意力softmax之后,用于计算自注意力头中的加权平均值。

用于DPRQuestionEncoder输出的类。

transformers.models.dpr.modeling_dpr.DPRQuestionEncoderOutput

< >

( pooler_output: FloatTensor hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • pooler_output (torch.FloatTensor of shape (batch_size, embeddings_size)) — DPR编码器输出的pooler_output对应于问题表示。序列的第一个标记(分类标记)的最后一层隐藏状态通过线性层进一步处理。 此输出用于嵌入问题,以便与上下文嵌入进行最近邻查询。
  • 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 + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

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

    注意力权重在注意力softmax之后,用于计算自注意力头中的加权平均值。

用于DPRQuestionEncoder输出的类。

transformers.DPRReaderOutput

< >

( start_logits: FloatTensor end_logits: FloatTensor = None relevance_logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • start_logits (torch.FloatTensor of shape (n_passages, sequence_length)) — 每个段落跨度的开始索引的Logits。
  • end_logits (torch.FloatTensor of shape (n_passages, sequence_length)) — 每个段落跨度结束索引的Logits。
  • relevance_logits (torch.FloatTensor of shape (n_passages, )) — DPRReader的QA分类器的输出,对应于每个段落回答问题的分数,与所有其他段落相比。
  • 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 + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

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

    注意力权重在注意力softmax之后,用于计算自注意力头中的加权平均值。

用于DPRQuestionEncoder输出的类。

Pytorch
Hide Pytorch content

DPRContextEncoder

transformers.DPRContextEncoder

< >

( config: DPRConfig )

参数

  • config (DPRConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸的DPRContextEncoder变压器输出池化输出作为上下文表示。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.dpr.modeling_dpr.DPRContextEncoderOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows:

    (a) 对于序列对(例如标题+文本的对):

返回

transformers.models.dpr.modeling_dpr.DPRContextEncoderOutputtuple(torch.FloatTensor)

一个 transformers.models.dpr.modeling_dpr.DPRContextEncoderOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(DPRConfig)和输入。

  • pooler_output (torch.FloatTensor 形状为 (batch_size, embeddings_size)) — DPR 编码器输出的 pooler_output 对应于上下文表示。序列的第一个标记(分类标记)的最后一层隐藏状态通过线性层进一步处理。 此输出用于嵌入上下文,以便与问题嵌入进行最近邻查询。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

DPRContextEncoder 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer

>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
>>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
>>> embeddings = model(input_ids).pooler_output

DPR问题编码器

transformers.DPRQuestionEncoder

< >

( config: DPRConfig )

参数

  • config (DPRConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸DPRQuestionEncoder变压器输出池化输出作为问题表示。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.dpr.modeling_dpr.DPRQuestionEncoderOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows:

    (a) 对于序列对(例如标题+文本的对):

返回

transformers.models.dpr.modeling_dpr.DPRQuestionEncoderOutputtuple(torch.FloatTensor)

一个 transformers.models.dpr.modeling_dpr.DPRQuestionEncoderOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(DPRConfig)和输入。

  • pooler_output (torch.FloatTensor 形状为 (batch_size, embeddings_size)) — DPR 编码器输出的 pooler_output 对应于问题表示。序列的第一个标记(分类标记)的最后一层隐藏状态通过线性层进一步处理。 此输出用于嵌入问题,以便与上下文嵌入进行最近邻查询。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

DPRQuestionEncoder 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer

>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
>>> model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
>>> embeddings = model(input_ids).pooler_output

DPRReader

transformers.DPRReader

< >

( config: DPRConfig )

参数

  • config (DPRConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸DPRReader变压器输出跨度预测。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.dpr.modeling_dpr.DPRReaderOutputtuple(torch.FloatTensor)

参数

  • input_ids (Tuple[torch.LongTensor] of shapes (n_passages, sequence_length)) — Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question and 2) the passages titles and 3) the passages texts To match pretraining, DPR input_ids sequence should be formatted with [CLS] and [SEP] with the format:

    [CLS] <问题标记ID> [SEP] <标题ID> [SEP] <文本ID>

    DPR 是一个具有绝对位置嵌入的模型,因此通常建议在输入的右侧而不是左侧进行填充。

    可以使用DPRReaderTokenizer获取索引。有关更多详细信息,请参阅此类的文档。

    什么是输入ID?

  • attention_mask (torch.FloatTensor of shape (n_passages, 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.

    什么是注意力掩码?

  • inputs_embeds (torch.FloatTensor 形状为 (n_passages, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.dpr.modeling_dpr.DPRReaderOutputtuple(torch.FloatTensor)

一个 transformers.models.dpr.modeling_dpr.DPRReaderOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(DPRConfig)和输入。

  • start_logits (torch.FloatTensor 形状为 (n_passages, sequence_length)) — 每个段落跨度的起始索引的 logits。

  • end_logits (torch.FloatTensor 形状为 (n_passages, sequence_length)) — 每个段落跨度的结束索引的 logits。

  • relevance_logits (torch.FloatTensor 形状为 (n_passages, )) — DPRReader 的 QA 分类器的输出,对应于每个段落回答问题的分数,与其他所有段落相比。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

DPRReader 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import DPRReader, DPRReaderTokenizer

>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
>>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
>>> encoded_inputs = tokenizer(
...     questions=["What is love ?"],
...     titles=["Haddaway"],
...     texts=["'What Is Love' is a song recorded by the artist Haddaway"],
...     return_tensors="pt",
... )
>>> outputs = model(**encoded_inputs)
>>> start_logits = outputs.start_logits
>>> end_logits = outputs.end_logits
>>> relevance_logits = outputs.relevance_logits
TensorFlow
Hide TensorFlow content

TFDPRContextEncoder

transformers.TFDPRContextEncoder

< >

( config: DPRConfig *args **kwargs )

参数

  • config (DPRConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸的DPRContextEncoder变压器输出池化输出作为上下文表示。

该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是 Tensorflow keras.Model 的子类。将其作为常规的 TF 2.0 Keras 模型使用,并参考 TF 2.0 文档以获取与一般用法和行为相关的所有信息。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None training: bool = False ) transformers.models.dpr.modeling_tf_dpr.TFDPRContextEncoderOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows:

    (a) 对于序列对(例如标题+文本的对):

返回

transformers.models.dpr.modeling_tf_dpr.TFDPRContextEncoderOutputtuple(tf.Tensor)

一个 transformers.models.dpr.modeling_tf_dpr.TFDPRContextEncoderOutput 或一个 tf.Tensor 的元组(如果 传递了 return_dict=False 或当 config.return_dict=False 时),包含根据配置(DPRConfig)和输入的各种元素。

  • pooler_output (tf.Tensor 形状为 (batch_size, embeddings_size)) — DPR 编码器输出的 pooler_output 对应于上下文表示。序列的第一个标记(分类标记)的最后一层隐藏状态通过线性层进一步处理。 此输出用于嵌入上下文,以便与问题嵌入进行最近邻查询。

  • hidden_states (tuple(tf.Tensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(tf.Tensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — tf.Tensor 的元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

TFDPRContextEncoder 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import TFDPRContextEncoder, DPRContextEncoderTokenizer

>>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
>>> model = TFDPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", from_pt=True)
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
>>> embeddings = model(input_ids).pooler_output

TFDPRQuestionEncoder

transformers.TFDPRQuestionEncoder

< >

( config: DPRConfig *args **kwargs )

参数

  • config (DPRConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸DPRQuestionEncoder变压器输出池化输出作为问题表示。

该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是 Tensorflow keras.Model 的子类。将其作为常规的 TF 2.0 Keras 模型使用,并参考 TF 2.0 文档以获取与一般用法和行为相关的所有信息。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None token_type_ids: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None training: bool = False ) transformers.models.dpr.modeling_tf_dpr.TFDPRQuestionEncoderOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be formatted with [CLS] and [SEP] tokens as follows:

    (a) 对于序列对(例如标题+文本的对):

返回

transformers.models.dpr.modeling_tf_dpr.TFDPRQuestionEncoderOutputtuple(tf.Tensor)

一个 transformers.models.dpr.modeling_tf_dpr.TFDPRQuestionEncoderOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (DPRConfig) 和输入。

  • pooler_output (tf.Tensor 形状为 (batch_size, embeddings_size)) — DPR 编码器输出的 pooler_output 对应于问题表示。序列的第一个标记(分类标记)的最后一层隐藏状态通过线性层进一步处理。 此输出用于嵌入问题,以便与上下文嵌入进行最近邻查询。

  • hidden_states (tuple(tf.Tensor), 可选, 当 output_hidden_states=True 被传递或当 config.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(tf.Tensor), 可选, 当 output_attentions=True 被传递或当 config.output_attentions=True 时返回) — tf.Tensor 的元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

TFDPRQuestionEncoder 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import TFDPRQuestionEncoder, DPRQuestionEncoderTokenizer

>>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
>>> model = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base", from_pt=True)
>>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
>>> embeddings = model(input_ids).pooler_output

TFDPRReader

transformers.TFDPRReader

< >

( config: DPRConfig *args **kwargs )

参数

  • config (DPRConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸DPRReader变压器输出跨度预测。

该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是 Tensorflow keras.Model 的子类。将其作为常规的 TF 2.0 Keras 模型使用,并参考 TF 2.0 文档以获取与一般用法和行为相关的所有信息。

TensorFlow 模型和层在 transformers 中接受两种格式作为输入:

  • 将所有输入作为关键字参数(如PyTorch模型),或
  • 将所有输入作为列表、元组或字典放在第一个位置参数中。

支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit() 这样的方法时,事情应该“正常工作”——只需以 model.fit() 支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:

  • 仅包含input_ids的单个张量,没有其他内容:model(input_ids)
  • 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序: model([input_ids, attention_mask])model([input_ids, attention_mask, token_type_ids])
  • 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量: model({"input_ids": input_ids, "token_type_ids": token_type_ids})

请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!

调用

< >

( input_ids: TFModelInputType | None = None attention_mask: tf.Tensor | None = None inputs_embeds: tf.Tensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None training: bool = False ) transformers.models.dpr.modeling_tf_dpr.TFDPRReaderOutputtuple(tf.Tensor)

参数

  • input_ids (Numpy array or tf.Tensor of shapes (n_passages, sequence_length)) — Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question and 2) the passages titles and 3) the passages texts To match pretraining, DPR input_ids sequence should be formatted with [CLS] and [SEP] with the format:

    [CLS] <问题标记ID> [SEP] <标题ID> [SEP] <文本ID>

    DPR 是一个具有绝对位置嵌入的模型,因此通常建议在输入的右侧而不是左侧进行填充。

    可以使用DPRReaderTokenizer获取索引。有关更多详细信息,请参阅此类的文档。

  • attention_mask (Numpy array or tf.Tensor of shape (n_passages, 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.

    什么是注意力掩码?

  • inputs_embeds (Numpy arraytf.Tensor 形状为 (n_passages, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True.
  • 训练 (bool, 可选, 默认为 False) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。

返回

transformers.models.dpr.modeling_tf_dpr.TFDPRReaderOutputtuple(tf.Tensor)

一个 transformers.models.dpr.modeling_tf_dpr.TFDPRReaderOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (DPRConfig) 和输入。

  • start_logits (tf.Tensor 形状为 (n_passages, sequence_length)) — 每个段落跨度的开始索引的 logits。

  • end_logits (tf.Tensor 形状为 (n_passages, sequence_length)) — 每个段落跨度的结束索引的 logits。

  • relevance_logits (tf.Tensor 形状为 (n_passages, )) — DPRReader 的 QA 分类器的输出,对应于每个段落回答问题的分数,与所有其他段落相比。

  • hidden_states (tuple(tf.Tensor), 可选, 当 output_hidden_states=True 被传递或当 config.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当 output_attentions=True 被传递或当 config.output_attentions=True 时返回) — torch.FloatTensor 的元组(每层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

TFDPRReader 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import TFDPRReader, DPRReaderTokenizer

>>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
>>> model = TFDPRReader.from_pretrained("facebook/dpr-reader-single-nq-base", from_pt=True)
>>> encoded_inputs = tokenizer(
...     questions=["What is love ?"],
...     titles=["Haddaway"],
...     texts=["'What Is Love' is a song recorded by the artist Haddaway"],
...     return_tensors="tf",
... )
>>> outputs = model(encoded_inputs)
>>> start_logits = outputs.start_logits
>>> end_logits = outputs.end_logits
>>> relevance_logits = outputs.relevance_logits
< > Update on GitHub