Transformers 文档

SqueezeBERT

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

SqueezeBERT

概述

SqueezeBERT 模型在SqueezeBERT: 计算机视觉可以教 NLP 关于高效神经网络什么? 中提出,作者是 Forrest N. Iandola、Albert E. Shaw、Ravi Krishna、Kurt W. Keutzer。它是一个类似于 BERT 模型的双向 Transformer。BERT 架构和 SqueezeBERT 架构之间的主要区别在于,SqueezeBERT 对 Q、K、V 和 FFN 层使用分组卷积,而不是全连接层。

论文的摘要如下

人类每天阅读和撰写数千亿条消息。此外,由于大型数据集、大型计算系统和更好的神经网络模型的可用性,自然语言处理 (NLP) 技术在理解、校对和组织这些消息方面取得了重大进展。因此,在无数应用中部署 NLP 以帮助网络用户、社交网络和企业存在重大机遇。特别是,我们将智能手机和其他移动设备视为大规模部署 NLP 模型的关键平台。然而,当今高度精确的 NLP 神经网络模型(如 BERT 和 RoBERTa)的计算成本极高,BERT-base 在 Pixel 3 智能手机上对文本片段进行分类需要 1.7 秒。在这项工作中,我们观察到诸如分组卷积之类的方法已为计算机视觉网络带来了显着的加速,但许多这些技术尚未被 NLP 神经网络设计人员采用。我们演示了如何用分组卷积替换自注意力层中的几个操作,并在一种名为 SqueezeBERT 的新型网络架构中使用了这项技术,该架构在 Pixel 3 上的运行速度比 BERT-base 快 4.3 倍,同时在 GLUE 测试集上实现了具有竞争力的准确率。SqueezeBERT 代码将被发布。

此模型由forresti贡献。

使用技巧

  • SqueezeBERT 是一个具有绝对位置嵌入的模型,因此通常建议在右侧而不是左侧填充输入。
  • SqueezeBERT 类似于 BERT,因此依赖于掩码语言建模 (MLM) 目标。因此,它在预测掩码标记和 NLU 方面很有效,但对于文本生成来说不是最佳选择。使用因果语言建模 (CLM) 目标训练的模型在这方面更好。
  • 为了在序列分类任务上进行微调时获得最佳结果,建议从 squeezebert/squeezebert-mnli-headless 检查点开始。

资源

SqueezeBertConfig

class transformers.SqueezeBertConfig

< >

