Transformers 文档

DeBERTa

DeBERTa

概述

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于谷歌2018年发布的BERT模型和Facebook 2019年发布的RoBERTa模型。

它在RoBERTa的基础上构建,使用了分离注意力和增强的掩码解码器训练,并且只使用了RoBERTa一半的数据。

论文的摘要如下:

预训练神经语言模型的最新进展显著提高了许多自然语言处理(NLP)任务的性能。在本文中,我们提出了一种新的模型架构DeBERTa(具有解耦注意力的解码增强BERT),该架构通过两种新技术改进了BERT和RoBERTa模型。第一种是解耦注意力机制,其中每个单词使用两个向量表示,分别编码其内容和位置,并且单词之间的注意力权重是使用其内容和相对位置的解耦矩阵计算的。其次,使用增强的掩码解码器替换输出softmax层,以预测模型预训练中的掩码标记。我们展示了这两种技术显著提高了模型预训练的效率和下游任务的性能。与RoBERTa-Large相比,使用一半训练数据训练的DeBERTa模型在各种NLP任务上表现一致更好,在MNLI上提高了+0.9%(90.2% vs. 91.1%),在SQuAD v2.0上提高了+2.3%(88.4% vs. 90.7%),在RACE上提高了+3.6%(83.2% vs. 86.8%)。DeBERTa代码和预训练模型将在https://github.com/microsoft/DeBERTa上公开提供。

该模型由DeBERTa贡献。该模型的TF 2.0实现由kamalkraj贡献。原始代码可以在这里找到。

资源

以下是官方 Hugging Face 和社区(由🌎表示)提供的资源列表,帮助您开始使用 DeBERTa。如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。

Text Classification
Token Classification
Fill-Mask
Question Answering

DebertaConfig

transformers.DebertaConfig

< >

( 词汇表大小 = 50265 隐藏层大小 = 768 隐藏层数量 = 12 注意力头数量 = 12 中间层大小 = 3072 隐藏层激活函数 = 'gelu' 隐藏层dropout概率 = 0.1 注意力概率dropout概率 = 0.1 最大位置嵌入 = 512 类型词汇表大小 = 0 初始化范围 = 0.02 层归一化epsilon = 1e-07 相对注意力 = False 最大相对位置 = -1 填充标记ID = 0 位置偏置输入 = True 位置注意力类型 = None 池化器dropout = 0 池化器隐藏层激活函数 = 'gelu' 遗留 = True **kwargs )

