Transformers 文档

XLNet

XLNet

Models Spaces

概述

XLNet模型由Zhilin Yang、Zihang Dai、Yiming Yang、Jaime Carbonell、Ruslan Salakhutdinov和Quoc V. Le在XLNet: Generalized Autoregressive Pretraining for Language Understanding中提出。XLNet是Transformer-XL模型的扩展,通过自回归方法预训练,通过最大化输入序列分解顺序的所有排列的期望似然来学习双向上下文。

论文的摘要如下:

凭借建模双向上下文的能力,基于去噪自编码的预训练方法(如BERT)在性能上优于基于自回归语言建模的预训练方法。然而,BERT依赖于通过掩码破坏输入,忽略了掩码位置之间的依赖关系,并存在预训练与微调之间的差异。鉴于这些优缺点,我们提出了XLNet,一种广义的自回归预训练方法,它(1)通过最大化所有因子分解顺序排列的期望似然来学习双向上下文,(2)由于其自回归公式,克服了BERT的局限性。此外,XLNet将来自Transformer-XL(最先进的自回归模型)的思想整合到预训练中。实验表明,在可比的实验设置下,XLNet在20个任务上优于BERT,通常优势显著,包括问答、自然语言推理、情感分析和文档排序。

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

使用提示

  • 在训练和测试时,可以使用perm_mask输入来控制特定的注意力模式。
  • 由于在各种分解顺序上训练完全自回归模型的难度,XLNet 仅使用输出标记的子集作为目标进行预训练,这些目标通过 target_mapping 输入选择。
  • 要使用XLNet进行顺序解码(即不在完全双向设置中),请使用perm_masktarget_mapping输入来控制注意力范围和输出(参见examples/pytorch/text-generation/run_generation.py中的示例)
  • XLNet 是少数没有序列长度限制的模型之一。
  • XLNet 不是一个传统的自回归模型,而是使用了一种基于此的训练策略。它对句子中的标记进行排列,然后允许模型使用最后 n 个标记来预测第 n+1 个标记。由于这一切都是通过掩码完成的,句子实际上是以正确的顺序输入模型的,但 XLNet 不是为 n+1 掩码前 n 个标记,而是使用一个掩码来隐藏 1,…,序列长度 的某个给定排列中的先前标记。
  • XLNet 也使用与 Transformer-XL 相同的递归机制来构建长期依赖关系。

资源

XLNetConfig

transformers.XLNetConfig

< >

