Transformers 文档

RemBERT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

RemBERT

概述

RemBERT 模型由 Hyung Won Chung、Thibault Févry、Henry Tsai、Melvin Johnson 和 Sebastian Ruder 在Rethinking Embedding Coupling in Pre-trained Language Models中提出。

论文摘要如下

We re-evaluate the standard practice of sharing weights between input and output embeddings in state-of-the-art pre-trained language models. We show that decoupled embeddings provide increased modeling flexibility, allowing us to significantly improve the efficiency of parameter allocation in the input embedding of multilingual models. By reallocating the input embedding parameters in the Transformer layers, we achieve dramatically better performance on standard natural language understanding tasks with the same number of parameters during fine-tuning. We also show that allocating additional capacity to the output embedding provides benefits to the model that persist through the fine-tuning stage even though the output embedding is discarded after pre-training. Our analysis shows that larger output embeddings prevent the model’s last layers from overspecializing to the pre-training task and encourage Transformer representations to be more general and more transferable to other tasks and languages. Harnessing these findings, we are able to train models that achieve strong performance on the XTREME benchmark without increasing the number of parameters at the fine-tuning stage.

使用技巧

For fine-tuning, RemBERT can be thought of as a bigger version of mBERT with an ALBERT-like factorization of the embedding layer. The embeddings are not tied in pre-training, in contrast with BERT, which enables smaller input embeddings (preserved during fine-tuning) and bigger output embeddings (discarded at fine-tuning). The tokenizer is also similar to the Albert one rather than the BERT one.

资源

RemBertConfig

class transformers.RemBertConfig

< >

( vocab_size = 250300 hidden_size = 1152 num_hidden_layers = 32 num_attention_heads = 18 input_embedding_size = 256 output_embedding_size = 1664 intermediate_size = 4608 hidden_act = 'gelu' hidden_dropout_prob = 0.0 attention_probs_dropout_prob = 0.0 classifier_dropout_prob = 0.1 max_position_embeddings = 512 type_vocab_size = 2 initializer_range = 0.02 layer_norm_eps = 1e-12 use_cache = True pad_token_id = 0 bos_token_id = 312 eos_token_id = 313 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 250300) — RemBERT 模型的词汇表大小。 定义了在调用 RemBertModelTFRemBertModel 时,可以通过 inputs_ids 传递的不同 token 的数量。 模型的词汇表大小。 定义了可以通过传递给 RemBertModel 前向方法的 inputs_ids 表示的不同 token。
  • hidden_size (int, 可选, 默认为 1152) — 编码器层和池化器层的维度。
  • num_hidden_layers (int, 可选, 默认为 32) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, 可选, 默认为 18) — Transformer 编码器中每个注意力层的注意力头数。
  • input_embedding_size (int, 可选, 默认为 256) — 输入嵌入的维度。
  • output_embedding_size (int, 可选, 默认为 1664) — 输出嵌入的维度。
  • intermediate_size (int, 可选, 默认为 4608) — Transformer 编码器中“中间”(即,前馈)层的维度。
  • hidden_act (strfunction, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu", "relu", "selu""gelu_new"
  • hidden_dropout_prob (float, 可选, 默认为 0) — 嵌入、编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, 可选, 默认为 0) — 注意力概率的 dropout 比率。
  • classifier_dropout_prob (float, 可选, 默认为 0.1) — 微调时分类器层的 dropout 比率。
  • max_position_embeddings (int, 可选, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • type_vocab_size (int, 可选, 默认为 2) — 调用 RemBertModelTFRemBertModel 时传递的 token_type_ids 的词汇表大小。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-12) — 层归一化层使用的 epsilon 值。
  • is_decoder (bool, 可选, 默认为 False) — 模型是否用作解码器。如果为 False,则模型用作编码器。
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回上次的键/值注意力(并非所有模型都使用)。仅当 config.is_decoder=True 时相关。

这是用于存储 RemBertModel 配置的配置类。它用于根据指定的参数实例化 RemBERT 模型,定义模型架构。使用默认值实例化配置将产生与 RemBERT google/rembert 架构类似的配置。

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

示例

>>> from transformers import RemBertModel, RemBertConfig

>>> # Initializing a RemBERT rembert style configuration
>>> configuration = RemBertConfig()

>>> # Initializing a model from the rembert style configuration
>>> model = RemBertModel(configuration)

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

RemBertTokenizer

class transformers.RemBertTokenizer

< >

( vocab_file do_lower_case = False remove_space = True keep_accents = True bos_token = '[CLS]' eos_token = '[SEP]' unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),其中包含实例化 tokenizer 所需的词汇表。
  • bos_token (str, 可选, 默认为 "[CLS]") — 预训练期间使用的序列开始 token。可以用作序列分类器 token。

    当使用特殊 token 构建序列时,这不是用于序列开始的 token。使用的 token 是 cls_token

  • eos_token (str, 可选, 默认为 "[SEP]") — 序列结束 token。

    当使用特殊 token 构建序列时,这不是用于序列结束的 token。使用的 token 是 sep_token

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

构建 RemBERT 分词器。基于 SentencePiece

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

build_inputs_with_special_tokens

< >

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

参数

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

返回:

List[int]

包含适当特殊标记的输入 ID 列表。

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

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

get_special_tokens_mask

< >

( token_ids_0: List token_ids_1: Optional = 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: List token_ids_1: Optional = None ) List[int]

参数

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

返回:

List[int]

根据给定序列的标记类型 ID 列表。

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

序列对掩码具有以下格式

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 ,则此方法仅返回掩码的第一部分(0)。

save_vocabulary

< >

( save_directory: str filename_prefix: Optional = None )

RemBertTokenizerFast