( vocab_size = 30522 hidden_size = 768 num_hidden_layers = 12 num_attention_heads = 12 intermediate_size = 3072 hidden_act = 'gelu' hidden_dropout_prob = 0.1 attention_probs_dropout_prob = 0.1 max_position_embeddings = 512 type_vocab_size = 2 initializer_range = 0.02 layer_norm_eps = 1e-12 pad_token_id = 0 embedding_size = 768 q_groups = 4 k_groups = 4 v_groups = 4 post_attention_groups = 1 intermediate_groups = 4 output_groups = 4 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 30522) — SqueezeBERT 模型的词汇表大小。定义了在调用 SqueezeBertModel 时,可以通过 inputs_ids 传递的不同 tokens 的数量。
  • hidden_size (int, 可选, 默认为 768) — 编码器层和池化层的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数。
  • intermediate_size (int, 可选, 默认为 3072) — Transformer 编码器中“中间”层(通常称为前馈层)的维度。
  • hidden_act (strCallable, 可选, 默认为 "gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu", "relu", "silu""gelu_new"
  • hidden_dropout_prob (float, 可选, 默认为 0.1) — embeddings, 编码器和池化器中所有全连接层的 dropout 概率。
  • attention_probs_dropout_prob (float, 可选, 默认为 0.1) — 注意力概率的 dropout 比率。
  • max_position_embeddings (int, 可选, 默认为 512) — 此模型可能使用的最大序列长度。通常设置为较大的值以防万一(例如,512 或 1024 或 2048)。
  • type_vocab_size (int, 可选, 默认为 2) — 调用 BertModelTFBertModel 时,可以通过 token_type_ids 传递的词汇表大小。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • layer_norm_eps (float, 可选, 默认为 1e-12) —
  • pad_token_id (int, 可选, 默认为 0) — 在词嵌入中用作填充的 token 的 ID。
  • embedding_size (int, 可选, 默认为 768) — 词嵌入向量的维度。
  • q_groups (int, 可选, 默认为 4) — Q 层中的组数。
  • k_groups (int, 可选, 默认为 4) — K 层中的组数。
  • v_groups (int, 可选, 默认为 4) — V 层中的组数。
  • post_attention_groups (int, 可选, 默认为 1) — 第一个前馈网络层中的组数。
  • intermediate_groups (int, 可选, 默认为 4) — 第二个前馈网络层中的组数。
  • output_groups (int, 可选, 默认为 4) — 第三个前馈网络层中的组数。

这是用于存储 SqueezeBertModel 配置的配置类。它用于根据指定的参数实例化 SqueezeBERT 模型,从而定义模型架构。使用默认值实例化配置将产生与 SqueezeBERT squeezebert/squeezebert-uncased 架构类似的配置。

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

示例

>>> from transformers import SqueezeBertConfig, SqueezeBertModel

>>> # Initializing a SqueezeBERT configuration
>>> configuration = SqueezeBertConfig()

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

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

SqueezeBertTokenizer

class transformers.SqueezeBertTokenizer

< >

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

参数

  • vocab_file (str) — 包含词汇表的文件。
  • do_lower_case (bool, 可选, 默认为 True) — 是否在 tokenizing 时将输入转换为小写。
  • do_basic_tokenize (bool, 可选, 默认为 True) — 是否在 WordPiece 之前进行基本 tokenization。
  • never_split (Iterable, 可选) — 在 tokenization 期间永远不会被分割的 tokens 集合。仅当 do_basic_tokenize=True 时有效
  • unk_token (str, 可选, 默认为 "[UNK]") — 未知 token。词汇表中不存在的 token 无法转换为 ID,而是设置为此 token。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符 token,用于从多个序列构建一个序列时,例如用于序列分类的两个序列,或者用于问答的文本和问题。它也用作使用特殊 token 构建的序列的最后一个 token。
  • pad_token (str, optional, defaults to "[PAD]") — 填充 token,例如在批量处理不同长度的序列时使用。
  • cls_token (str, optional, defaults to "[CLS]") — 分类器 token,用于进行序列分类(对整个序列而不是每个 token 进行分类)。当使用特殊 token 构建序列时,它是序列的第一个 token。
  • mask_token (str, optional, defaults to "[MASK]") — 掩码 token,用于掩盖值。这是使用掩码语言建模训练此模型时使用的 token。这是模型将尝试预测的 token。
  • tokenize_chinese_chars (bool, optional, defaults to True) — 是否对中文字符进行 token 化。

    对于日语,可能应该停用此功能(参见此 issue)。

  • strip_accents (bool, optional) — 是否去除所有重音符号。如果未指定此选项,则将由 lowercase 的值确定(与原始 SqueezeBERT 中一样)。
  • clean_up_tokenization_spaces (bool, optional, defaults to True) — 是否在解码后清理空格,清理包括删除潜在的伪像,如多余的空格。

构建 SqueezeBERT tokenizer。基于 WordPiece。

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

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) — 用于序列对的可选的第二个 ID 列表。

返回值

List[int]

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

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

  • 单个序列:[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) — token 列表是否已使用模型的特殊 token 格式化。

返回值

List[int]

一个整数列表,范围为 [0, 1]:1 表示特殊 token,0 表示序列 token。

从没有添加特殊 token 的 token 列表中检索序列 ID。当使用 tokenizer 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) — 用于序列对的可选的第二个 ID 列表。

返回值

List[int]

根据给定的序列,token 类型 ID 列表。

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

对掩码具有以下格式

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 )

SqueezeBertTokenizerFast

class transformers.SqueezeBertTokenizerFast

< >

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

