SqueezeBERT
概述
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。它是一个类似于BERT模型的双向变压器。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
类 transformers.SqueezeBertConfig
< source >( 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
, optional, defaults to 768) — 编码器层和池化层的维度。 - num_hidden_layers (
int
, optional, defaults to 12) — Transformer编码器中的隐藏层数量。 - num_attention_heads (
int
, optional, defaults to 12) — Transformer编码器中每个注意力层的注意力头数量。 - intermediate_size (
int
, optional, 默认为 3072) — Transformer 编码器中“中间”(通常称为前馈)层的维度。 - hidden_act (
str
或Callable
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - hidden_dropout_prob (
float
, optional, 默认为 0.1) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
float
, optional, defaults to 0.1) — 注意力概率的丢弃比例。 - max_position_embeddings (
int
, optional, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512、1024 或 2048)。 - type_vocab_size (
int
, 可选, 默认为 2) — 调用 BertModel 或 TFBertModel 时传递的token_type_ids
的词汇大小. - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - layer_norm_eps (
float
, 可选, 默认为 1e-12) — - pad_token_id (
int
, optional, 默认为 0) — 在词嵌入中用作填充的标记的ID。 - embedding_size (
int
, optional, 默认为 768) — 词嵌入向量的维度。 - q_groups (
int
, optional, 默认为 4) — Q 层中的组数。 - k_groups (
int
, 可选, 默认为 4) — K层中的组数。 - v_groups (
int
, optional, 默认为 4) — V 层中的组数。 - post_attention_groups (
int
, optional, defaults to 1) — 第一个前馈网络层中的组数。 - intermediate_groups (
int
, optional, 默认为 4) — 第二个前馈网络层中的组数。 - output_groups (
int
, optional, 默认为 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
类 transformers.SqueezeBertTokenizer
< source >( 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 toTrue
) — 是否在分词时将输入转换为小写。 - do_basic_tokenize (
bool
, optional, defaults toTrue
) — 是否在WordPiece之前进行基本的分词。 - never_split (
Iterable
, 可选) — 在分词过程中永远不会被分割的标记集合。仅在do_basic_tokenize=True
- unk_token (
str
, optional, defaults to"[UNK]"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。 - sep_token (
str
, optional, defaults to"[SEP]"
) — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - pad_token (
str
, 可选, 默认为"[PAD]"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。 - cls_token (
str
, 可选, 默认为"[CLS]"
) — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。 - mask_token (
str
, 可选, 默认为"[MASK]"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。 - tokenize_chinese_chars (
bool
, optional, defaults toTrue
) — Whether or not to tokenize Chinese characters.这可能应该为日语停用(参见此 issue)。
- strip_accents (
bool
, 可选) — 是否去除所有重音符号。如果未指定此选项,则将由lowercase
的值决定(如原始SqueezeBERT中所示)。 - clean_up_tokenization_spaces (
bool
, 可选, 默认为True
) — 是否在解码后清理空格,清理包括移除潜在的额外空格等可能的痕迹。
构建一个SqueezeBERT分词器。基于WordPiece。
此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。SqueezeBERT序列具有以下格式:
- 单一序列:
[CLS] X [SEP]
- 序列对:
[CLS] A [SEP] B [SEP]
get_special_tokens_mask
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) → List[int]
从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model
方法添加特殊标记时,会调用此方法。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。一个SqueezeBERT序列
如果 token_ids_1
是 None
,此方法仅返回掩码的第一部分(0s)。
SqueezeBertTokenizerFast
类 transformers.SqueezeBertTokenizerFast
< source >( 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
, 可选, 默认为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
, 可选, 默认为"[CLS]"
) — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。 - mask_token (
str
, optional, 默认为"[MASK]"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。 - clean_text (
bool
, optional, defaults toTrue
) — 是否在分词前通过移除任何控制字符并用经典空格替换所有空格来清理文本。 - tokenize_chinese_chars (
bool
, 可选, 默认为True
) — 是否对中文字符进行分词。对于日语,可能需要停用此功能(参见此问题)。 - strip_accents (
bool
, 可选) — 是否去除所有重音符号。如果未指定此选项,则将由lowercase
的值决定(如原始SqueezeBERT中所示)。 - wordpieces_prefix (
str
, optional, defaults to"##"
) — 子词的前缀。
构建一个“快速”的SqueezeBERT分词器(由HuggingFace的tokenizers库支持)。基于WordPiece。
这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0 token_ids_1 = 无 ) → List[int]
通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。SqueezeBERT序列具有以下格式:
- 单一序列:
[CLS] X [SEP]
- 序列对:
[CLS] A [SEP] B [SEP]
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。一个SqueezeBERT序列
如果 token_ids_1
是 None
,此方法仅返回掩码的第一部分(0s)。
SqueezeBertModel
类 transformers.SqueezeBertModel
< source >( config )
参数
- config (SqueezeBertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
SqueezeBERT模型的基本变换器,输出原始的隐藏状态,顶部没有任何特定的头部。
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
为了在文本分类任务上微调SqueezeBERT获得最佳效果,建议使用squeezebert/squeezebert-mnli-headless检查点作为起点。
层级结构:
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.
前进
< source >( 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.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(SqueezeBertConfig)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
形状为(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)在经过用于辅助预训练任务的层进一步处理后的最后一层隐藏状态。例如,对于BERT系列模型,这返回经过线性层和tanh激活函数处理后的分类标记。线性层的权重是在预训练期间通过下一个句子预测(分类)目标训练的。 -
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之后,用于计算自注意力头中的加权平均值。
SqueezeBertModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
< source >( config )
参数
- config (SqueezeBertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
SqueezeBERT 模型,顶部带有language modeling
头。
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
为了在文本分类任务上微调SqueezeBERT获得最佳效果,建议使用squeezebert/squeezebert-mnli-headless检查点作为起点。
层级结构:
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.
前进
< source >( 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.MaskedLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对标签在[0, ..., config.vocab_size]
范围内的标记进行计算
返回
transformers.modeling_outputs.MaskedLMOutput 或 tuple(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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(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 后的注意力权重,用于计算自注意力头中的加权平均值。
SqueezeBertForMaskedLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
类 transformers.SqueezeBertForSequenceClassification
< source >( config )
参数
- config (SqueezeBertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
SqueezeBERT模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于GLUE任务。
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
为了在文本分类任务上微调SqueezeBERT获得最佳效果,建议使用squeezebert/squeezebert-mnli-headless检查点作为起点。
层级结构:
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.
前进
< source >( 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.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - 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
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失(均方损失),如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回
transformers.modeling_outputs.SequenceClassifierOutput 或 tuple(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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(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 后的注意力权重,用于计算自注意力头中的加权平均值。
SqueezeBertForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
< source >( config )
参数
- config (SqueezeBertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
SqueezeBERT模型,顶部带有多项选择分类头(在池化输出之上的线性层和softmax),例如用于RocStories/SWAG任务。
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
为了在文本分类任务上微调SqueezeBERT获得最佳效果,建议使用squeezebert/squeezebert-mnli-headless检查点作为起点。
层级结构:
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.
前进
< source >( 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.MultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, num_choices, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- token_type_ids (
torch.LongTensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
形状为(batch_size, num_choices, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices-1]
范围内,其中 num_choices 是输入张量第二维的大小。(参见上面的 input_ids)
返回
transformers.modeling_outputs.MultipleChoiceModelOutput 或 tuple(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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(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 后的注意力权重,用于计算自注意力头中的加权平均值。
SqueezeBertForMultipleChoice 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
类 transformers.SqueezeBertForTokenClassification
< source >( config )
参数
- config (SqueezeBertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
SqueezeBERT 模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
为了在文本分类任务上微调SqueezeBERT获得最佳效果,建议使用squeezebert/squeezebert-mnli-headless检查点作为起点。
层级结构:
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.
前进
< source >( 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.TokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - head_mask (
torch.FloatTensor
形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算标记分类损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。
返回
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(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 后的注意力权重,用于计算自注意力头中的加权平均值。
SqueezeBertForTokenClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
类 transformers.SqueezeBertForQuestionAnswering
< source >( config )
参数
- config (SqueezeBertConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
SqueezeBERT模型,顶部带有用于抽取式问答任务(如SQuAD)的跨度分类头(在隐藏状态输出之上的线性层,用于计算span start logits
和span end logits
)。
SqueezeBERT模型由Forrest N. Iandola、Albert E. Shaw、Ravi Krishna和Kurt W. Keutzer在SqueezeBERT: What can computer vision teach NLP about efficient neural networks?中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
为了在文本分类任务上微调SqueezeBERT获得最佳效果,建议使用squeezebert/squeezebert-mnli-headless检查点作为起点。
层级结构:
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.
前进
< source >( 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 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- token_type_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Segment token indices to indicate first and second portions of the inputs. Indices are selected in[0, 1]
:- 0 corresponds to a sentence A token,
- 1 corresponds to a sentence B token.
- position_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range[0, config.max_position_embeddings - 1]
. - 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
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会被考虑用于计算损失。 - end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
返回
transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 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
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(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 后的注意力权重,用于计算自注意力头中的加权平均值。
SqueezeBertForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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