class transformers.RemBertTokenizerFast

< >

( vocab_file = None tokenizer_file = None do_lower_case = True remove_space = True keep_accents = False bos_token = '[CLS]' eos_token = '[SEP]' unk_token = '<unk>' sep_token = '[SEP]' pad_token = '<pad>' cls_token = '[CLS]' mask_token = '[MASK]' **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),其中包含实例化分词器所需的词汇表。
  • do_lower_case (bool, optional, defaults to True) — 在分词时是否将输入转换为小写。
  • remove_space (bool, optional, defaults to True) — 在分词时是否去除文本(删除字符串前后多余的空格)。
  • keep_accents (bool, optional, defaults to False) — 在分词时是否保留重音符号。
  • bos_token (str, optional, defaults to "[CLS]") — 预训练期间使用的序列开始标记。可以用作序列分类器标记。

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

  • eos_token (str, optional, defaults to "[SEP]") — 序列结束标记。 .. note:: 当使用特殊标记构建序列时,这不是用于序列结束的标记。使用的标记是 sep_token
  • unk_token (str, optional, defaults to "<unk>") — 未知标记。词汇表中没有的标记无法转换为 ID,而是设置为此标记。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列,或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。
  • pad_token (str, optional, defaults to "<pad>") — 用于填充的标记,例如在对不同长度的序列进行批处理时。
  • cls_token (str, optional, defaults to "[CLS]") — 分类器标记,用于进行序列分类(对整个序列而不是每个标记进行分类)。当使用特殊标记构建序列时,它是序列的第一个标记。
  • mask_token (str, optional, defaults to "[MASK]") — 用于掩码值的 token。 这是使用掩码语言建模训练此模型时使用的 token。 这是模型将尝试预测的 token。

构建一个“快速” RemBert 分词器(由 HuggingFace 的 tokenizers 库支持)。 基于 Unigram。 此分词器继承自 PreTrainedTokenizerFast,其中包含大多数主要方法。 用户应参考此超类以获取有关这些方法的更多信息

build_inputs_with_special_tokens

< >

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

参数

  • token_ids_0 (List[int]) — 将向其添加特殊 token 的 ID 列表
  • token_ids_1 (List[int], optional, defaults to None) — 序列对的可选第二个 ID 列表。

返回:

List[int]

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

通过连接并添加特殊 token,从序列或序列对构建模型输入,用于序列分类任务。 RemBERT 序列具有以下格式

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

get_special_tokens_mask

< >

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

参数

  • token_ids_0 (List[int]) — ID 列表。
  • token_ids_1 (List[int], optional, defaults to None) — 序列对的可选第二个 ID 列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 如果 token 列表已使用模型的特殊 token 格式化,则设置为 True

返回:

List[int]

范围为 [0, 1] 的整数列表:特殊标记为 1,序列标记为 0。

从没有添加特殊 token 的 token 列表中检索序列 ID。 当使用分词器的 prepare_for_model 方法添加特殊 token 时,将调用此方法。

create_token_type_ids_from_sequences

< >

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

参数

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

返回:

List[int]

根据给定序列的标记类型 ID 列表。

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

序列对掩码具有以下格式

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_1 为 None,则仅返回掩码的第一部分(0)。

save_vocabulary

< >

( save_directory: str filename_prefix: Optional = None )

Pytorch
隐藏 Pytorch 内容

RemBertModel

class transformers.RemBertModel

< >

( config add_pooling_layer = True )

参数

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

裸 RemBERT 模型 Transformer 输出原始隐藏状态,顶部没有任何特定的 head。 此模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

该模型可以充当编码器(仅具有自注意力),也可以充当解码器,在后一种情况下,在自注意力层之间添加一个交叉注意力层,遵循 Attention is all you need 中 Ashish Vaswani、Noam Shazeer、Niki Parmar、Jakob Uszkoreit、Llion Jones、Aidan N. Gomez、Lukasz Kaiser 和 Illia Polosukhin 描述的架构。

要充当解码器,模型需要使用配置的 is_decoder 参数设置为 True 进行初始化。 要在 Seq2Seq 模型中使用,模型需要使用 is_decoder 参数和 add_cross_attention 都设置为 True 进行初始化; 然后需要将 encoder_hidden_states 作为前向传递的输入。

forward

< >