参数

  • vocab_file (str) — 包含词汇表的文件。
  • do_lower_case (bool, optional, defaults to True) — 是否在 token 化时将输入转换为小写。
  • unk_token (str, optional, defaults to "[UNK]") — 未知 token。词汇表中没有的 token 无法转换为 ID,而是设置为此 token。
  • sep_token (str, optional, defaults to "[SEP]") — 分隔符 token,用于从多个序列构建一个序列时,例如用于序列分类的两个序列,或者用于问答的文本和问题。它也用作使用特殊 token 构建的序列的最后一个 token。
  • pad_token (str, optional, defaults to "[PAD]") — 填充 token,例如在批量处理不同长度的序列时使用。
  • cls_token (str, optional, defaults to "[CLS]") — 分类器 token,用于进行序列分类(对整个序列而不是每个 token 进行分类)。当使用特殊 token 构建序列时,它是序列的第一个 token。
  • mask_token (str, optional, defaults to "[MASK]") — 掩码 token,用于掩盖值。这是使用掩码语言建模训练此模型时使用的 token。这是模型将尝试预测的 token。
  • clean_text (bool, optional, defaults to True) — 是否在 token 化之前清理文本,方法是删除任何控制字符并将所有空格替换为经典空格。
  • tokenize_chinese_chars (bool, 可选, 默认为 True) — 是否对中文字符进行分词。 对于日语,可能应该停用此功能(参见 此问题)。
  • strip_accents (bool, 可选) — 是否去除所有重音符号。 如果未指定此选项,则将由 lowercase 的值决定(与原始 SqueezeBERT 中相同)。
  • wordpieces_prefix (str, 可选, 默认为 "##") — 子词的前缀。

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

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

build_inputs_with_special_tokens

< >

( token_ids_0 token_ids_1 = None ) List[int]

参数

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

返回值

List[int]

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

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

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

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], 可选) — 序列对的可选的第二个 ID 列表。

返回值

List[int]

根据给定的序列,token 类型 ID 列表。

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

对掩码具有以下格式

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

SqueezeBertModel

class transformers.SqueezeBertModel

< >

( config )

参数

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

裸 SqueezeBERT 模型 Transformer 输出原始隐藏状态,顶部没有任何特定的 head。

SqueezeBERT 模型在 SqueezeBERT: What can computer vision teach NLP about efficient neural networks? 中提出,作者是 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, 和 Kurt W. Keutzer

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

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

为了在文本分类任务上获得微调 SqueezeBERT 的最佳结果,建议使用 squeezebert/squeezebert-mnli-headless checkpoint 作为起点。

层次结构

Internal class hierarchy:
SqueezeBertModel
    SqueezeBertEncoder
        SqueezeBertModule
        SqueezeBertSelfAttention
            ConvActivation
            ConvDropoutLayerNorm

数据布局

Input data is in [batch, sequence_length, hidden_size] format.

Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

The final output of the encoder is in [batch, sequence_length, hidden_size] format.

forward

< >

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

参数

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

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

    什么是输入 ID?

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

    • 1 表示 未被掩码 的 token,
    • 0 表示 被掩码 的 token。

    什么是 attention 掩码?

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

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

    什么是 token 类型 ID?

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

    什么是位置 ID?

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

    • 1 表示 head 未被掩码
    • 0 表示 head 被掩码
  • 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 而不是普通元组。