( vocab_size = 32000 d_model = 1024 n_layer = 24 n_head = 16 d_inner = 4096 ff_activation = 'gelu' untie_r = True attn_type = 'bi' initializer_range = 0.02 layer_norm_eps = 1e-12 dropout = 0.1 mem_len = 512 reuse_len = None use_mems_eval = True use_mems_train = False bi_data = False clamp_len = -1 same_length = False summary_type = 'last' summary_use_proj = True summary_activation = 'tanh' summary_last_dropout = 0.1 start_n_top = 5 end_n_top = 5 pad_token_id = 5 bos_token_id = 1 eos_token_id = 2 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 32000) — XLNet 模型的词汇表大小。定义了调用 XLNetModelTFXLNetModel 时传递的 inputs_ids 可以表示的不同标记的数量。
  • d_model (int, optional, 默认为 1024) — 编码器层和池化层的维度。
  • n_layer (int, optional, 默认为 24) — Transformer 编码器中的隐藏层数。
  • n_head (int, optional, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数。
  • d_inner (int, 可选, 默认为 4096) — Transformer编码器中“中间”(通常称为前馈)层的维度。
  • ff_activation (strCallable, 可选, 默认为 "gelu") — 非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu", "relu", "silu""gelu_new".
  • untie_r (bool, optional, defaults to True) — 是否解除相对位置偏置
  • attn_type (str, optional, defaults to "bi") — 模型使用的注意力类型。对于XLNet设置为"bi",对于Transformer-XL设置为"uni".
  • initializer_range (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • dropout (float, optional, defaults to 0.1) — 嵌入层、编码器和池化器中所有全连接层的dropout概率。
  • mem_len (intNone, 可选) — 要缓存的令牌数量。在前一次前向传递中已经预计算过的键/值对将不会被重新计算。有关更多信息,请参阅 快速入门.
  • reuse_len (int, optional) — 当前批次中要缓存并在未来重用的令牌数量。
  • bi_data (bool, 可选, 默认为 False) — 是否使用双向输入管道。通常在预训练期间设置为 True,在微调期间设置为 False
  • clamp_len (int, 可选, 默认为 -1) — 将所有大于 clamp_len 的相对距离进行限制。将此属性设置为 -1 表示不进行限制。
  • same_length (bool, optional, defaults to False) — 是否对每个标记使用相同的注意力长度。
  • summary_type (str, optional, defaults to “last”) — Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.

    必须是以下选项之一:

    • "last": Take the last token hidden state (like XLNet).
    • "first": Take the first token hidden state (like BERT).
    • "mean": Take the mean of all tokens hidden states.
    • "cls_index": Supply a Tensor of classification token position (like GPT/GPT-2).
    • "attn": Not implemented now, use multi-head attention.
  • summary_use_proj (bool, optional, defaults to True) — Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.

    是否在向量提取后添加投影。

  • summary_activation (str, optional) — Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.

    传递 "tanh" 作为输出层的 tanh 激活函数,任何其他值将导致没有激活函数。

  • summary_proj_to_labels (boo, optional, defaults to True) — Used in the sequence classification and multiple choice models.

    投影输出是否应该具有config.num_labelsconfig.hidden_size类别。

  • summary_last_dropout (float, optional, defaults to 0.1) — Used in the sequence classification and multiple choice models.

    在投影和激活后使用的丢弃比率。

  • start_n_top (int, optional, 默认为 5) — 用于 SQuAD 评估脚本。
  • end_n_top (int, 可选, 默认为 5) — 用于SQuAD评估脚本。
  • use_mems_eval (bool, 可选, 默认为 True) — 模型是否应在评估模式下使用循环记忆机制。
  • use_mems_train (bool, optional, defaults to False) — Whether or not the model should make use of the recurrent memory mechanism in train mode.

    对于预训练,建议将use_mems_train设置为True。对于微调,建议将use_mems_train设置为False,如这里所讨论的。如果use_mems_train设置为True,必须确保训练批次被正确预处理,例如 batch_1 = [[This line is], [This is the]]batch_2 = [[ the first line], [ second line]],并且所有批次的大小相同。

这是用于存储XLNetModelTFXLNetModel配置的配置类。它用于根据指定的参数实例化XLNet模型,定义模型架构。使用默认值实例化配置将生成与xlnet/xlnet-large-cased架构相似的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

示例:

>>> from transformers import XLNetConfig, XLNetModel

>>> # Initializing a XLNet configuration
>>> configuration = XLNetConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = XLNetModel(configuration)

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

XLNetTokenizer

transformers.XLNetTokenizer

< >

( vocab_file do_lower_case = False remove_space = True keep_accents = False bos_token = '' eos_token = '' unk_token = '' sep_token = '' pad_token = '' cls_token = '' mask_token = '' additional_special_tokens = ['', ''] sp_model_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。
  • do_lower_case (bool, optional, defaults to False) — 是否在分词时将输入转换为小写。
  • remove_space (bool, 可选, 默认为 True) — 是否在分词时去除文本中的空格(去除字符串前后的多余空格)。
  • keep_accents (bool, optional, defaults to False) — 是否在分词时保留重音符号。
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • unk_token (str, 可选, 默认为 "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • sep_token (str, optional, defaults to "") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • mask_token (str, 可选, 默认为 "") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • additional_special_tokens (List[str], 可选, 默认为 ['', '']) — 分词器使用的额外特殊标记。
  • sp_model_kwargs (dict, optional) — Will be passed to the SentencePieceProcessor.__init__() method. The Python wrapper for SentencePiece can be used, among other things, to set:
    • enable_sampling: 启用子词正则化。

    • nbest_size: 用于unigram的采样参数。对于BPE-Dropout无效。

      • nbest_size = {0,1}: No sampling is performed.
      • nbest_size > 1: samples from the nbest_size results.
      • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
    • alpha: 用于单字采样的平滑参数,以及BPE-dropout的合并操作丢弃概率。

  • sp_model (SentencePieceProcessor) — 用于每次转换(字符串、标记和ID)的SentencePiece处理器。

构建一个XLNet分词器。基于SentencePiece

此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表。
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。一个XLNet序列具有以下格式:

  • 单一序列:X
  • 序列对:A B

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 令牌列表是否已经用模型的特殊令牌格式化。

返回

List[int]

一个整数列表,范围在[0, 1]:1表示特殊标记,0表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model方法添加特殊标记时,会调用此方法。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

根据给定序列的token type IDs列表。

从传递给序列对分类任务的两个序列中创建一个掩码。一个XLNet

序列对掩码具有以下格式:

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

如果 token_ids_1None,此方法仅返回掩码的第一部分(0s)。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

XLNetTokenizerFast

transformers.XLNetTokenizerFast

< >

( vocab_file = None tokenizer_file = None do_lower_case = False remove_space = True keep_accents = False bos_token = '' eos_token = '' unk_token = '' sep_token = '' pad_token = '' cls_token = '' mask_token = '' additional_special_tokens = ['', ''] **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。
  • do_lower_case (bool, optional, defaults to True) — 是否在分词时将输入转换为小写。
  • remove_space (bool, 可选, 默认为 True) — 是否在分词时去除文本中的空格(去除字符串前后的多余空格)。
  • keep_accents (bool, optional, defaults to False) — 是否在分词时保留重音符号。
  • bos_token (str, optional, defaults to "<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

    在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是cls_token

  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • unk_token (str, 可选, 默认为 "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • sep_token (str, 可选, 默认为 "") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • cls_token (str, 可选, 默认为 "") — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • mask_token (str, 可选, 默认为 "") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • additional_special_tokens (List[str], 可选, 默认为 ["", ""]) — 分词器使用的额外特殊标记.
  • sp_model (SentencePieceProcessor) — 用于每次转换(字符串、标记和ID)的SentencePiece处理器。

构建一个“快速”的XLNet分词器(基于HuggingFace的tokenizers库)。基于 Unigram

这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表。
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。一个XLNet序列具有以下格式:

  • 单一序列:X
  • 序列对:A B

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

根据给定序列的token type IDs列表。

从传递给序列对分类任务的两个序列中创建一个掩码。一个XLNet

序列对掩码具有以下格式:

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

如果 token_ids_1None,此方法仅返回掩码的第一部分(0s)。

XLNet 特定输出

transformers.models.xlnet.modeling_xlnet.XLNetModelOutput

< >

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

参数

  • last_hidden_state (torch.FloatTensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,那么 num_predict 对应于 sequence_length

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

XLNetModel的输出类型。

transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None mems: typing.Optional[typing.List[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • loss (torch.FloatTensor of shape (1,), optional, 当提供 labels 时返回) — 语言建模损失(用于下一个标记的预测)。
  • logits (torch.FloatTensor of shape (batch_size, num_predict, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,那么 num_predict 对应于 sequence_length

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

XLNetLMHeadModel的输出类型。

transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None mems: typing.Optional[typing.List[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • loss (torch.FloatTensor of shape (1,), optional, 当提供 label 时返回) — 分类(或回归,如果 config.num_labels==1)损失。
  • logits (torch.FloatTensor of shape (batch_size, config.num_labels)) — 分类(如果config.num_labels==1则为回归)得分(在SoftMax之前)。
  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

XLNetForSequenceClassification的输出类型。

transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None mems: typing.Optional[typing.List[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • loss (torch.FloatTensor of shape (1,), optional, 当提供 labels 时返回) — 分类损失.
  • logits (torch.FloatTensor of shape (batch_size, num_choices)) — num_choices is the second dimension of the input tensors. (see input_ids above).

    分类分数(在SoftMax之前)。

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

XLNetForMultipleChoice的输出类型。

transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None mems: typing.Optional[typing.List[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — 分类损失.
  • logits (torch.FloatTensor of shape (batch_size, sequence_length, config.num_labels)) — 分类分数(在SoftMax之前)。
  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

输出类型为 XLNetForTokenClassificationOutput

transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutput

< >

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

参数

  • loss (torch.FloatTensor of shape (1,), optional, 当提供 labels 时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。
  • start_logits (torch.FloatTensor of shape (batch_size, sequence_length,)) — 跨度起始分数(在SoftMax之前)。
  • end_logits (torch.FloatTensor of shape (batch_size, sequence_length,)) — 跨度结束分数(在SoftMax之前)。
  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

XLNetForQuestionAnsweringSimple 的输出类型。

transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutput

< >

( loss: typing.Optional[torch.FloatTensor] = None start_top_log_probs: typing.Optional[torch.FloatTensor] = None start_top_index: typing.Optional[torch.LongTensor] = None end_top_log_probs: typing.Optional[torch.FloatTensor] = None end_top_index: typing.Optional[torch.LongTensor] = None cls_logits: typing.Optional[torch.FloatTensor] = None mems: typing.Optional[typing.List[torch.FloatTensor]] = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )

参数

  • loss (torch.FloatTensor of shape (1,), optional, 如果同时提供了 start_positionsend_positions 则返回) — 分类损失,作为起始标记、结束标记(以及如果提供了 is_impossible)分类损失的总和。
  • start_top_log_probs (torch.FloatTensor of shape (batch_size, config.start_n_top), optional, returned if start_positions or end_positions is not provided) — 用于前config.start_n_top个起始标记可能性的对数概率(beam-search)。
  • start_top_index (torch.LongTensor of shape (batch_size, config.start_n_top), optional, 如果未提供 start_positionsend_positions 则返回) — 表示前 config.start_n_top 个开始标记可能性的索引(beam-search)。
  • end_top_log_probs (torch.FloatTensor 形状为 (batch_size, config.start_n_top * config.end_n_top), 可选, 如果未提供 start_positionsend_positions 时返回) — 前 config.start_n_top * config.end_n_top 个结束标记可能性的对数概率 (beam-search).
  • end_top_index (torch.LongTensor of shape (batch_size, config.start_n_top * config.end_n_top), 可选, 如果未提供 start_positionsend_positions 时返回) — 表示前 config.start_n_top * config.end_n_top 个结束标记可能性的索引(beam-search)。
  • cls_logits (torch.FloatTensor of shape (batch_size,), optional, 如果未提供 start_positionsend_positions 则返回) — 答案的 is_impossible 标签的对数概率.
  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • 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之后,用于计算自注意力头中的加权平均值。

XLNetForQuestionAnswering的输出类型。

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput

< >

( last_hidden_state: tf.Tensor = None mems: List[tf.Tensor] | None = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None )

参数

  • last_hidden_state (tf.Tensor of shape (batch_size, num_predict, hidden_size)) — Sequence of hidden-states at the last layer of the model.

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,那么 num_predict 对应于 sequence_length

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

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

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

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

TFXLNetModel的输出类型。

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput

< >

( loss: tf.Tensor | None = None logits: tf.Tensor = None mems: List[tf.Tensor] | None = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None )

参数

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 labels 时返回) — 语言建模损失(用于下一个标记的预测)。
  • logits (tf.Tensor of shape (batch_size, num_predict, config.vocab_size)) — Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,那么 num_predict 对应于 sequence_length

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

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

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

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

TFXLNetLMHeadModel 的输出类型。

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput

< >

( loss: tf.Tensor | None = None logits: tf.Tensor = None mems: List[tf.Tensor] | None = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None )

参数

  • loss (tf.Tensor of shape (1,), optional, 当提供 label 时返回) — 分类(或回归,如果 config.num_labels==1)损失.
  • logits (tf.Tensor of shape (batch_size, config.num_labels)) — 分类(如果 config.num_labels==1 则为回归)分数(在 SoftMax 之前)。
  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

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

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

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

TFXLNetForSequenceClassification的输出类型。

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutput

< >

( loss: tf.Tensor | None = None logits: tf.Tensor = None mems: List[tf.Tensor] | None = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None )

参数

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 labels 时返回) — 分类损失.
  • logits (tf.Tensor of shape (batch_size, num_choices)) — num_choices is the second dimension of the input tensors. (see input_ids above).

    分类分数(在SoftMax之前)。

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

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

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

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

TFXLNetForMultipleChoice的输出类型。

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput

< >

( loss: tf.Tensor | None = None logits: tf.Tensor = None mems: List[tf.Tensor] | None = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None )

参数

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 labels 时返回) — 分类损失.
  • logits (tf.Tensor of shape (batch_size, sequence_length, config.num_labels)) — 分类分数(在SoftMax之前)。
  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

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

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

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

TFXLNetForTokenClassificationOutput 的输出类型。

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput

< >

( loss: tf.Tensor | None = None start_logits: tf.Tensor = None end_logits: tf.Tensor = None mems: List[tf.Tensor] | None = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None )

参数

  • loss (tf.Tensor of shape (1,), optional, returned when labels is provided) — 总跨度提取损失是起始和结束位置的交叉熵之和。
  • start_logits (tf.Tensor of shape (batch_size, sequence_length,)) — 跨度起始分数(在SoftMax之前)。
  • end_logits (tf.Tensor of shape (batch_size, sequence_length,)) — 跨度结束分数(在SoftMax之前)。
  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预先计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。
  • hidden_states (tuple(tf.Tensor), optional, returned when output_hidden_states=True is passed or when config.output_hidden_states=True) — Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

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

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

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

TFXLNetForQuestionAnsweringSimple 的输出类型。

Pytorch
Hide Pytorch content

XLNetModel

transformers.XLNetModel

< >

( config )

参数

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

裸的XLNet模型转换器输出原始隐藏状态,没有任何特定的头部。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.xlnet.modeling_xlnet.XLNetModelOutputtuple(torch.FloatTensor)

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

  • last_hidden_state (torch.FloatTensor 形状为 (batch_size, num_predict, hidden_size)) — 模型最后一层的隐藏状态序列。

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,则 num_predict 对应于 sequence_length

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经将其过去状态提供给此模型的 token ids 不应作为 input_ids 传递,因为它们已经被计算过。

  • 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 之后,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, XLNetModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetModel.from_pretrained("xlnet/xlnet-base-cased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state

XLNetLMHeadModel

transformers.XLNetLMHeadModel

< >

( config )

参数

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

XLNet 模型,顶部带有语言建模头(线性层,权重与输入嵌入绑定)。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor 形状为 (batch_size, num_predict, sequence_length), 可选) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size, num_predict), optional) — Labels for masked language modeling. num_predict corresponds to target_mapping.shape[1]. If target_mapping is None, then num_predict corresponds to sequence_length.

    标签应与需要预测的掩码输入词相对应,并依赖于target_mapping。请注意,为了执行标准的自回归语言建模,必须在input_ids中添加一个标记(请参阅下面的prepare_inputs_for_generation函数和示例)

    索引在[-100, 0, ..., config.vocab_size]中选择。所有设置为-100的标签将被忽略,损失仅针对[0, ..., config.vocab_size]中的标签计算。

返回

transformers.models.xlnet.modeling_xlnet.XLNetLMHeadModelOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 labels 时返回) 语言建模损失(用于下一个标记的预测)。

  • logits (torch.FloatTensor 形状为 (batch_size, num_predict, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,则 num_predict 对应于 sequence_length

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可以用于(参见 mems 输入)加速顺序解码。已经计算过的标记 ID 不应作为 input_ids 传递,因为它们已经被计算过了。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, XLNetLMHeadModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
>>> model = XLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")

>>> # We show how to setup inputs to predict a next token using a bi-directional context.
>>> input_ids = torch.tensor(
...     tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
... ).unsqueeze(
...     0
... )  # We will predict the masked token
>>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
>>> perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token
>>> target_mapping = torch.zeros(
...     (1, 1, input_ids.shape[1]), dtype=torch.float
... )  # Shape [1, 1, seq_length] => let's predict one token
>>> target_mapping[
...     0, 0, -1
... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

>>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
>>> next_token_logits = outputs[
...     0
... ]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]

>>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.
>>> input_ids = torch.tensor(
...     tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
... ).unsqueeze(
...     0
... )  # We will predict the masked token
>>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0)
>>> assert labels.shape[0] == 1, "only one word will be predicted"
>>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
>>> perm_mask[
...     :, :, -1
... ] = 1.0  # Previous tokens don't see last token as is done in standard auto-regressive lm training
>>> target_mapping = torch.zeros(
...     (1, 1, input_ids.shape[1]), dtype=torch.float
... )  # Shape [1, 1, seq_length] => let's predict one token
>>> target_mapping[
...     0, 0, -1
... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

>>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)
>>> loss = outputs.loss
>>> next_token_logits = (
...     outputs.logits
... )  # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]

XLNetForSequenceClassification

transformers.XLNetForSequenceClassification

< >

( config )

参数

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

XLNet 模型,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 GLUE 任务。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.models.xlnet.modeling_xlnet.XLNetForSequenceClassificationOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 label 时返回) — 分类(或回归,如果 config.num_labels==1)损失。

  • logits (torch.FloatTensor 形状为 (batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递。

  • 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 之后,用于计算自注意力头中的加权平均值。

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

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

单标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, XLNetForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetForSequenceClassification.from_pretrained("xlnet/xlnet-base-cased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_id = logits.argmax().item()

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = XLNetForSequenceClassification.from_pretrained("xlnet/xlnet-base-cased", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss

多标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, XLNetForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetForSequenceClassification.from_pretrained("xlnet/xlnet-base-cased", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = XLNetForSequenceClassification.from_pretrained(
...     "xlnet/xlnet-base-cased", num_labels=num_labels, problem_type="multi_label_classification"
... )

>>> labels = torch.sum(
...     torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).loss

XLNetForMultipleChoice

transformers.XLNetForMultipleChoice

< >

( config )

参数

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

XLNet 模型,顶部带有多项选择分类头(在池化输出之上的线性层和 softmax),例如用于 RACE/SWAG 任务。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

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

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, num_choices, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, num_choices, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算多项选择分类损失的标签。索引应在 [0, ..., num_choices-1] 范围内,其中 num_choices 是输入张量第二维的大小。(参见上面的 input_ids

返回

transformers.models.xlnet.modeling_xlnet.XLNetForMultipleChoiceOutputtuple(torch.FloatTensor)

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

  • loss(形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回)— 分类损失。

  • logits(形状为 (batch_size, num_choices)torch.FloatTensor)— num_choices 是输入张量的第二维度。(见上面的 input_ids)。

    分类分数(在 SoftMax 之前)。

  • mems(长度为 config.n_layersList[torch.FloatTensor])— 包含预计算的隐藏状态。可用于(见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。

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

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

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, XLNetForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetForMultipleChoice.from_pretrained("xlnet/xlnet-base-cased")

>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."
>>> labels = torch.tensor(0).unsqueeze(0)  # choice0 is correct (according to Wikipedia ;)), batch size 1

>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True)
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels)  # batch size is 1

>>> # the linear classifier still needs to be trained
>>> loss = outputs.loss
>>> logits = outputs.logits

XLNetForTokenClassification

transformers.XLNetForTokenClassification

< >

( config )

参数

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

XLNet 模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算多项选择分类损失的标签。索引应在 [0, ..., num_choices] 范围内, 其中 num_choices 是输入张量第二维的大小。(参见上面的 input_ids

返回

transformers.models.xlnet.modeling_xlnet.XLNetForTokenClassificationOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 分类损失。

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.num_labels)) — 分类分数(在 SoftMax 之前)。

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。

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

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

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, XLNetForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetForTokenClassification.from_pretrained("xlnet/xlnet-base-cased")

>>> inputs = tokenizer(
...     "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_token_class_ids = logits.argmax(-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]

>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss

XLNetForQuestionAnsweringSimple

transformers.XLNetForQuestionAnsweringSimple

< >

( config )

参数

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

XLNet 模型,顶部带有用于抽取式问答任务(如 SQuAD)的跨度分类头(在隐藏状态输出之上的线性层,用于计算 span start logitsspan end logits)。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会被考虑用于计算损失。
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。

返回

transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringSimpleOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。

  • start_logits (torch.FloatTensor 形状为 (batch_size, sequence_length,)) — 跨度起始分数(在 SoftMax 之前)。

  • end_logits (torch.FloatTensor 形状为 (batch_size, sequence_length,)) — 跨度结束分数(在 SoftMax 之前)。

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, XLNetForQuestionAnsweringSimple
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetForQuestionAnsweringSimple.from_pretrained("xlnet/xlnet-base-cased")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]

>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss

XLNetForQuestionAnswering

transformers.XLNetForQuestionAnswering

< >

( config )

参数

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

XLNet 模型,顶部带有用于抽取式问答任务(如 SQuAD)的跨度分类头(在隐藏状态输出之上的线性层用于计算 span start logitsspan end logits)。

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

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None mems: typing.Optional[torch.Tensor] = None perm_mask: typing.Optional[torch.Tensor] = None target_mapping: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None input_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None is_impossible: typing.Optional[torch.Tensor] = None cls_index: typing.Optional[torch.Tensor] = None p_mask: typing.Optional[torch.Tensor] = None use_mems: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None **kwargs ) transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会被考虑用于计算损失。
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
  • is_impossible (torch.LongTensor of shape (batch_size,), optional) — 标签指示问题是否有答案或无答案(SQuAD 2.0)
  • cls_index (torch.LongTensor of shape (batch_size,), optional) — 用于计算答案合理性的分类标记的位置(索引)标签。
  • p_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 可选的标记掩码,这些标记不能出现在答案中(例如 [CLS], [PAD], …)。1.0 表示标记应被掩码。0.0 表示标记未被掩码。

返回

transformers.models.xlnet.modeling_xlnet.XLNetForQuestionAnsweringOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,如果提供了 start_positionsend_positions 则返回) — 分类损失,作为起始标记、结束标记(以及如果提供了 is_impossible)分类损失的总和。

  • start_top_log_probs (torch.FloatTensor 形状为 (batch_size, config.start_n_top)可选,如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top 个起始标记可能性的对数概率(beam-search)。

  • start_top_index (torch.LongTensor 形状为 (batch_size, config.start_n_top)可选,如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top 个起始标记可能性的索引(beam-search)。

  • end_top_log_probs (torch.FloatTensor 形状为 (batch_size, config.start_n_top * config.end_n_top)可选,如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top * config.end_n_top 个结束标记可能性的对数概率(beam-search)。

  • end_top_index (torch.LongTensor 形状为 (batch_size, config.start_n_top * config.end_n_top)可选,如果未提供 start_positionsend_positions 则返回) — 前 config.start_n_top * config.end_n_top 个结束标记可能性的索引(beam-search)。

  • cls_logits (torch.FloatTensor 形状为 (batch_size,)可选,如果未提供 start_positionsend_positions 则返回) — 答案的 is_impossible 标签的对数概率。

  • mems (List[torch.FloatTensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(参见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, XLNetForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = XLNetForQuestionAnswering.from_pretrained("xlnet/xlnet-base-cased")

>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
...     0
... )  # Batch size 1
>>> start_positions = torch.tensor([1])
>>> end_positions = torch.tensor([3])
>>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)

>>> loss = outputs.loss
TensorFlow
Hide TensorFlow content

TFXLNetModel

transformers.TFXLNetModel

< >

( config *inputs **kwargs )

参数

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

裸的XLNet模型转换器输出原始隐藏状态,没有任何特定的头部。

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

该模型也是一个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: np.ndarray | tf.Tensor | None = None mems: np.ndarray | tf.Tensor | None = None perm_mask: np.ndarray | tf.Tensor | None = None target_mapping: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None input_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None use_mems: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: bool = False ) transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutputtuple(tf.Tensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutputtuple(tf.Tensor)

一个 transformers.models.xlnet.modeling_tf_xlnet.TFXLNetModelOutput 或一个由 tf.Tensor 组成的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置 (XLNetConfig) 和输入而定的各种元素。

  • last_hidden_state (tf.Tensor 形状为 (batch_size, num_predict, hidden_size)) — 模型最后一层的隐藏状态序列。

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,则 num_predict 对应于 sequence_length

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可以用于(见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过了。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, TFXLNetModel
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = TFXLNetModel.from_pretrained("xlnet/xlnet-base-cased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)

>>> last_hidden_states = outputs.last_hidden_state

TFXLNetLMHeadModel

transformers.TFXLNetLMHeadModel

< >

( config *inputs **kwargs )

参数

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

XLNet 模型,顶部带有语言建模头(线性层,权重与输入嵌入绑定)。

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

该模型也是一个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: np.ndarray | tf.Tensor | None = None mems: np.ndarray | tf.Tensor | None = None perm_mask: np.ndarray | tf.Tensor | None = None target_mapping: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None input_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None use_mems: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: bool = False ) transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutputtuple(tf.Tensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — 用于计算交叉熵分类损失的标签。索引应在 [0, ..., config.vocab_size - 1] 范围内。

返回

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutputtuple(tf.Tensor)

一个 transformers.models.xlnet.modeling_tf_xlnet.TFXLNetLMHeadModelOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,取决于 配置 (XLNetConfig) 和输入。

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 labels 时返回) 语言建模损失(用于下一个标记的预测)。

  • logits (tf.Tensor 形状为 (batch_size, num_predict, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。

    num_predict 对应于 target_mapping.shape[1]。如果 target_mappingNone,则 num_predict 对应于 sequence_length

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可以用于(见 mems 输入)加速顺序解码。已经 计算过的标记 ID 不应作为 input_ids 传递,因为它们已经被计算过了。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> import tensorflow as tf
>>> import numpy as np
>>> from transformers import AutoTokenizer, TFXLNetLMHeadModel

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
>>> model = TFXLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")

>>> # We show how to setup inputs to predict a next token using a bi-directional context.
>>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=True))[
...     None, :
... ]  # We will predict the masked token

>>> perm_mask = np.zeros((1, input_ids.shape[1], input_ids.shape[1]))
>>> perm_mask[:, :, -1] = 1.0  # Previous tokens don't see last token

>>> target_mapping = np.zeros(
...     (1, 1, input_ids.shape[1])
... )  # Shape [1, 1, seq_length] => let's predict one token
>>> target_mapping[
...     0, 0, -1
... ] = 1.0  # Our first (and only) prediction will be the last token of the sequence (the masked token)

>>> outputs = model(
...     input_ids,
...     perm_mask=tf.constant(perm_mask, dtype=tf.float32),
...     target_mapping=tf.constant(target_mapping, dtype=tf.float32),
... )

>>> next_token_logits = outputs[
...     0
... ]  # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]

TFXLNetForSequenceClassification

transformers.TFXLNetForSequenceClassification

< >

( config *inputs **kwargs )

参数

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

XLNet 模型,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 GLUE 任务。

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

该模型也是一个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: np.ndarray | tf.Tensor | None = None mems: np.ndarray | tf.Tensor | None = None perm_mask: np.ndarray | tf.Tensor | None = None target_mapping: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None input_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None use_mems: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: bool = False ) transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutputtuple(tf.Tensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (tf.Tensor 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutputtuple(tf.Tensor)

一个 transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForSequenceClassificationOutput 或一个由 tf.Tensor 组成的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置(XLNetConfig)和输入的各种元素。

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 label 时返回) — 分类(或回归,如果 config.num_labels==1)损失。

  • logits (tf.Tensor 形状为 (batch_size, config.num_labels)) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递。

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

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

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, TFXLNetForSequenceClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = TFXLNetForSequenceClassification.from_pretrained("xlnet/xlnet-base-cased")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")

>>> logits = model(**inputs).logits

>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = TFXLNetForSequenceClassification.from_pretrained("xlnet/xlnet-base-cased", num_labels=num_labels)

>>> labels = tf.constant(1)
>>> loss = model(**inputs, labels=labels).loss

TFXLNetForMultipleChoice

transformers.TFXLNetForMultipleChoice

< >

( config *inputs **kwargs )

参数

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

XLNET模型,顶部带有多项选择分类头(在池化输出之上的线性层和softmax),例如用于RocStories/SWAG任务。

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

该模型也是一个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 token_type_ids: np.ndarray | tf.Tensor | None = None input_mask: np.ndarray | tf.Tensor | None = None attention_mask: np.ndarray | tf.Tensor | None = None mems: np.ndarray | tf.Tensor | None = None perm_mask: np.ndarray | tf.Tensor | None = None target_mapping: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None use_mems: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: bool = False ) transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutputtuple(tf.Tensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

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

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, num_choices, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, num_choices, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • labels (tf.Tensor 形状为 (batch_size,), 可选) — 用于计算多项选择分类损失的标签。索引应在 [0, ..., num_choices] 范围内, 其中 num_choices 是输入张量第二维的大小。(参见上面的 input_ids

返回

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForMultipleChoiceOutputtuple(tf.Tensor)

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

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 labels 时返回) — 分类损失。

  • logits (tf.Tensor 形状为 (batch_size, num_choices)) — num_choices 是输入张量的第二维度。(见上面的 input_ids)。

    分类分数(在 SoftMax 之前)。

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递,因为它们已经被计算过。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, TFXLNetForMultipleChoice
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = TFXLNetForMultipleChoice.from_pretrained("xlnet/xlnet-base-cased")

>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."

>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="tf", padding=True)
>>> inputs = {k: tf.expand_dims(v, 0) for k, v in encoding.items()}
>>> outputs = model(inputs)  # batch size is 1

>>> # the linear classifier still needs to be trained
>>> logits = outputs.logits

TFXLNetForTokenClassification

transformers.TFXLNetForTokenClassification

< >

( config *inputs **kwargs )

参数

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

XLNet 模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。

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

该模型也是一个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: np.ndarray | tf.Tensor | None = None mems: np.ndarray | tf.Tensor | None = None perm_mask: np.ndarray | tf.Tensor | None = None target_mapping: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None input_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None use_mems: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: bool = False ) transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutputtuple(tf.Tensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — 用于计算标记分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutputtuple(tf.Tensor)

一个 transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForTokenClassificationOutput 或一个由 tf.Tensor 组成的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置 (XLNetConfig) 和输入的各种元素。

  • loss (tf.Tensor 形状为 (1,), 可选, 当提供 labels 时返回) — 分类损失。

  • logits (tf.Tensor 形状为 (batch_size, sequence_length, config.num_labels)) — 分类分数(在 SoftMax 之前)。

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, TFXLNetForTokenClassification
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = TFXLNetForTokenClassification.from_pretrained("xlnet/xlnet-base-cased")

>>> inputs = tokenizer(
...     "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="tf"
... )

>>> logits = model(**inputs).logits
>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]
>>> labels = predicted_token_class_ids
>>> loss = tf.math.reduce_mean(model(**inputs, labels=labels).loss)

TFXLNetForQuestionAnsweringSimple

transformers.TFXLNetForQuestionAnsweringSimple

< >

( config *inputs **kwargs )

参数

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

XLNet 模型,顶部带有用于抽取式问答任务(如 SQuAD)的跨度分类头(在隐藏状态输出之上的线性层用于计算 span start logitsspan end logits)。

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

该模型也是一个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: np.ndarray | tf.Tensor | None = None mems: np.ndarray | tf.Tensor | None = None perm_mask: np.ndarray | tf.Tensor | None = None target_mapping: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None input_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None use_mems: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None start_positions: np.ndarray | tf.Tensor | None = None end_positions: np.ndarray | tf.Tensor | None = None training: bool = False ) transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutputtuple(tf.Tensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

  • attention_mask (torch.FloatTensor 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.

    什么是注意力掩码?

  • mems (List[torch.FloatTensor] of length config.n_layers) — Contains pre-computed hidden-states (see mems output below) . Can be used to speed up sequential decoding. The token ids which have their past given to this model should not be passed as input_ids as they have already been computed.

    use_mems 必须设置为 True 才能使用 mems

  • perm_mask (torch.FloatTensor of shape (batch_size, sequence_length, sequence_length), optional) — Mask to indicate the attention pattern for each input token with values selected in [0, 1]:
    • if perm_mask[k, i, j] = 0, i attend to j in batch k;
    • if perm_mask[k, i, j] = 1, i does not attend to j in batch k.

    如果未设置,每个标记都会关注所有其他标记(完全双向注意力)。仅在预训练期间(用于定义分解顺序)或顺序解码(生成)时使用。

  • target_mapping (torch.FloatTensor of shape (batch_size, num_predict, sequence_length), optional) — 用于指示要使用的输出标记的掩码。如果 target_mapping[k, i, j] = 1,则批次 k 中的第 i 个预测位于第 j 个标记上。仅在预训练期间用于部分预测或顺序解码(生成)。
  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:
    • 0 corresponds to a sentence A token,
    • 1 corresponds to a sentence B token.

    什么是token type IDs?

  • input_mask (torch.FloatTensor of shape batch_size, sequence_length, optional) — Mask to avoid performing attention on padding token indices. Negative of attention_mask, i.e. with 0 for real tokens and 1 for padding which is kept for compatibility with the original code base.

    [0, 1]中选择的掩码值:

    • 1 for tokens that are masked,
    • 0 for tokens that are not masked.

    你只能使用input_maskattention_mask中的一个。

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • start_positions (tf.Tensor 形状为 (batch_size,), 可选) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
  • end_positions (tf.Tensor of shape (batch_size,), optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。

返回

transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutputtuple(tf.Tensor)

一个 transformers.models.xlnet.modeling_tf_xlnet.TFXLNetForQuestionAnsweringSimpleOutput 或一个由 tf.Tensor 组成的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置(XLNetConfig)和输入的各种元素。

  • loss (tf.Tensor 形状为 (1,)可选,当提供 labels 时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。

  • start_logits (tf.Tensor 形状为 (batch_size, sequence_length,)) — 跨度起始分数(在 SoftMax 之前)。

  • end_logits (tf.Tensor 形状为 (batch_size, sequence_length,)) — 跨度结束分数(在 SoftMax 之前)。

  • mems (List[tf.Tensor] 长度为 config.n_layers) — 包含预计算的隐藏状态。可用于(见 mems 输入)加速顺序解码。已经计算过的 token ids 不应作为 input_ids 传递。

  • 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 之后,用于计算自注意力头中的加权平均值。

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

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

示例:

>>> from transformers import AutoTokenizer, TFXLNetForQuestionAnsweringSimple
>>> import tensorflow as tf

>>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
>>> model = TFXLNetForQuestionAnsweringSimple.from_pretrained("xlnet/xlnet-base-cased")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

>>> inputs = tokenizer(question, text, return_tensors="tf")
>>> outputs = model(**inputs)

>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> # target is "nice puppet"
>>> target_start_index = tf.constant([14])
>>> target_end_index = tf.constant([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = tf.math.reduce_mean(outputs.loss)
< > Update on GitHub