( input_ids: LongTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None encoder_hidden_states: Optional = None encoder_attention_mask: Optional = None past_key_values: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列 token 的索引。

    可以使用 AutoTokenizer 获取索引。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length), optional) — 掩码,以避免对填充 token 索引执行注意力机制。 在 [0, 1] 中选择的掩码值:

    • 1 表示 token 未被掩码
    • 0 表示 token 被掩码

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length), optional) — 分段 token 索引,用于指示输入的第一部分和第二部分。 在 [0, 1] 中选择索引:

    • 0 对应于 句子 A token,
    • 1 对应于 句子 B token。

    什么是 token 类型 ID?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length), optional) — 每个输入序列 token 在位置嵌入中的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 ID?

  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads), optional) — 用于使自注意力模块的选定 head 失效的掩码。 在 [0, 1] 中选择的掩码值:

    • 1 表示 head 未被掩码
    • 0 表示 head 被掩码
  • inputs_embeds (torch.FloatTensor,形状为 (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, optional) — 是否返回 ModelOutput 而不是普通的元组。
  • encoder_hidden_states (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 编码器最后一层的输出的隐藏状态序列。 如果模型配置为解码器,则在交叉注意力机制中使用。
  • encoder_attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — 用于避免在编码器输入的填充 token 索引上执行注意力的掩码。 如果模型配置为解码器,则在交叉注意力机制中使用此掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 token 未被掩盖
    • 0 表示 token 被掩盖
  • past_key_values (tuple(tuple(torch.FloatTensor)),长度为 config.n_layers,每个元组包含 4 个形状为 (batch_size, num_heads, sequence_length - 1, embed_size_per_head) 的张量) — 包含注意力模块的预先计算的键和值隐藏状态。 可用于加速解码。 如果使用 past_key_values,用户可以选择仅输入形状为 (batch_size, 1) 的最后一个 decoder_input_ids (那些没有提供给此模型的过去键值状态的),而不是形状为 (batch_size, sequence_length) 的所有 decoder_input_ids
  • use_cache (bool, optional) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。

返回:

transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

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

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

    如果使用 past_key_values,则仅输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — tuple(torch.FloatTensor) 的元组,长度为 config.n_layers,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量,以及可选的,如果 config.is_encoder_decoder=True,则包含 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

    包含预先计算的隐藏状态(自注意力模块中的键和值,以及可选的,如果 config.is_encoder_decoder=True,则在交叉注意力模块中),这些状态可以用于(参见 past_key_values 输入)加速顺序解码。

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

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

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

RemBertModel forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, RemBertModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertModel.from_pretrained("google/rembert")

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

>>> last_hidden_states = outputs.last_hidden_state

RemBertForCausalLM

class transformers.RemBertForCausalLM

< >

( config )

参数

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

RemBERT 模型,顶部带有用于 CLM 微调的 language modeling 头。 该模型是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与常规用法和行为相关的事项。

forward

< >

( input_ids: LongTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None encoder_hidden_states: Optional = None encoder_attention_mask: Optional = None past_key_values: Optional = None labels: Optional = None use_cache: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.CausalLMOutputWithCrossAttentionstuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列 tokens 的索引。

    索引可以使用 AutoTokenizer 获得。 参见 PreTrainedTokenizer.encode()PreTrainedTokenizer.call() 了解详情。

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — 用于避免在填充 token 索引上执行注意力的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 token 未被掩盖
    • 0 表示 token 被掩盖

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 分段 token 索引以指示输入的第一部分和第二部分。 索引在 [0, 1] 中选择:

    • 0 对应于 句子 A token,
    • 1 对应于 句子 B token。

    什么是 token 类型 IDs?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 位置嵌入中每个输入序列 tokens 的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 IDs?

  • 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, optional) — 是否返回所有注意力层的注意力张量。 详见返回张量下的 attentions 部分了解更多详情。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states 部分了解更多详情。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯元组。
  • encoder_hidden_states (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 编码器最后一层的输出端的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。
  • encoder_attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — 用于避免在编码器输入的填充标记索引上执行注意力的掩码。如果模型配置为解码器,则此掩码在交叉注意力中使用。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩蔽
    • 0 表示标记被掩蔽
  • past_key_values (tuple(tuple(torch.FloatTensor)),长度为 config.n_layers,每个元组包含 4 个形状为 (batch_size, num_heads, sequence_length - 1, embed_size_per_head) 的张量) — 包含注意力块的预计算的键和值隐藏状态。可用于加速解码。如果使用 past_key_values,则用户可以选择仅输入最后面的 decoder_input_ids(那些没有将其过去的键值状态提供给此模型的),形状为 (batch_size, 1),而不是所有形状为 (batch_size, sequence_length)decoder_input_ids
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 用于计算从左到右语言建模损失(下一个词预测)的标签。索引应在 [-100, 0, ..., config.vocab_size] 中(请参阅 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩蔽),损失仅针对标签在 [0, ..., config.vocab_size] 中的标记计算。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(请参阅 past_key_values)。

返回:

transformers.modeling_outputs.CausalLMOutputWithCrossAttentionstuple(torch.FloatTensor)

一个 transformers.modeling_outputs.CausalLMOutputWithCrossAttentionstorch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置 (RemBertConfig) 和输入。

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

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

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

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

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — torch.FloatTensor 元组的元组,长度为 config.n_layers,每个元组都包含自注意力和交叉注意力层的缓存键、值状态(如果模型在编码器-解码器设置中使用)。仅当 config.is_decoder = True 时相关。

    包含预先计算的隐藏状态(注意力块中的键和值),可以用于(请参阅 past_key_values 输入)加速顺序解码。

RemBertForCausalLM 前向方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, RemBertForCausalLM, RemBertConfig
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> config = RemBertConfig.from_pretrained("google/rembert")
>>> config.is_decoder = True
>>> model = RemBertForCausalLM.from_pretrained("google/rembert", config=config)

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

>>> prediction_logits = outputs.logits

RemBertForMaskedLM

class transformers.RemBertForMaskedLM

< >

( config )

参数

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

带有位于顶部的 language modeling 头的 RemBERT 模型。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以获取与常规用法和行为相关的所有事项。

forward

< >

( input_ids: LongTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None encoder_hidden_states: Optional = None encoder_attention_mask: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — 用于避免在填充标记索引上执行注意力的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩蔽
    • 0 表示标记被掩蔽

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 分段标记索引,用于指示输入的第一个和第二个部分。索引在 [0, 1] 中选择:

    • 0 对应于句子 A 标记,
    • 1 对应于句子 B 标记。

    什么是标记类型 ID?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 位置嵌入中每个输入序列标记的位置索引。在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 ID?

  • 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,形状为 (batch_size, sequence_length)可选) — 用于计算掩码语言建模损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 中(请参阅 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩蔽),损失仅针对标签在 [0, ..., config.vocab_size] 中的标记计算。

返回:

transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.MaskedLMOutputtorch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),其中包含各种元素,具体取决于配置 (RemBertConfig) 和输入。

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

RemBertForMaskedLM 前向方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, RemBertForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertForMaskedLM.from_pretrained("google/rembert")

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

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

RemBertForSequenceClassification

class transformers.RemBertForSequenceClassification

< >

( config )

参数

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

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

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( input_ids: FloatTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — 词汇表中输入序列tokens的索引。

    索引可以使用 AutoTokenizer 获得。 请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.__call__() 以获取详细信息。

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免对padding token索引执行attention的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 **未掩码** 的 tokens,
    • 0 表示 **已掩码** 的 tokens。

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 段token索引,用于指示输入的第一个和第二个部分。索引在 [0, 1] 中选择:

    • 0 对应于 *句子 A* token,
    • 1 对应于 *句子 B* token。

    什么是 token 类型 IDs?

  • position_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 每个输入序列token在位置嵌入中的位置索引。在 [0, config.max_position_embeddings - 1] 范围内选择。

    什么是位置 IDs?

  • head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于使自注意力模块的选定head无效的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head **未被掩码**,
    • 0 表示 head **被掩码**。
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递 `input_ids`。如果您想比模型的内部嵌入查找矩阵更精细地控制如何将 `input_ids` 索引转换为关联向量,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有注意力层的attention tensors。有关更多详细信息,请参阅返回的 tensors 下的 `attentions`。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回的 tensors 下的 `hidden_states`。
  • return_dict (bool, optional) — 是否返回 `ModelOutput` 而不是普通tuple。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 中。如果 `config.num_labels == 1`,则计算回归损失(均方误差损失);如果 `config.num_labels > 1`,则计算分类损失(交叉熵损失)。

返回:

transformers.modeling_outputs.SequenceClassifierOutput or tuple(torch.FloatTensor)

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

  • loss (torch.FloatTensor of shape (1,), optional, returned when labels is provided) — 分类(或回归,如果 `config.num_labels==1`)损失。

  • logits (torch.FloatTensor of shape (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 之后的注意力权重,用于计算自注意力头中的加权平均值。

`RemBertForSequenceClassification` 的 `forward` 方法,覆盖了 __call__ 特殊方法。

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

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, RemBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertForSequenceClassification.from_pretrained("google/rembert")

>>> 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 = RemBertForSequenceClassification.from_pretrained("google/rembert", num_labels=num_labels)

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

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, RemBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertForSequenceClassification.from_pretrained("google/rembert", 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 = RemBertForSequenceClassification.from_pretrained(
...     "google/rembert", 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

RemBertForMultipleChoice

class transformers.RemBertForMultipleChoice

< >

( config )

参数

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

RemBERT 模型,顶部带有单项选择分类头(池化输出顶部的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( input_ids: FloatTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.MultipleChoiceModelOutput or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length)) — 词汇表中输入序列tokens的索引。

    索引可以使用 AutoTokenizer 获得。 请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.__call__() 以获取详细信息。

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor of shape (batch_size, num_choices, sequence_length), optional) — 用于避免对padding token索引执行attention的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 **未掩码** 的 tokens,
    • 0 表示 **已掩码** 的 tokens。

    什么是注意力掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, num_choices, sequence_length)可选) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 对应于 sentence A token,
    • 1 对应于 sentence B token。

    什么是 token type IDs?

  • position_ids (torch.LongTensor,形状为 (batch_size, num_choices, sequence_length)可选) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.max_position_embeddings - 1]

    什么是 position IDs?

  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads)可选) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 表示 head 是未被遮罩的
    • 0 表示 head 是被遮罩的
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, num_choices, sequence_length, hidden_size)可选) — (可选) 您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool可选) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. (是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions。)
  • output_hidden_states (bool可选) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. (是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。)
  • return_dict (bool可选) — Whether or not to return a ModelOutput instead of a plain tuple. (是否返回 ModelOutput 而不是一个普通元组。)
  • labels (torch.LongTensor,形状为 (batch_size,)可选) — Labels for computing the multiple choice classification loss. Indices should be in [0, ..., num_choices-1] where num_choices is the size of the second dimension of the input tensors. (See input_ids above) (用于计算多项选择分类损失的标签。索引应在 [0, ..., num_choices-1] 中,其中 num_choices 是输入张量第二维的大小。(请参阅上面的 input_ids))