参数

  • vocab_size (int, optional, defaults to 50265) — DeBERTa模型的词汇表大小。定义了调用DebertaModelTFDebertaModel时传递的inputs_ids可以表示的不同标记的数量。
  • hidden_size (int, optional, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数。
  • intermediate_size (int, optional, 默认为 3072) — Transformer 编码器中“中间”(通常称为前馈)层的维度。
  • hidden_act (strCallable, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持 "gelu", "relu", "silu", "gelu", "tanh", "gelu_fast", "mish", "linear", "sigmoid""gelu_new"
  • hidden_dropout_prob (float, 可选, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, optional, 默认为 0.1) — 注意力概率的丢弃比例。
  • max_position_embeddings (int, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • type_vocab_size (int, 可选, 默认为 0) — 调用 DebertaModelTFDebertaModel 时传递的 token_type_ids 的词汇大小.
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • relative_attention (bool, optional, defaults to False) — 是否使用相对位置编码。
  • max_relative_positions (int, 可选, 默认为 1) — 相对位置的范围 [-max_position_embeddings, max_position_embeddings]。使用与 max_position_embeddings 相同的值。
  • pad_token_id (int, optional, 默认为 0) — 用于填充 input_ids 的值。
  • position_biased_input (bool, optional, defaults to True) — 是否将绝对位置嵌入添加到内容嵌入中。
  • pos_att_type (List[str], 可选) — 相对位置注意力的类型,可以是 ["p2c", "c2p"] 的组合,例如 ["p2c"], ["p2c", "c2p"].
  • layer_norm_eps (float, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。
  • legacy (bool, 可选, 默认为 True) — 模型是否应使用旧的 LegacyDebertaOnlyMLMHead,该模型在掩码填充任务中无法正常工作。

这是用于存储DebertaModelTFDebertaModel配置的配置类。它用于根据指定的参数实例化一个DeBERTa模型,定义模型架构。使用默认值实例化配置将产生与DeBERTa microsoft/deberta-base架构类似的配置。

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

示例:

>>> from transformers import DebertaConfig, DebertaModel

>>> # Initializing a DeBERTa microsoft/deberta-base style configuration
>>> configuration = DebertaConfig()

>>> # Initializing a model (with random weights) from the microsoft/deberta-base style configuration
>>> model = DebertaModel(configuration)

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

DebertaTokenizer

transformers.DebertaTokenizer

< >

( vocab_file merges_file errors = 'replace' bos_token = '[CLS]' eos_token = '[SEP]' sep_token = '[SEP]' cls_token = '[CLS]' unk_token = '[UNK]' pad_token = '[PAD]' mask_token = '[MASK]' add_prefix_space = False add_bos_token = False **kwargs )

参数

  • vocab_file (str) — 词汇表文件的路径。
  • merges_file (str) — 合并文件的路径。
  • errors (str, 可选, 默认为 "replace") — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode.
  • bos_token (str, optional, defaults to "[CLS]") — 序列的开始标记。
  • eos_token (str, optional, defaults to "[SEP]") — 序列结束标记。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, 可选, 默认为 "[CLS]") — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, optional, defaults to "[UNK]") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "[PAD]") — 用于填充的标记,例如在批处理不同长度的序列时使用。
  • mask_token (str, 可选, 默认为 "[MASK]") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(Deberta 分词器通过前面的空格检测单词的开头)。
  • add_bos_token (bool, 可选, 默认为 False) — 是否在输入中添加一个初始的 <|endoftext|>。这允许将前导词视为任何其他词。

构建一个DeBERTa分词器。基于字节级的字节对编码。

这个分词器已经被训练成将空格视为标记的一部分(有点像sentencepiece),因此一个单词将会

无论它是否在句子的开头(没有空格),编码方式都会有所不同:

>>> from transformers import DebertaTokenizer

>>> tokenizer = DebertaTokenizer.from_pretrained("microsoft/deberta-base")
>>> tokenizer("Hello world")["input_ids"]
[1, 31414, 232, 2]

>>> tokenizer(" Hello world")["input_ids"]
[1, 20920, 232, 2]

你可以通过在实例化此分词器或在某些文本上调用它时传递add_prefix_space=True来绕过这种行为,但由于模型不是以这种方式预训练的,这可能会导致性能下降。

当与is_split_into_words=True一起使用时,此分词器将在每个单词(即使是第一个单词)前添加一个空格。

此分词器继承自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列表。

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

  • 单个序列: [CLS] X [SEP]
  • 序列对:[CLS] A [SEP] B [SEP]

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_modelencode_plus方法添加特殊标记时,会调用此方法。

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列表。

从传递给的两个序列创建一个掩码,用于序列对分类任务。一个DeBERTa

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

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 )

DebertaTokenizerFast

transformers.DebertaTokenizerFast

< >

( vocab_file = None merges_file = None tokenizer_file = None errors = 'replace' bos_token = '[CLS]' eos_token = '[SEP]' sep_token = '[SEP]' cls_token = '[CLS]' unk_token = '[UNK]' pad_token = '[PAD]' mask_token = '[MASK]' add_prefix_space = False **kwargs )

参数

  • vocab_file (str, optional) — 词汇表文件的路径。
  • merges_file (str, optional) — 合并文件的路径。
  • tokenizer_file (str, optional) — 用于替代词汇表文件的标记器文件路径。
  • errors (str, 可选, 默认为 "replace") — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode.
  • bos_token (str, optional, defaults to "[CLS]") — 序列的开始标记。
  • eos_token (str, optional, defaults to "[SEP]") — 序列结束标记。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • cls_token (str, optional, defaults to "[CLS]") — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。
  • unk_token (str, optional, defaults to "[UNK]") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "[PAD]") — 用于填充的标记,例如在批处理不同长度的序列时使用。
  • mask_token (str, 可选, 默认为 "[MASK]") — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。
  • add_prefix_space (bool, 可选, 默认为 False) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(Deberta 分词器通过前面的空格检测单词的开头)。