返回值

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

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

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

  • pooler_output (形状为 (batch_size, hidden_size)torch.FloatTensor) — 序列的第一个 token(分类 token)的最后一层隐藏状态,在通过用于辅助预训练任务的层进一步处理后获得。 例如,对于 BERT 系列模型,这将返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重通过预训练期间的下一句预测(分类)目标进行训练。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (如果模型有嵌入层,则为嵌入层的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

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

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

示例

>>> from transformers import AutoTokenizer, SqueezeBertModel
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertModel.from_pretrained("squeezebert/squeezebert-uncased")

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

>>> last_hidden_states = outputs.last_hidden_state

SqueezeBertForMaskedLM

class transformers.SqueezeBertForMaskedLM

< >

( config )

参数

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

带有 language modeling 头部的 SqueezeBERT 模型。

SqueezeBERT 模型在 SqueezeBERT: What can computer vision teach NLP about efficient neural networks? 中提出,作者是 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, 和 Kurt W. Keutzer

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

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

为了在文本分类任务上获得微调 SqueezeBERT 的最佳结果,建议使用 squeezebert/squeezebert-mnli-headless checkpoint 作为起点。

层次结构

Internal class hierarchy:
SqueezeBertModel
    SqueezeBertEncoder
        SqueezeBertModule
        SqueezeBertSelfAttention
            ConvActivation
            ConvDropoutLayerNorm

数据布局

Input data is in [batch, sequence_length, hidden_size] format.

Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

The final output of the encoder is in [batch, sequence_length, hidden_size] format.

forward

< >

( input_ids: Optional = 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.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), 可选) — 用于避免在 padding 标记索引上执行注意力的掩码。 掩码值在 [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), 可选) — 用于 nullify 自注意力模块的选定头的掩码。 掩码值在 [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 时),其中包含各种元素,具体取决于配置 (SqueezeBertConfig) 和输入。

  • 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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (如果模型有嵌入层,则为嵌入层的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

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

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

示例

>>> from transformers import AutoTokenizer, SqueezeBertForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertForMaskedLM.from_pretrained("squeezebert/squeezebert-uncased")

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

SqueezeBertForSequenceClassification

class transformers.SqueezeBertForSequenceClassification

< >

( config )

参数

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

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

SqueezeBERT 模型在 SqueezeBERT: What can computer vision teach NLP about efficient neural networks? 中提出,作者是 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, 和 Kurt W. Keutzer

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

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

为了在文本分类任务上获得微调 SqueezeBERT 的最佳结果,建议使用 squeezebert/squeezebert-mnli-headless checkpoint 作为起点。

层次结构

Internal class hierarchy:
SqueezeBertModel
    SqueezeBertEncoder
        SqueezeBertModule
        SqueezeBertSelfAttention
            ConvActivation
            ConvDropoutLayerNorm

数据布局

Input data is in [batch, sequence_length, hidden_size] format.

Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

The final output of the encoder is in [batch, sequence_length, hidden_size] format.

forward

< >

( input_ids: Optional = 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.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length), 可选) — 用于避免在 padding 标记索引上执行注意力的掩码。 掩码值在 [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), 可选) — 用于屏蔽自注意力模块中选定 attention heads 的掩码。 掩码值应在 [0, 1] 中选择:

    • 1 表示 attention head 不被屏蔽
    • 0 表示 attention head 被屏蔽
  • 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,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [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 时),其中包含各种元素,具体取决于配置 (SqueezeBertConfig) 和输入。

  • 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=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (如果模型有嵌入层,则为嵌入层的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

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

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

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, SqueezeBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-uncased")

>>> 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 = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-uncased", num_labels=num_labels)

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

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, SqueezeBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-uncased", 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 = SqueezeBertForSequenceClassification.from_pretrained(
...     "squeezebert/squeezebert-uncased", 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

SqueezeBertForMultipleChoice

class transformers.SqueezeBertForMultipleChoice

< >

( config )

参数

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

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

SqueezeBERT 模型在 SqueezeBERT: What can computer vision teach NLP about efficient neural networks? 中提出,作者是 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, 和 Kurt W. Keutzer

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

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

为了在文本分类任务上获得微调 SqueezeBERT 的最佳结果,建议使用 squeezebert/squeezebert-mnli-headless checkpoint 作为起点。

层次结构

Internal class hierarchy:
SqueezeBertModel
    SqueezeBertEncoder
        SqueezeBertModule
        SqueezeBertSelfAttention
            ConvActivation
            ConvDropoutLayerNorm

数据布局

Input data is in [batch, sequence_length, hidden_size] format.

Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

The final output of the encoder is in [batch, sequence_length, hidden_size] format.

forward

< >

( input_ids: Optional = 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.MultipleChoiceModelOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 IDs?

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

    • 1 表示 tokens 不被掩蔽
    • 0 表示 tokens 被掩蔽

    什么是 attention 掩码?

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

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

    什么是 token 类型 IDs?

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

    什么是位置 IDs?

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

    • 1 表示 attention head 不被屏蔽
    • 0 表示 attention head 被屏蔽
  • inputs_embeds (torch.FloatTensor, 形状为 (batch_size, num_choices, 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,), 可选) — 用于计算多项选择分类损失的标签。索引应在 [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 时),其中包含各种元素,具体取决于配置 (SqueezeBertConfig) 和输入。

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

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

    分类得分(在 SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (如果模型有嵌入层,则为嵌入层的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

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

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

示例

>>> from transformers import AutoTokenizer, SqueezeBertForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertForMultipleChoice.from_pretrained("squeezebert/squeezebert-uncased")

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

SqueezeBertForTokenClassification

class transformers.SqueezeBertForTokenClassification

< >

( config )

参数

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

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

SqueezeBERT 模型在 SqueezeBERT: What can computer vision teach NLP about efficient neural networks? 中提出,作者是 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, 和 Kurt W. Keutzer

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

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

为了在文本分类任务上获得微调 SqueezeBERT 的最佳结果,建议使用 squeezebert/squeezebert-mnli-headless checkpoint 作为起点。

层次结构

Internal class hierarchy:
SqueezeBertModel
    SqueezeBertEncoder
        SqueezeBertModule
        SqueezeBertSelfAttention
            ConvActivation
            ConvDropoutLayerNorm

数据布局

Input data is in [batch, sequence_length, hidden_size] format.

Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

The final output of the encoder is in [batch, sequence_length, hidden_size] format.

forward

< >

( input_ids: Optional = 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)) — 词汇表中输入序列 token 的索引。

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

    什么是输入 ID?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — 用于避免在 padding 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 类型 ID?

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

    什么是位置 ID?

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

    • 1 表示 head 未被掩码
    • 0 表示 head 已被掩码
  • 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)可选) — 用于计算 token 分类损失的标签。 索引应为 [0, ..., config.num_labels - 1]

返回值

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

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

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (如果模型有嵌入层,则为嵌入层的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

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

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

示例

>>> from transformers import AutoTokenizer, SqueezeBertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertForTokenClassification.from_pretrained("squeezebert/squeezebert-uncased")

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

SqueezeBertForQuestionAnswering

class transformers.SqueezeBertForQuestionAnswering

< >

( config )

参数

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

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

SqueezeBERT 模型在 SqueezeBERT: What can computer vision teach NLP about efficient neural networks? 中提出,作者是 Forrest N. Iandola, Albert E. Shaw, Ravi Krishna, 和 Kurt W. Keutzer

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

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

为了在文本分类任务上获得微调 SqueezeBERT 的最佳结果,建议使用 squeezebert/squeezebert-mnli-headless checkpoint 作为起点。

层次结构

Internal class hierarchy:
SqueezeBertModel
    SqueezeBertEncoder
        SqueezeBertModule
        SqueezeBertSelfAttention
            ConvActivation
            ConvDropoutLayerNorm

数据布局

Input data is in [batch, sequence_length, hidden_size] format.

Data inside the encoder is in [batch, hidden_size, sequence_length] format. But, if `output_hidden_states == True`, the data from inside the encoder is returned in [batch, sequence_length, hidden_size] format.

The final output of the encoder is in [batch, sequence_length, hidden_size] format.

forward

< >

( input_ids: Optional = 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.QuestionAnsweringModelOutputtuple(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)可选) — 用于避免在 padding 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 类型 ID?

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

    什么是位置 ID?

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

    • 1 表示 head 不被掩盖
    • 0 表示 head 被掩盖
  • 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 而不是纯粹的元组。
  • start_positions (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算 token 分类损失的带标签 span 起始位置(索引)的标签。 位置被限制在序列的长度(sequence_length)内。 序列之外的位置不计入损失计算。
  • end_positions (torch.LongTensor,形状为 (batch_size,)可选) — 用于计算 token 分类损失的带标签 span 结束位置(索引)的标签。 位置被限制在序列的长度(sequence_length)内。 序列之外的位置不计入损失计算。

返回值

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

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

  • start_logits (torch.FloatTensor,形状为 (batch_size, sequence_length)) — Span-start 得分(SoftMax 之前)。

  • end_logits (torch.FloatTensor,形状为 (batch_size, sequence_length)) — Span-end 得分(SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回) — torch.FloatTensor 的元组 (如果模型有嵌入层,则为嵌入层的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

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

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

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

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

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

示例

>>> from transformers import AutoTokenizer, SqueezeBertForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("squeezebert/squeezebert-uncased")
>>> model = SqueezeBertForQuestionAnswering.from_pretrained("squeezebert/squeezebert-uncased")

>>> 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
< > 在 GitHub 上更新