返回:

transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

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

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

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

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

RemBertForMultipleChoice 的前向传播方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, RemBertForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertForMultipleChoice.from_pretrained("google/rembert")

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

RemBertForTokenClassification

class transformers.RemBertForTokenClassification

< >

( config )

参数

  • config (RemBertConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights. (模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。)

RemBERT 模型,顶部带有一个 token 分类 head(隐藏状态输出顶部的线性层),例如,用于命名实体识别 (NER) 任务。

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( input_ids: FloatTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None labels: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列 tokens 的索引。

    可以使用 AutoTokenizer 获取索引。请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call() 以了解详细信息。

    什么是 input IDs?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 表示 tokens 是未被遮罩的
    • 0 表示 tokens 是被遮罩的

    什么是 attention masks?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in [0, 1]:

    • 0 对应于 sentence A token,
    • 1 对应于 sentence B token。

    什么是 token type IDs?

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

    什么是 position IDs?

  • head_mask (torch.FloatTensor,形状为 (num_heads,)(num_layers, num_heads)可选) — Mask to nullify selected heads of the self-attention modules. Mask values selected in [0, 1]:

    • 1 表示 head 是未被遮罩的
    • 0 表示 head 是被遮罩的
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — (可选) 您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool可选) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail. (是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions。)
  • output_hidden_states (bool可选) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail. (是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。)
  • return_dict (bool可选) — Whether or not to return a ModelOutput instead of a plain tuple. (是否返回 ModelOutput 而不是一个普通元组。)
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — Labels for computing the token classification loss. Indices should be in [0, ..., config.num_labels - 1]. (用于计算 token 分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 中。)

返回:

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

  • logits (torch.FloatTensor,形状为 (batch_size, sequence_length, config.num_labels)) — Classification scores (before SoftMax). (分类得分(在 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 之后的注意力权重,用于计算自注意力头中的加权平均值。

RemBertForTokenClassification 的前向传播方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, RemBertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertForTokenClassification.from_pretrained("google/rembert")

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

RemBertForQuestionAnswering

class transformers.RemBertForQuestionAnswering

< >

( config )

参数

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

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

此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参考 PyTorch 文档以了解与常规用法和行为相关的所有事项。

forward

< >

( input_ids: FloatTensor = None attention_mask: Optional = None token_type_ids: Optional = None position_ids: Optional = None head_mask: Optional = None inputs_embeds: Optional = None start_positions: Optional = None end_positions: Optional = None output_attentions: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(torch.FloatTensor)

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列标记的索引。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 IDs?

  • attention_mask (形状为 (batch_size, sequence_length)torch.FloatTensor可选) — 掩码,用于避免在 padding 标记索引上执行 attention。Mask 值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是 attention masks?

  • token_type_ids (形状为 (batch_size, sequence_length)torch.LongTensor可选) — 分段标记索引,用于指示输入的第一部分和第二部分。索引在 [0, 1] 中选择:

    • 0 对应于 句子 A 标记,
    • 1 对应于 句子 B 标记。

    什么是标记类型 IDs?

  • position_ids (形状为 (batch_size, sequence_length)torch.LongTensor可选) — 每个输入序列标记在位置嵌入中的位置索引。在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 IDs?

  • head_mask (形状为 (num_heads,)(num_layers, num_heads)torch.FloatTensor可选) — 用于 nullify 自注意力模块的选定头的掩码。Mask 值在 [0, 1] 中选择:

    • 1 表示头未被掩码
    • 0 表示头被掩码
  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想要比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联的向量,这将非常有用。
  • output_attentions (bool可选) — 是否返回所有 attention 层的 attention 张量。有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通元组。
  • start_positions (形状为 (batch_size,)torch.LongTensor可选) — 用于计算标记分类损失的标记跨度开始位置(索引)的标签。位置被限制在序列的长度(sequence_length)内。序列之外的位置不计入损失计算。
  • end_positions (形状为 (batch_size,)torch.LongTensor可选) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。位置被限制在序列的长度(sequence_length)内。序列之外的位置不计入损失计算。

返回:

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

transformers.modeling_outputs.QuestionAnsweringModelOutputtorch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包括各种元素,具体取决于配置 (RemBertConfig) 和输入。

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

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

  • end_logits (形状为 (batch_size, sequence_length)torch.FloatTensor) — 跨度结束分数(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 之后的注意力权重,用于计算自注意力头中的加权平均值。

RemBertForQuestionAnswering 的 forward 方法,覆盖了 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, RemBertForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = RemBertForQuestionAnswering.from_pretrained("google/rembert")

>>> 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
TensorFlow
隐藏 TensorFlow 内容

TFRemBertModel

class transformers.TFRemBertModel

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

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

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None encoder_hidden_states: np.ndarray | tf.Tensor | None = None encoder_attention_mask: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None use_cache: Optional[bool] = 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.TFBaseModelOutputWithPoolingAndCrossAttentions or tuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor]Dict[str, np.ndarray],并且每个示例都必须具有形状 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入 IDs?

  • attention_mask (形状为 (batch_size, sequence_length)np.ndarraytf.Tensor可选) — 掩码,用于避免在 padding 标记索引上执行 attention。Mask 值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是 attention masks?

  • token_type_ids (形状为 (batch_size, sequence_length)np.ndarraytf.Tensor可选) — 分段标记索引,用于指示输入的第一部分和第二部分。索引在 [0, 1] 中选择:

    • 0 对应于 句子 A 标记,
    • 1 对应于 句子 B 标记。

    什么是标记类型 IDs?

  • position_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length)可选) — 每个输入序列 token 在位置嵌入中的位置索引。在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 ID?

  • head_mask (np.ndarraytf.Tensor,形状为 (num_heads,)(num_layers, num_heads)可选) — 用于置空自注意力模块中选定 head 的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head 不被掩盖
    • 0 表示 head 被掩盖
  • inputs_embeds (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length, hidden_size)可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是纯元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。
  • training (bool可选,默认为 `False`) — 是否在训练模式下使用模型(某些模块(如 dropout 模块)在训练和评估之间具有不同的行为)。
  • encoder_hidden_states (tf.Tensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 编码器最后一层输出的隐藏状态序列。如果模型配置为解码器,则在交叉注意力中使用。
  • encoder_attention_mask (tf.Tensor,形状为 (batch_size, sequence_length)可选) — 用于避免对编码器输入的 padding token 索引执行注意力的掩码。如果模型配置为解码器,则此掩码在交叉注意力中使用。掩码值在 [0, 1] 中选择:

    • 1 表示 token 不被掩盖
    • 0 表示 token 被掩盖
  • past_key_values (Tuple[Tuple[tf.Tensor]],长度为 config.n_layers) — 包含注意力块的预计算的 key 和 value 隐藏状态。可用于加速解码。如果使用 past_key_values,则用户可以选择仅输入最后一个 decoder_input_ids(那些没有将其过去的 key value 状态提供给此模型的),形状为 (batch_size, 1),而不是所有形状为 (batch_size, sequence_length)decoder_input_ids
  • use_cache (bool可选,默认为 True) — 如果设置为 True,则返回 past_key_values 键值状态,并且可以用于加速解码(请参阅 past_key_values)。在训练期间设置为 False,在生成期间设置为 True

返回:

transformers.modeling_tf_outputs.TFBaseModelOutputWithPoolingAndCrossAttentionstuple(tf.Tensor)

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

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

  • pooler_output (tf.Tensor,形状为 (batch_size, hidden_size)) — 序列的第一个 token(分类 token)的最后一层隐藏状态,通过线性层和 Tanh 激活函数进一步处理。线性层权重在预训练期间从下一句预测(分类)目标中训练得出。

    此输出通常不是输入语义内容的良好摘要,对于整个输入序列,您通常最好使用平均或池化隐藏状态序列。

  • past_key_values (List[tf.Tensor]可选,当传递 use_cache=Trueconfig.use_cache=True 时返回) — tf.Tensor 的列表,长度为 config.n_layers,每个张量的形状为 (2, batch_size, num_heads, sequence_length, embed_size_per_head))。

    包含预先计算的隐藏状态(注意力块中的键和值),可以用于(请参阅 past_key_values 输入)加速顺序解码。

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

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

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

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

TFRemBertModel 前向方法,覆盖了 __call__ 特殊方法。

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

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertModel.from_pretrained("google/rembert")

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

>>> last_hidden_states = outputs.last_hidden_state

TFRemBertForMaskedLM

class transformers.TFRemBertForMaskedLM

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

RemBERT 模型,顶部带有 language modeling (语言建模) head。

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: 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]Dict[str, np.ndarray],且每个示例必须具有形状 (batch_size, sequence_length)) — 输入序列 token 在词汇表中的索引。

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入 ID?

  • attention_mask (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length)可选) — 用于避免对 padding token 索引执行注意力的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 token 不被掩盖
    • 0 表示 token 被掩盖

    什么是注意力掩码?

  • token_type_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length)可选) — 段落 token 索引,用于指示输入的第一个和第二个部分。索引在 [0, 1] 中选择:

    • 0 对应于 句子 A token,
    • 1 对应于 句子 B token。

    什么是 token 类型 ID?

  • position_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length)可选) — 每个输入序列 token 在位置嵌入中的位置索引。在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是位置 ID?

  • head_mask (np.ndarraytf.Tensor,形状为 (num_heads,)(num_layers, num_heads)可选) — 用于置空自注意力模块中选定 head 的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head 不被掩盖
    • 0 表示 head 被掩盖
  • inputs_embeds (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length, hidden_size)可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 更多细节请查看返回张量下的 hidden_states。 此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯粹的元组。 此参数可以在 eager 模式下使用,在 graph 模式下,该值将始终设置为 True。
  • training (bool, optional, defaults to `False“) — 是否在训练模式下使用模型(某些模块如 dropout 模块在训练和评估之间有不同的行为)。
  • labels (tf.Tensor or np.ndarray of shape (batch_size, sequence_length), optional) — 用于计算 masked language modeling loss 的标签。 索引应该在 [-100, 0, ..., config.vocab_size] 中(参见 input_ids 文档字符串)。 索引设置为 -100 的 tokens 将被忽略(masked),loss 仅针对标签在 [0, ..., config.vocab_size] 中的 tokens 计算。

返回:

transformers.modeling_tf_outputs.TFMaskedLMOutputtuple(tf.Tensor)

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

  • loss (tf.Tensor of shape (n,), optional, 当提供了 labels 时返回,其中 n 是非 masked 标签的数量) — Masked language modeling (MLM) loss。

  • logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — 语言模型头的预测分数(SoftMax 之前的每个词汇表 token 的分数)。

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

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

TFRemBertForMaskedLM forward 方法,覆盖了 __call__ 特殊方法。

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

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertForMaskedLM.from_pretrained("google/rembert")

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

TFRemBertForCausalLM

class transformers.TFRemBertForCausalLM

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

RemBERT 模型,顶部带有 language modeling 头,用于 CLM 微调。

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None encoder_hidden_states: np.ndarray | tf.Tensor | None = None encoder_attention_mask: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None use_cache: 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: Optional[bool] = False ) transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentionstuple(tf.Tensor)

返回:

transformers.modeling_tf_outputs.TFCausalLMOutputWithCrossAttentionstuple(tf.Tensor)

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

  • loss (tf.Tensor of shape (n,), optional, 当提供了 labels 时返回,其中 n 是非 masked 标签的数量) — 语言模型 loss (用于预测下一个 token)。

  • logits (tf.Tensor of shape (batch_size, sequence_length, config.vocab_size)) — 语言模型头的预测分数(SoftMax 之前的每个词汇表 token 的分数)。

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

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

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

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • past_key_values (List[tf.Tensor]可选,当传递 use_cache=Trueconfig.use_cache=True 时返回) — tf.Tensor 的列表,长度为 config.n_layers,每个张量的形状为 (2, batch_size, num_heads, sequence_length, embed_size_per_head))。

    包含预先计算的隐藏状态(注意力块中的键和值),可以用于(请参阅 past_key_values 输入)加速顺序解码。

encoder_hidden_states (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional): 编码器最后一层的输出的隐藏状态序列。 如果模型配置为解码器,则在 cross-attention 中使用。 encoder_attention_mask (tf.Tensor of shape (batch_size, sequence_length), optional): 用于避免对编码器输入的 padding token 索引执行 attention 的 Mask。 如果模型配置为解码器,则此 mask 在 cross-attention 中使用。 Mask 值在 [0, 1] 中选择

  • 1 表示 tokens 未被 masked
  • 0 表示 tokens 被 masked

past_key_values (Tuple[Tuple[tf.Tensor]] of length config.n_layers) 包含 attention blocks 的预计算的 key 和 value 隐藏状态。 可用于加速解码。 如果使用 past_key_values,用户可以选择仅输入最后一次的 decoder_input_ids (那些没有将其过去的 key value 状态提供给此模型的),形状为 (batch_size, 1),而不是所有形状为 (batch_size, sequence_length)decoder_input_ids。 use_cache (bool, optional, defaults to True): 如果设置为 True,则返回 past_key_values key value 状态,并且可以用于加速解码(参见 past_key_values)。 在训练期间设置为 False,在生成期间设置为 True。 labels (tf.Tensornp.ndarray of shape (batch_size, sequence_length), optional): 用于计算交叉熵分类 loss 的标签。 索引应该在 [0, ..., config.vocab_size - 1] 中。

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertForCausalLM.from_pretrained("google/rembert")

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

TFRemBertForSequenceClassification

class transformers.TFRemBertForSequenceClassification

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

RemBERT 模型 transformer,顶部带有序列分类/回归头,例如,用于 GLUE 任务。

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: 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]Dict[str, np.ndarray] 并且每个示例都必须具有形状 (batch_size, sequence_length)) — 词汇表中输入序列 tokens 的索引。

    索引可以使用 AutoTokenizer 获得。 参见 PreTrainedTokenizer.call()PreTrainedTokenizer.encode() 获取详细信息。

    什么是输入 IDs?

  • attention_mask (np.ndarraytf.Tensor of shape (batch_size, sequence_length), optional) — Mask,用于避免在 padding token 索引上执行 attention。 Mask 值在 [0, 1] 中选择:

    • 1 表示 tokens 未被 masked
    • 0 表示 tokens 被 masked

    什么是 attention masks?

  • token_type_ids (np.ndarraytf.Tensor of shape (batch_size, sequence_length), optional) — Segment token 索引,用于指示输入的第一部分和第二部分。 索引在 [0, 1] 中选择:

    • 0 对应于 sentence A token,
    • 1 对应于 sentence B token。

    什么是 token type IDs?

  • position_ids (np.ndarraytf.Tensor of shape (batch_size, sequence_length), optional) — 每个输入序列 tokens 在位置 embeddings 中的位置索引。 在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (np.ndarraytf.Tensor of shape (num_heads,)(num_layers, num_heads), optional) — 用于 nullify self-attention 模块的选定 heads 的 Mask。 Mask 值在 [0, 1] 中选择:

    • 1 表示 head 未被 masked
    • 0 表示 head 被 masked
  • inputs_embeds (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。
  • training (bool, 可选, 默认为 `False`) — 是否在训练模式下使用模型(某些模块,如 dropout 模块,在训练和评估之间有不同的行为)。
  • 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 时),包含各种元素,具体取决于配置 (RemBertConfig) 和输入。

  • 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=Trueconfig.output_hidden_states=True 时返回) — tf.Tensor 的元组(embeddings 的输出一个,每层的输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

TFRemBertForSequenceClassification 前向传播方法,覆盖了 __call__ 特殊方法。

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

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertForSequenceClassification.from_pretrained("google/rembert")

>>> 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 = TFRemBertForSequenceClassification.from_pretrained("google/rembert", num_labels=num_labels)

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

TFRemBertForMultipleChoice

class transformers.TFRemBertForMultipleChoice

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

RemBERT 模型,顶部带有单项选择分类头(池化输出顶部的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: 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.TFMultipleChoiceModelOutputtuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor]Dict[str, np.ndarray],并且每个示例必须具有形状 (batch_size, num_choices, sequence_length)) — 词汇表中输入序列标记的索引。

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入 IDs?

  • attention_mask (np.ndarraytf.Tensor,形状为 (batch_size, num_choices, sequence_length)可选) — 用于避免对填充标记索引执行注意力的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示**未被掩码**的标记,
    • 0 表示**被掩码**的标记。

    什么是注意力掩码?

  • token_type_ids (np.ndarraytf.Tensor,形状为 (batch_size, num_choices, sequence_length)可选) — 分段标记索引,用于指示输入的第一个和第二个部分。索引在 [0, 1] 中选择:

    • 0 对应于 *句子 A* 标记,
    • 1 对应于 *句子 B* 标记。

    什么是标记类型 IDs?

  • position_ids (np.ndarraytf.Tensor,形状为 (batch_size, num_choices, sequence_length)可选) — 每个输入序列标记在位置嵌入中的位置索引。在 [0, config.max_position_embeddings - 1] 范围内选择。

    什么是位置 IDs?

  • head_mask (np.ndarraytf.Tensor,形状为 (num_heads,)(num_layers, num_heads)可选) — 用于使自注意力模块的选定 head 失效的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示 head **未被掩码**,
    • 0 表示 head **被掩码**。
  • inputs_embeds (np.ndarraytf.Tensor,形状为 (batch_size, num_choices, sequence_length, hidden_size)可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量下的 attentions。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。
  • training (bool, 可选, 默认为 `False`) — 是否在训练模式下使用模型(某些模块,如 dropout 模块,在训练和评估之间有不同的行为)。
  • labels (tf.Tensornp.ndarray,形状为 (batch_size,)可选) — 用于计算多项选择分类损失的标签。索引应在 [0, ..., num_choices] 中,其中 num_choices 是输入张量第二维的大小。(请参阅上面的 `input_ids`)

返回:

transformers.modeling_tf_outputs.TFMultipleChoiceModelOutputtuple(tf.Tensor)

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

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

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

    分类得分(在 SoftMax 之前)。

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

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

TFRemBertForMultipleChoice 前向传播方法,覆盖了 __call__ 特殊方法。

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

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertForMultipleChoice.from_pretrained("google/rembert")

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

TFRemBertForTokenClassification

class transformers.TFRemBertForTokenClassification

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

RemBERT 模型,顶部带有一个 token 分类 head(隐藏状态输出顶部的线性层),例如,用于命名实体识别 (NER) 任务。

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: 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.TFTokenClassifierOutput or tuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor] or Dict[str, np.ndarray] 并且每个示例必须具有形状 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入 IDs?

  • attention_mask (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length), 可选) — 用于避免在 padding 标记索引上执行 attention 的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是 attention masks?

  • token_type_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length), 可选) — 分段标记索引,用于指示输入的第一部分和第二部分。索引在 [0, 1] 中选择:

    • 0 对应于 句子 A 标记,
    • 1 对应于 句子 B 标记。

    什么是 token type IDs?

  • position_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length), 可选) — 位置嵌入中每个输入序列标记的位置索引。在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (np.ndarraytf.Tensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于 nullify self-attention 模块中选定头的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示头未被掩码
    • 0 表示头被掩码
  • inputs_embeds (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想要比模型的内部嵌入查找矩阵更好地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attentions 张量。 有关更多详细信息,请参阅返回张量下的 attentions。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回张量下的 hidden_states。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。
  • training (bool, 可选, 默认为 `False`) — 是否在训练模式下使用模型(某些模块(如 dropout 模块)在训练和评估之间具有不同的行为)。
  • labels (tf.Tensornp.ndarray,形状为 (batch_size, sequence_length), 可选) — 用于计算 token 分类损失的标签。索引应在 [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 时),包含各种元素,具体取决于配置 (RemBertConfig) 和输入。

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

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

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

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

TFRemBertForTokenClassification 前向方法,覆盖了 __call__ 特殊方法。

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

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertForTokenClassification.from_pretrained("google/rembert")

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

TFRemBertForQuestionAnswering

class transformers.TFRemBertForQuestionAnswering

< >

( config: RemBertConfig *inputs **kwargs )

参数

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

RemBERT 模型,顶部带有跨度分类头,用于执行抽取式问答任务,如 SQuAD(在 hidden-states 输出之上使用线性层来计算 span start logitsspan end logits)。

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

此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参考 TF 2.0 文档,了解与常规用法和行为相关的所有事项。

transformers 中的 TensorFlow 模型和层接受两种输入格式

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

支持第二种格式的原因是 Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用 model.fit() 等方法时,事情应该“正常工作” - 只需以 model.fit() 支持的任何格式传递输入和标签即可!但是,如果您想在 Keras 方法(如 fit()predict())之外使用第二种格式,例如在使用 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 函数一样传递输入!

call

< >

( 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 head_mask: 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.TFQuestionAnsweringModelOutput or tuple(tf.Tensor)

参数

  • input_ids (np.ndarray, tf.Tensor, List[tf.Tensor] `Dict[str, tf.Tensor]Dict[str, np.ndarray] 并且每个示例必须具有形状 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入 IDs?

  • attention_mask (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length), 可选) — 用于避免在 padding 标记索引上执行 attention 的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是 attention masks?

  • token_type_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length), 可选) — 分段标记索引,用于指示输入的第一部分和第二部分。索引在 [0, 1] 中选择:

    • 0 对应于 句子 A 标记,
    • 1 对应于 句子 B 标记。

    什么是 token type IDs?

  • position_ids (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length), 可选) — 位置嵌入中每个输入序列标记的位置索引。在范围 [0, config.max_position_embeddings - 1] 中选择。

    什么是 position IDs?

  • head_mask (np.ndarraytf.Tensor,形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于 nullify self-attention 模块中选定头的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示头未被掩码
    • 0 表示头被掩码
  • inputs_embeds (np.ndarraytf.Tensor,形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为相关的向量,这将非常有用。
  • output_attentions (bool, *可选*) — 是否返回所有注意力层的注意力张量。 更多细节请参阅返回张量下的 attentions。 此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • output_hidden_states (bool, *可选*) — 是否返回所有层的隐藏状态。 更多细节请参阅返回张量下的 hidden_states。 此参数只能在 eager 模式下使用,在 graph 模式下将使用配置中的值。
  • return_dict (bool, *可选*) — 是否返回一个 ModelOutput 而不是一个普通的元组。 此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。
  • training (bool, *可选*, 默认为 False) — 是否在训练模式下使用模型(诸如 dropout 模块之类的一些模块在训练和评估之间具有不同的行为)。
  • start_positions (tf.Tensornp.ndarray,形状为 (batch_size,), *可选*) — 用于计算 token 分类损失的已标记跨度起点的标签位置(索引)。 位置被限制在序列的长度 (sequence_length) 内。 序列之外的位置不计入损失计算。
  • end_positions (tf.Tensornp.ndarray,形状为 (batch_size,), *可选*) — 用于计算 token 分类损失的已标记跨度终点的标签位置(索引)。 位置被限制在序列的长度 (sequence_length) 内。 序列之外的位置不计入损失计算。

返回:

transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutputtuple(tf.Tensor)

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

  • 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=Trueconfig.output_hidden_states=True 时返回) — tf.Tensor 的元组(embeddings 的输出一个,每层的输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出以及初始 embedding 输出处的隐藏状态。

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

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

The TFRemBertForQuestionAnswering 的 forward 方法重写了 __call__ 特殊方法。

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

示例

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

>>> tokenizer = AutoTokenizer.from_pretrained("google/rembert")
>>> model = TFRemBertForQuestionAnswering.from_pretrained("google/rembert")

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