构建一个“快速”的DeBERTa分词器(由HuggingFace的tokenizers库支持)。基于字节级别的字节对编码。

这个分词器已经被训练成将空格视为标记的一部分(有点像sentencepiece),因此一个单词将会

无论它是否在句子的开头(没有空格),编码方式都会有所不同:

>>> from transformers import DebertaTokenizerFast

>>> tokenizer = DebertaTokenizerFast.from_pretrained("microsoft/deberta-base")
>>> tokenizer("Hello world")["input_ids"]
[1, 31414, 232, 2]

>>> tokenizer(" Hello world")["input_ids"]
[1, 20920, 232, 2]

你可以通过在实例化这个分词器时传递add_prefix_space=True来绕过这种行为,但由于模型不是以这种方式预训练的,这可能会导致性能下降。

当与is_split_into_words=True一起使用时,此分词器需要使用add_prefix_space=True进行实例化。

这个分词器继承自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列表。

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

  • 单个序列: [CLS] X [SEP]
  • 序列对:[CLS] A [SEP] B [SEP]

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列表。

从传递给的两个序列创建一个掩码,用于序列对分类任务。一个DeBERTa

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

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)。

Pytorch
Hide Pytorch content

DebertaModel

transformers.DebertaModel

< >

( config )

参数

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

裸DeBERTa模型变压器输出原始隐藏状态,没有任何特定的头部。 DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: 解码增强的BERT与解耦注意力中提出。它建立在BERT/RoBERTa之上,有两个改进,即解耦注意力和增强的掩码解码器。通过这两个改进,它在大多数任务上优于BERT/RoBERTa,使用了80GB的预训练数据。

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputtuple(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.

    什么是注意力掩码?

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

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • 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, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

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

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, DebertaModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-base")
>>> model = DebertaModel.from_pretrained("microsoft/deberta-base")

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

>>> last_hidden_states = outputs.last_hidden_state

DebertaPreTrainedModel

transformers.DebertaPreTrainedModel

< >

( config: PretrainedConfig *inputs **kwargs )

一个抽象类,用于处理权重初始化以及下载和加载预训练模型的简单接口。

DebertaForMaskedLM

transformers.DebertaForMaskedLM

< >

( config )

参数

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

DeBERTa模型顶部有一个语言建模头。 DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: 解码增强的BERT与解耦注意力中提出。它建立在BERT/RoBERTa的基础上,有两个改进,即解耦注意力和增强的掩码解码器。通过这两个改进,它在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MaskedLMOutputtuple(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.

    什么是注意力掩码?

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

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • 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 (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算掩码语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码), 损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记计算

返回

transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 掩码语言建模(MLM)损失。

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, DebertaForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("lsanochkin/deberta-large-feedback")
>>> model = DebertaForMaskedLM.from_pretrained("lsanochkin/deberta-large-feedback")

>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt")

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

>>> # retrieve index of [MASK]
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]

>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
>>> tokenizer.decode(predicted_token_id)
' Paris'

>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
>>> # mask labels of non-[MASK] tokens
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)

>>> outputs = model(**inputs, labels=labels)
>>> round(outputs.loss.item(), 2)
0.54

DebertaForSequenceClassification

transformers.DebertaForSequenceClassification

< >

( config )

参数

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

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

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于BERT/RoBERTa构建,并引入了两项改进,即解耦注意力和增强的掩码解码器。通过这两项改进,DeBERTa在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.SequenceClassifierOutputtuple(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.

    什么是注意力掩码?

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

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • 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 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失),如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

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

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

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

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

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

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

单标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, DebertaForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-base")
>>> model = DebertaForSequenceClassification.from_pretrained("microsoft/deberta-base")

>>> 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 = DebertaForSequenceClassification.from_pretrained("microsoft/deberta-base", num_labels=num_labels)

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

多标签分类示例:

