Transformers 文档

SqueezeBERT

Hugging Face's logo
加入 Hugging Face 社区

并获取增强的文档体验

开始使用

SqueezeBERT

PyTorch

概述

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 可以表示的不同标记的数量。
  • 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) — 嵌入层、编码器和池化器中所有全连接层的 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) — 词嵌入中用作填充的标记的 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, optional, defaults to True) — 是否在分词时将输入转换为小写。
  • do_basic_tokenize (bool, optional, defaults to True) — 是否在 WordPiece 分词之前进行基础分词。
  • never_split (Iterable, optional) — 在分词期间永远不会被分割的标记集合。仅在 do_basic_tokenize=True 时生效。
  • 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]") — 用于掩码值的标记。这是使用掩码语言建模训练此模型时使用的标记。这是模型将尝试预测的标记。
  • tokenize_chinese_chars (bool, optional, defaults to True) — 是否对中文字符进行分词。

    对于日语,这可能应该被停用(参见此问题)。

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

构建 SqueezeBERT 分词器。基于 WordPiece。

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

build_inputs_with_special_tokens

< >

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

参数

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

返回值

List[int]

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

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

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

get_special_tokens_mask

< >

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

参数

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

返回值

List[int]

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

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

create_token_type_ids_from_sequences

< >

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

参数

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

返回值

List[int]

根据给定序列列出的 token type IDs

创建一个由传递的两个序列生成的掩码,用于序列对分类任务。一个 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: typing.Optional[str] = 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) — 是否在分词时将输入转换为小写。
  • 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) — 是否在分词之前清理文本,方法是删除任何控制字符并将所有空格替换为经典空格。
  • tokenize_chinese_chars (bool, optional, defaults to True) — 是否对中文汉字进行分词。对于日语,这可能应该被停用(请参阅 此问题)。
  • strip_accents (bool, optional) — 是否去除所有重音符号。如果未指定此选项,则将由 lowercase 的值确定(与原始 SqueezeBERT 中一样)。
  • wordpieces_prefix (str, optional, defaults to "##") — 子词的前缀。

构建一个“快速” 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], optional) — 用于序列对的可选的第二个 ID 列表。

返回值

List[int]

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

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

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

create_token_type_ids_from_sequences

< >

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

参数

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

返回值

List[int]

根据给定序列列出的 token type IDs

创建一个由传递的两个序列生成的掩码,用于序列对分类任务。一个 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 Module,并参阅 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: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(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), 可选) — 用于避免在 padding token 索引上执行 attention 的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 tokens 未被掩码
    • 0 表示 tokens 已被掩码

    什么是 attention 掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — Segment 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), 可选) — 用于 nullify 自注意力模块的选定 head 的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩码
    • 0 表示 head 已被掩码
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size), 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回的 tensors 下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是普通的 tuple。

返回值

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

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

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

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

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

    模型在每层输出处的 Hidden-states 加上可选的初始嵌入输出。

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

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

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

尽管 forward pass 的配方需要在该函数内定义,但应该在此之后调用 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 head 的 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 Module,并参阅 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: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 IDs?

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

    • 1 表示 tokens 未被掩码
    • 0 表示 tokens 已被掩码

    什么是 attention 掩码?

  • token_type_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — Segment 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), 可选) — 用于 nullify 自注意力模块的选定 head 的掩码。 掩码值在 [0, 1] 中选择:

    • 1 表示 head 未被掩码
    • 0 表示 head 已被掩码
  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size), 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递 input_ids。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这将非常有用。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回的 tensors 下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的 hidden_states
  • return_dict (bool, optional) — 是否返回 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.MaskedLMOutput 或一个 torch.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=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型具有嵌入层,则为嵌入的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的 Hidden-states 加上可选的初始嵌入输出。

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

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

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

尽管 forward pass 的配方需要在该函数内定义,但应该在此之后调用 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 模型转换器,顶部带有序列分类/回归头(池化输出顶部的线性层),例如用于 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 Module,并参阅 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: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (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,)可选) — 用于计算序列分类/回归损失的标签。索引应在 [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=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型具有嵌入层,则为嵌入的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的 Hidden-states 加上可选的初始嵌入输出。

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

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

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

尽管 forward pass 的配方需要在该函数内定义,但应该在此之后调用 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 Module,并参阅 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: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

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

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

    什么是注意力掩码?

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

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

    什么是标记类型 ID?

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

    什么是位置 IDs?

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

    • 1 表示头不被 Mask
    • 0 表示头被 Mask
  • 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=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型具有嵌入层,则为嵌入的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的 Hidden-states 加上可选的初始嵌入输出。

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

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

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

尽管 forward pass 的配方需要在该函数内定义,但应该在此之后调用 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() 方法来加载模型权重。

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

参数

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

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

    什么是输入 IDs?

  • attention_mask (torch.FloatTensor,形状为 (batch_size, sequence_length)可选) — Mask,以避免对 padding 标记索引执行注意力机制。Mask 值在 [0, 1] 中选择:

    • 1 表示标记不被 Mask
    • 0 表示标记被 Mask

    什么是注意力 Mask?

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

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

    什么是标记类型 IDs?

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

    什么是位置 IDs?

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

    • 1 表示头不被 Mask
    • 0 表示头被 Mask
  • 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)可选) — 用于计算标记分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 中。

返回值

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.TokenClassifierOutput 或一个 torch.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=True 或当 config.output_hidden_states=True 时返回) — torch.FloatTensor 的 Tuple (如果模型具有嵌入层,则为嵌入的输出 + 每层输出一个),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的 Hidden-states 加上可选的初始嵌入输出。

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

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

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

尽管 forward pass 的配方需要在该函数内定义,但应该在此之后调用 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() 方法来加载模型权重。

SqueezeBERT 模型,顶部带有一个 span 分类头,用于抽取式问答任务,例如 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 Module,并参阅 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: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.QuestionAnsweringModelOutput or tuple(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), 可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在 [0, 1] 中选择:

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

    什么是 attention masks?

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

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

    什么是 token type IDs?

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

    什么是 position IDs?

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

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

返回值

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

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

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

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

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

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

    模型在每层输出处的 Hidden-states 加上可选的初始嵌入输出。

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

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

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

尽管 forward pass 的配方需要在该函数内定义,但应该在此之后调用 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 上更新