>>> import torch
>>> from transformers import AutoTokenizer, DebertaForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-base")
>>> model = DebertaForSequenceClassification.from_pretrained("microsoft/deberta-base", 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 = DebertaForSequenceClassification.from_pretrained(
...     "microsoft/deberta-base", 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

DebertaForTokenClassification

transformers.DebertaForTokenClassification

< >

( config )

参数

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

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

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于BERT/RoBERTa构建,并引入了两项改进,即解耦注意力和增强的掩码解码器。通过这两项改进,DeBERTa在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(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.

    什么是注意力掩码?

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

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • 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, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算标记分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, DebertaForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/deberta-base")
>>> model = DebertaForTokenClassification.from_pretrained("microsoft/deberta-base")

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

DebertaForQuestionAnswering

transformers.DebertaForQuestionAnswering

< >

( config )

参数

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

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

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于BERT/RoBERTa构建,并引入了两项改进,即解耦注意力和增强的掩码解码器。通过这两项改进,DeBERTa在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

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

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: 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 output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(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.

    什么是注意力掩码?

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

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • 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.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

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

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

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

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

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

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

示例:

>>> from transformers import AutoTokenizer, DebertaForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("Palak/microsoft_deberta-large_squad")
>>> model = DebertaForQuestionAnswering.from_pretrained("Palak/microsoft_deberta-large_squad")

>>> 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]
>>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
' a nice puppet'

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

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
0.14
TensorFlow
Hide TensorFlow content

TFDebertaModel

transformers.TFDebertaModel

< >

( config: DebertaConfig *inputs **kwargs )

参数

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

裸DeBERTa模型变压器输出原始隐藏状态,没有任何特定的头部。 DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: 解码增强的BERT与解耦注意力中提出。它建立在BERT/RoBERTa之上,有两个改进,即解耦注意力和增强的掩码解码器。通过这两个改进,它在大多数任务上优于BERT/RoBERTa,使用了80GB的预训练数据。

该模型也是一个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 token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFBaseModelOutputtuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • attention_mask (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (np.ndarray or tf.Tensor 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?

  • position_ids (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

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

返回

transformers.modeling_tf_outputs.TFBaseModelOutputtuple(tf.Tensor)

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

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

  • hidden_states (tuple(tf.FloatTensor), 可选, 当 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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

示例:

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

>>> tokenizer = AutoTokenizer.from_pretrained("kamalkraj/deberta-base")
>>> model = TFDebertaModel.from_pretrained("kamalkraj/deberta-base")

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

>>> last_hidden_states = outputs.last_hidden_state

TFDebertaPreTrainedModel

transformers.TFDebertaPreTrainedModel

< >

( *args **kwargs )

一个抽象类,用于处理权重初始化以及下载和加载预训练模型的简单接口。

调用

< >

( inputs training = None mask = None )

参数

  • inputs — 输入张量,或输入张量的字典/列表/元组。
  • 训练 — 布尔值或布尔标量张量,指示是否在训练模式或推理模式下运行 Network
  • mask — 一个掩码或掩码列表。掩码可以是布尔张量或None(无掩码)。更多详情,请查看指南这里.

在新输入上调用模型并返回张量形式的输出。

在这种情况下,call() 只是将图中的所有操作重新应用到新的输入上(例如,从提供的输入构建一个新的计算图)。

注意:此方法不应直接调用。它仅在子类化 tf.keras.Model 时用于重写。 要在输入上调用模型,请始终使用 __call__() 方法, 即 model(inputs),它依赖于底层的 call() 方法。

TFDebertaForMaskedLM

transformers.TFDebertaForMaskedLM

< >

( config: DebertaConfig *inputs **kwargs )

参数

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

DeBERTa模型顶部有一个语言建模头。 DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: 解码增强的BERT与解耦注意力中提出。它建立在BERT/RoBERTa的基础上,有两个改进,即解耦注意力和增强的掩码解码器。通过这两个改进,它在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

该模型也是一个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 token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = 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: Optional[bool] = False ) transformers.modeling_tf_outputs.TFMaskedLMOutputtuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • attention_mask (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (np.ndarray or tf.Tensor 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?

  • position_ids (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

  • inputs_embeds (np.ndarraytf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
  • return_dict (bool, optional) — 是否返回一个[`~utils.ModelOutput`]而不是一个普通的元组。
  • labels (tf.Tensornp.ndarray 形状为 (batch_size, sequence_length), 可选) — 用于计算掩码语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码), 损失仅针对标签在 [0, ..., config.vocab_size] 范围内的标记进行计算

返回

transformers.modeling_tf_outputs.TFMaskedLMOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFMaskedLMOutput 或一个 tf.Tensor 元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置 (DebertaConfig) 和输入的各种元素。

  • loss (tf.Tensor 形状为 (n,), 可选, 其中 n 是非掩码标签的数量,当提供 labels 时返回) — 掩码语言建模(MLM)损失。

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

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

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

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

示例:

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

>>> tokenizer = AutoTokenizer.from_pretrained("kamalkraj/deberta-base")
>>> model = TFDebertaForMaskedLM.from_pretrained("kamalkraj/deberta-base")

>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="tf")
>>> logits = model(**inputs).logits

>>> # retrieve index of [MASK]
>>> mask_token_index = tf.where((inputs.input_ids == tokenizer.mask_token_id)[0])
>>> selected_logits = tf.gather_nd(logits[0], indices=mask_token_index)

>>> predicted_token_id = tf.math.argmax(selected_logits, axis=-1)
>>> labels = tokenizer("The capital of France is Paris.", return_tensors="tf")["input_ids"]
>>> # mask labels of non-[MASK] tokens
>>> labels = tf.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)

>>> outputs = model(**inputs, labels=labels)

TFDebertaForSequenceClassification

class transformers.TFDebertaForSequenceClassification

< >

( config: DebertaConfig *inputs **kwargs )

参数

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

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

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于BERT/RoBERTa构建,并引入了两项改进,即解耦注意力和增强的掩码解码器。通过这两项改进,DeBERTa在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

该模型也是一个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 token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = 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: Optional[bool] = False ) transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • attention_mask (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (np.ndarray or tf.Tensor 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?

  • position_ids (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

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

返回

transformers.modeling_tf_outputs.TFSequenceClassifierOutputtuple(tf.Tensor)

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

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

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

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

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

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

示例:

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

>>> tokenizer = AutoTokenizer.from_pretrained("kamalkraj/deberta-base")
>>> model = TFDebertaForSequenceClassification.from_pretrained("kamalkraj/deberta-base")

>>> 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 = TFDebertaForSequenceClassification.from_pretrained("kamalkraj/deberta-base", num_labels=num_labels)

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

TFDebertaForTokenClassification

transformers.TFDebertaForTokenClassification

< >

( config: DebertaConfig *inputs **kwargs )

参数

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

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

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于BERT/RoBERTa构建,并引入了两项改进,即解耦注意力和增强的掩码解码器。通过这两项改进,DeBERTa在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

该模型也是一个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 token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = 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: Optional[bool] = False ) transformers.modeling_tf_outputs.TFTokenClassifierOutputtuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • attention_mask (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (np.ndarray or tf.Tensor 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?

  • position_ids (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

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

返回

transformers.modeling_tf_outputs.TFTokenClassifierOutputtuple(tf.Tensor)

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

  • loss (tf.Tensor 形状为 (n,), 可选, 其中 n 是未掩码标签的数量,当提供 labels 时返回) — 分类损失。

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

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

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

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

示例:

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

>>> tokenizer = AutoTokenizer.from_pretrained("kamalkraj/deberta-base")
>>> model = TFDebertaForTokenClassification.from_pretrained("kamalkraj/deberta-base")

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

TFDebertaForQuestionAnswering

transformers.TFDebertaForQuestionAnswering

< >

( config: DebertaConfig *inputs **kwargs )

参数

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

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

DeBERTa模型由彭成和、刘晓东、高剑峰、陈伟柱在DeBERTa: Decoding-enhanced BERT with Disentangled Attention中提出。它基于BERT/RoBERTa构建,并引入了两项改进,即解耦注意力和增强的掩码解码器。通过这两项改进,DeBERTa在大多数任务上表现优于BERT/RoBERTa,使用了80GB的预训练数据。

该模型也是一个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 token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = 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: Optional[bool] = False ) transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] and each example must have the shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary.

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

    什么是输入ID?

  • attention_mask (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • token_type_ids (np.ndarray or tf.Tensor 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?

  • position_ids (np.ndarray or tf.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1].

    什么是位置ID?

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

返回

transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

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

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

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

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

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

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

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

示例:

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

>>> tokenizer = AutoTokenizer.from_pretrained("kamalkraj/deberta-base")
>>> model = TFDebertaForQuestionAnswering.from_pretrained("kamalkraj/deberta-base")

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