改革者
概述
Reformer模型由Nikita Kitaev、Łukasz Kaiser和Anselm Levskaya在论文Reformer: The Efficient Transformer中提出。
论文的摘要如下:
大型Transformer模型在许多任务上通常能取得最先进的结果,但训练这些模型的成本可能非常高,尤其是在长序列上。我们引入了两种技术来提高Transformer的效率。首先,我们用局部敏感哈希替换了点积注意力机制,将其复杂度从O(L^2)降低到O(Llog(L)),其中L是序列的长度。此外,我们使用可逆残差层代替标准残差层,这使得在训练过程中只需存储一次激活值,而不是N次,其中N是层数。由此产生的模型,Reformer,在性能上与Transformer模型相当,同时在长序列上更加节省内存且速度更快。
该模型由patrickvonplaten贡献。作者的代码可以在这里找到。
使用提示
- Reformer 不 与 torch.nn.DataParallel 一起工作,因为 PyTorch 中存在一个错误,请参阅 issue #36035。
- 使用轴向位置编码(详见下文)。这是一种通过将位置编码矩阵分解为较小的矩阵来避免在序列长度非常大时拥有巨大的位置编码矩阵的机制。
- 用LSH(局部敏感哈希)注意力替换传统的注意力(详见下文)。这是一种避免在注意力层中计算完整查询-键乘积的技术。
- 通过使用可逆的transformer层在反向传播过程中获取每一层的中间结果(从下一层的输入中减去残差可以得到它们)或重新计算给定层内的结果(比存储它们效率低,但节省内存),避免存储每一层的中间结果。
- 按块计算前馈操作,而不是在整个批次上进行。
轴向位置编码
轴向位置编码首次在Google的trax库中实现,并由该模型论文的作者开发。在处理非常长的输入序列的模型中,传统的位置ID编码存储一个大小为的嵌入向量,即config.hidden_size
,对于每个位置,其中为config.max_embedding_size
。这意味着如果序列长度为,且config.hidden_size
为,将生成一个位置编码矩阵:
仅存储的参数就超过500M。轴向位置编码将分解为两个矩阵:
和
with:
因此,以下成立:
直观上,这意味着位置嵌入向量 现在是两个分解嵌入向量的组合:,其中 config.max_embedding_size
维度 被分解为。这种设计确保了每个位置嵌入向量 是唯一的。
再次使用上述示例,轴向位置编码与 可以显著减少参数数量,从500,000,000减少到 参数,这意味着内存使用量减少了85%。
在实践中,参数 config.axial_pos_embds_dim
被设置为一个元组,其总和必须等于 config.hidden_size
,而 config.axial_pos_shape
被设置为一个元组,其乘积必须等于 config.max_embedding_size
,在训练期间,它必须等于 input_ids
的序列长度。
LSH 自注意力
在局部敏感哈希(LSH)自注意力机制中,键和查询的投影权重是绑定的。因此,键查询嵌入向量也是绑定的。LSH自注意力机制使用了在Practical and Optimal LSH for Angular Distance中提出的局部敏感哈希机制,将每个绑定的键查询嵌入向量分配到config.num_buckets
个可能的桶中的一个。前提是,键查询嵌入向量之间的“相似度”越高(以余弦相似度衡量),它们被分配到同一个桶的可能性就越大。
LSH机制的准确性可以通过增加config.num_hashes
或直接增加前向函数的参数num_hashes
来提高,从而使LSH自注意力的输出更好地近似于“正常”全自注意力的输出。然后,桶被排序并分块成查询键嵌入向量块,每个块的长度为config.lsh_chunk_length
。对于每个块,查询嵌入向量会关注其键向量(这些键向量与自身绑定)以及config.lsh_num_chunks_before
个前一个相邻块和config.lsh_num_chunks_after
个后一个相邻块的键嵌入向量。
请注意,config.num_buckets
也可以分解为一个列表。这样,查询键嵌入向量不是被分配到 中的一个,而是被分配到 中的一个。这对于非常长的序列来说,节省内存至关重要。
当从头开始训练模型时,建议保持config.num_buckets=None
,以便根据序列长度动态计算num_buckets
的合适值。这个值随后会自动保存在配置中,并应在推理时重复使用。
使用LSH自注意力机制,查询-键矩阵乘法操作的内存和时间复杂度可以从 降低到,这通常代表了Transformer模型中的内存和时间瓶颈,其中 是序列长度。
局部自注意力
局部自注意力本质上是一个“正常”的自注意力层,具有键、查询和值的投影,但被分块处理,使得在每个长度为config.local_chunk_length
的块中,查询嵌入向量仅关注其块中的键嵌入向量以及config.local_num_chunks_before
个前邻块和config.local_num_chunks_after
个后邻块的键嵌入向量。
使用局部自注意力机制,查询-键矩阵乘法操作的内存和时间复杂度可以从 降低到,这通常代表了Transformer模型中的内存和时间瓶颈,其中 是序列长度。
训练
在训练过程中,我们必须确保序列长度设置为可以被config.lsh_chunk_length
和config.local_chunk_length
的最小公倍数整除的值,并且如上述所述正确设置轴向位置编码的参数。Reformer非常节省内存,因此模型可以轻松地在长达64000个标记的序列上进行训练。
对于训练,应如下使用ReformerModelWithLMHead:
input_ids = tokenizer.encode("This is a sentence from the training data", return_tensors="pt")
loss = model(input_ids, labels=input_ids)[0]
资源
ReformerConfig
类 transformers.ReformerConfig
< source >( attention_head_size = 64 attn_layers = ['local', 'lsh', 'local', 'lsh', 'local', 'lsh'] axial_norm_std = 1.0 axial_pos_embds = True axial_pos_shape = [64, 64] axial_pos_embds_dim = [64, 192] chunk_size_lm_head = 0 eos_token_id = 2 feed_forward_size = 512 hash_seed = None hidden_act = 'relu' hidden_dropout_prob = 0.05 hidden_size = 256 initializer_range = 0.02 is_decoder = False layer_norm_eps = 1e-12 local_num_chunks_before = 1 local_num_chunks_after = 0 local_attention_probs_dropout_prob = 0.05 local_attn_chunk_length = 64 lsh_attn_chunk_length = 64 lsh_attention_probs_dropout_prob = 0.0 lsh_num_chunks_before = 1 lsh_num_chunks_after = 0 max_position_embeddings = 4096 num_attention_heads = 12 num_buckets = None num_hashes = 1 pad_token_id = 0 vocab_size = 320 tie_word_embeddings = False use_cache = True classifier_dropout = None **kwargs )
参数
- attention_head_size (
int
, optional, 默认为 64) — 投影的键、查询和值向量的维度 - attn_layers (
List[str]
, optional, defaults to["local", "lsh", "local", "lsh", "local", "lsh"]
) — List of attention layer types in ascending order. It can be chosen between a LSHSelfAttention layer ("lsh"
) and a LocalSelfAttention layer ("local"
).有关LSHSelfAttention层的更多信息,请参阅LSH Self Attention。有关LocalSelfAttention层的更多信息,请参阅Local Self Attention.
- axial_pos_embds (
bool
, 可选, 默认为True
) — 是否使用轴向位置嵌入。有关轴向位置嵌入如何工作的更多信息,请参见 Axial Position Encodings. - axial_norm_std (
float
, 可选, 默认为 1.0) — 用于初始化轴向位置编码权重矩阵的 normal_initializer 的标准差。 - axial_pos_shape (
List[int]
, optional, defaults to[64, 64]
) — The position dims of the axial position encodings. During training, the product of the position dims has to be equal to the sequence length.有关轴向位置嵌入如何工作的更多信息,请参阅轴向位置编码.
- axial_pos_embds_dim (
List[int]
, optional, defaults to[64, 192]
) — The embedding dims of the axial position encodings. The sum of the embedding dims has to be equal to the hidden size.有关轴向位置嵌入如何工作的更多信息,请参阅轴向位置编码.
- chunk_size_lm_head (
int
, optional, defaults to 0) — The chunk size of the final language model feed forward head layer. A chunk size of 0 means that the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes n < sequence_length embeddings at a time.有关前馈分块的更多信息,请参阅前馈分块如何工作?.
- eos_token_id (
int
, optional, defaults to 2) — 句子结束标记的标记ID。 - feed_forward_size (
int
, optional, 默认为 512) — 残差注意力块中前馈层的维度。 - hash_seed (
int
, 可选) — 种子,可用于使LSHSelfAttention
中的局部敏感哈希具有确定性。这应该仅用于测试目的。对于评估和训练目的,hash_seed
应保持为None
,以确保局部敏感哈希方案中的完全随机旋转。 - hidden_act (
str
或Callable
, 可选, 默认为"relu"
) — 残差注意力块中前馈层的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
,"relu"
,"silu"
和"gelu_new"
. - hidden_dropout_prob (
float
, optional, 默认为 0.05) — 嵌入层、编码器和池化器中所有全连接层的 dropout 概率。 - hidden_size (
int
, optional, 默认为 256) — 残差注意力块的输出隐藏状态的维度。 - initializer_range (
float
, 可选, 默认值为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - is_decoder (
bool
, 可选, 默认为False
) — 是否在传递给 ReformerModel 的attention_mask
之外使用因果掩码。当 使用 Reformer 进行因果语言建模时,此参数应设置为True
. - layer_norm_eps (
float
, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。 - local_chunk_length (
int
, 可选, 默认为 64) — 在LocalSelfAttention
中,自身关注的块的长度。分块将内存复杂度从 序列长度 x 序列长度(自注意力)降低到块长度 x 块长度 x 序列长度 / 块 长度(分块自注意力)。 - local_num_chunks_before (
int
, optional, defaults to 1) — 在LocalSelfAttention
层中,自身需要关注的先前相邻块的数量。 - local_num_chunks_after (
int
, optional, 默认为 0) — 在LocalSelfAttention
层中,除了自身之外,还需要关注后续相邻块的数量。 - local_attention_probs_dropout_prob (
float
, 可选, 默认为 0.1) —LocalSelfAttention
中注意力概率的丢弃比例。 - lsh_attn_chunk_length (
int
, 可选, 默认为 64) — 在LSHSelfAttention
中,自身关注的块长度。分块将内存复杂度从序列长度 x 序列长度(自注意力)降低到块长度 x 块长度 x 序列长度 / 块长度(分块自注意力)。 - lsh_num_chunks_before (
int
, 可选, 默认为 1) — 在LSHSelfAttention
层中,自身需要关注的先前相邻块的数量。 - lsh_num_chunks_after (
int
, optional, defaults to 0) — 在LSHSelfAttention
层中,自身需要关注的下一个相邻块的数量。 - lsh_attention_probs_dropout_prob (
float
, optional, 默认为 0.1) — 在LSHSelfAttention
中注意力概率的丢弃比例。 - max_position_embeddings (
int
, optional, 默认为 4096) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。 - num_attention_heads (
int
, optional, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数。 - num_buckets (
int
或List[int]
, 可选) — 桶的数量,关键查询向量可以使用局部敏感哈希方案“哈希到”这些桶中。 每个查询关键向量被哈希到1, ..., num_buckets
中的一个哈希值。桶的数量也可以被分解为一个列表以提高内存复杂度。在这种情况下,如果num_buckets
被分解为两个因子,每个查询关键向量将被哈希到1-1, 1-2, ..., num_buckets[0]-1, ..., num_buckets[0]-num_buckets[1]
中的一个哈希值。桶的数量(或因子的乘积)应大约等于序列长度 / lsh_chunk_length。如果未设置num_buckets
,则会动态计算一个合适的值。 - num_hashes (
int
, 可选, 默认为 1) — 局部敏感哈希方案中的哈希轮数(例如,随机旋转的次数)。num_hashes
越高,LSHSelfAttention
的准确性越高,但哈希所需的内存和时间也越多。 - pad_token_id (
int
, optional, defaults to 0) — 用于填充的token id. - vocab_size (
int
, 可选, 默认为 320) —\ Reformer 模型的词汇表大小。定义了调用 ReformerModel 时传递的inputs_ids
可以表示的不同标记的数量。 - tie_word_embeddings (
bool
, 可选, 默认为False
) — 是否将输入和输出嵌入绑定在一起. - use_cache (
bool
, 可选, 默认为True
) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。 - classifier_dropout (
float
, optional) — 分类头的丢弃比率。
这是用于存储ReformerModel配置的配置类。它用于根据指定的参数实例化一个Reformer模型,定义模型架构。使用默认值实例化配置将产生类似于ReFormergoogle/reformer-crime-and-punishment架构的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import ReformerConfig, ReformerModel
>>> # Initializing a Reformer configuration
>>> configuration = ReformerConfig()
>>> # Initializing a Reformer model (with random weights)
>>> model = ReformerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
ReformerTokenizer
类 transformers.ReformerTokenizer
< source >( vocab_file eos_token = '' unk_token = '
参数
- vocab_file (
str
) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。 - eos_token (
str
, optional, defaults to"</s>"
) — The end of sequence token.在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是
sep_token
。 - unk_token (
str
, optional, defaults to"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。" - additional_special_tokens (
List[str]
, optional, defaults to[]
) — 分词器使用的额外特殊标记。 - sp_model_kwargs (
dict
, optional) — Will be passed to theSentencePieceProcessor.__init__()
method. The Python wrapper for SentencePiece can be used, among other things, to set:-
enable_sampling
: 启用子词正则化。 -
nbest_size
: 用于unigram的采样参数。对于BPE-Dropout无效。nbest_size = {0,1}
: No sampling is performed.nbest_size > 1
: samples from the nbest_size results.nbest_size < 0
: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
-
alpha
: 用于单字采样的平滑参数,以及BPE-dropout的合并操作丢弃概率。
-
构建一个Reformer分词器。基于SentencePiece。
此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
ReformerTokenizerFast
类 transformers.ReformerTokenizerFast
< source >( vocab_file = None tokenizer_file = None eos_token = '' unk_token = '
参数
- vocab_file (
str
) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。 - eos_token (
str
, optional, defaults to"</s>"
) — The end of sequence token.在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是
sep_token
。 - unk_token (
str
, optional, defaults to"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。" - pad_token (
str
, optional, defaults to"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。" - additional_special_tokens (
List[str]
, optional) — 分词器使用的额外特殊标记。
构建一个“快速”的Reformer分词器(基于HuggingFace的tokenizers库)。基于 Unigram。
这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。
ReformerModel
类 transformers.ReformerModel
< source >( config )
参数
- config (ReformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Reformer模型的基本变换器输出原始隐藏状态,没有任何特定的头部。 Reformer由Nikita Kitaev、Łukasz Kaiser和Anselm Levskaya在Reformer: The Efficient Transformer中提出。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: 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 num_hashes: typing.Optional[int] = None past_buckets_states: typing.Optional[typing.List[typing.Tuple[torch.Tensor]]] = None use_cache: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.reformer.modeling_reformer.ReformerModelOutput
或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. During training the input_ids sequence_length has to be a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices are automatically padded to be a multiple of the chunk length.可以使用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.
- 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
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - num_hashes (
int
, optional) — The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites the default defined inconfig.num_hashes
.有关更多信息,请参阅ReformerConfig中的
num_hashes
。 - past_buckets_states (
List[Tuple(torch.LongTensor, torch.FloatTensor)]
, optional) — List ofTuple(torch.LongTensor, torch.FloatTensor
of lengthconfig.n_layers
, with the first element being the previous buckets of shape(batch_size, num_heads, num_hashes, sequence_length)
) and the second being the previous hidden_states of shape(batch_size, sequence_length, hidden_size)
).包含预计算的隐藏状态和桶(仅与LSH自注意力相关)。可用于加速顺序解码。
- use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回的张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.models.reformer.modeling_reformer.ReformerModelOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.reformer.modeling_reformer.ReformerModelOutput
或一个由 torch.FloatTensor
组成的元组
(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置(ReformerConfig)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, num_predict, hidden_size)
) — 模型最后一层的隐藏状态序列。num_predict
对应于target_mapping.shape[1]
。如果target_mapping
为None
,则num_predict
对应于sequence_length
。 -
past_buckets_states (
List[Tuple(torch.LongTensor, torch.FloatTensor)]
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的Tuple(torch.LongTensor, torch.FloatTensor
列表,第一个元素 是形状为(batch_size, num_heads, num_hashes, sequence_length)
的前一个 buckets,第二个元素 是形状为(batch_size, sequence_length, hidden_size)
的前一个 hidden_states)。包含预计算的分桶和隐藏状态,可用于(参见
past_buckets_states
输入)加速顺序解码。 -
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 之后,用于计算自注意力头中的加权平均值。
ReformerModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, ReformerModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerModel.from_pretrained("google/reformer-crime-and-punishment")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
ReformerModelWithLMHead
类 transformers.ReformerModelWithLMHead
< source >( config )
参数
- config (ReformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Reformer 模型顶部带有 language modeling
头。
Reformer 是由 Nikita Kitaev、Łukasz Kaiser 和 Anselm Levskaya 在 Reformer: The Efficient Transformer 中提出的。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None past_buckets_states: typing.Optional[typing.List[typing.Tuple[torch.Tensor]]] = None use_cache: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None ) → transformers.modeling_outputs.CausalLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. During training the input_ids sequence_length has to be a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices are automatically padded to be a multiple of the chunk length.可以使用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.
- 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
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - num_hashes (
int
, optional) — The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites the default defined inconfig.num_hashes
.有关更多信息,请参阅ReformerConfig中的
num_hashes
。 - past_buckets_states (
List[Tuple(torch.LongTensor, torch.FloatTensor)]
, optional) — List ofTuple(torch.LongTensor, torch.FloatTensor
of lengthconfig.n_layers
, with the first element being the previous buckets of shape(batch_size, num_heads, num_hashes, sequence_length)
) and the second being the previous hidden_states of shape(batch_size, sequence_length, hidden_size)
).包含预计算的隐藏状态和桶(仅与LSH自注意力相关)。可用于加速顺序解码。
- use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算序列分类/回归损失的标签。索引应在[-100, 0, ..., config.vocab_size - 1]
范围内。所有设置为-100
的标签将被忽略(掩码),损失仅计算在[0, ..., config.vocab_size]
范围内的标签
返回
transformers.modeling_outputs.CausalLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(ReformerConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失(用于下一个标记预测)。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。
ReformerModelWithLMHead 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import torch
>>> from transformers import AutoTokenizer, ReformerModelWithLMHead
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerModelWithLMHead.from_pretrained("google/reformer-crime-and-punishment")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs, labels=inputs["input_ids"])
>>> loss = outputs.loss
>>> logits = outputs.logits
ReformerForMaskedLM
类 transformers.ReformerForMaskedLM
< source >( config )
参数
- config (ReformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Reformer 模型顶部带有 language modeling
头。
Reformer 是由 Nikita Kitaev、Łukasz Kaiser 和 Anselm Levskaya 在 Reformer: The Efficient Transformer 中提出的。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: 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. During training the input_ids sequence_length has to be a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices are automatically padded to be a multiple of the chunk length.可以使用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.
- 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
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - num_hashes (
int
, optional) — The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites the default defined inconfig.num_hashes
.有关更多信息,请参阅ReformerConfig中的
num_hashes
。 - past_buckets_states (
List[Tuple(torch.LongTensor, torch.FloatTensor)]
, optional) — List ofTuple(torch.LongTensor, torch.FloatTensor
of lengthconfig.n_layers
, with the first element being the previous buckets of shape(batch_size, num_heads, num_hashes, sequence_length)
) and the second being the previous hidden_states of shape(batch_size, sequence_length, hidden_size)
).包含预计算的隐藏状态和桶(仅与LSH自注意力相关)。可用于加速顺序解码。
- use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对带有标签的标记进行计算
返回
transformers.modeling_outputs.MaskedLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.MaskedLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(ReformerConfig)和输入。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
ReformerForMaskedLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
此示例使用了一个虚假的检查点,因为我们没有任何可用的预训练模型用于Reformer架构的掩码语言建模任务。
示例:
>>> import torch
>>> from transformers import AutoTokenizer, ReformerForMaskedLM
>>> tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-reformer")
>>> model = ReformerForMaskedLM.from_pretrained("hf-internal-testing/tiny-random-reformer")
>>> # add mask_token
>>> tokenizer.add_special_tokens({"mask_token": "[MASK]"})
>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="pt")
>>> # resize model's embedding matrix
>>> model.resize_token_embeddings(new_num_tokens=model.config.vocab_size + 1)
>>> 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)
>>> predicted_token = tokenizer.decode(predicted_token_id)
>>> 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[:, : inputs["input_ids"].shape[-1]], -100
... )
>>> outputs = model(**inputs, labels=labels)
>>> loss = round(outputs.loss.item(), 2)
ReformerForSequenceClassification
类 transformers.ReformerForSequenceClassification
< source >( config )
参数
- config (ReformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Reformer模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于GLUE任务。
Reformer 是由 Nikita Kitaev、Łukasz Kaiser 和 Anselm Levskaya 在 Reformer: The Efficient Transformer 中提出的。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: 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. During training the input_ids sequence_length has to be a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices are automatically padded to be a multiple of the chunk length.可以使用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.
- 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
索引转换为相关向量有更多控制权,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - num_hashes (
int
, optional) — The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites the default defined inconfig.num_hashes
.有关更多信息,请参阅ReformerConfig中的
num_hashes
。 - past_buckets_states (
List[Tuple(torch.LongTensor, torch.FloatTensor)]
, optional) — List ofTuple(torch.LongTensor, torch.FloatTensor
of lengthconfig.n_layers
, with the first element being the previous buckets of shape(batch_size, num_heads, num_hashes, sequence_length)
) and the second being the previous hidden_states of shape(batch_size, sequence_length, hidden_size)
).包含预计算的隐藏状态和桶(仅与LSH自注意力相关)。可用于加速顺序解码。
- use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - 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
时),包含各种
元素,具体取决于配置(ReformerConfig)和输入。
-
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 后的注意力权重,用于计算自注意力头中的加权平均值。
ReformerForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
单标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, ReformerForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerForSequenceClassification.from_pretrained("google/reformer-crime-and-punishment")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> label = model.config.id2label[predicted_class_id]
>>> # 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 = ReformerForSequenceClassification.from_pretrained(
... "google/reformer-crime-and-punishment", num_labels=num_labels
... )
>>> labels = torch.tensor(1)
>>> loss = model(**inputs, labels=labels).loss
ReformerForQuestionAnswering
类 transformers.ReformerForQuestionAnswering
< source >( config )
参数
- config (ReformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Reformer 模型,顶部带有用于抽取式问答任务(如 SQuAD / TriviaQA)的跨度分类头
(在隐藏状态输出顶部有一个线性层,用于计算 span start logits
和 span end logits
。
Reformer 是由 Nikita Kitaev、Łukasz Kaiser 和 Anselm Levskaya 在 Reformer: The Efficient Transformer 中提出的。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None num_hashes: typing.Optional[int] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None output_attentions: 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. During training the input_ids sequence_length has to be a multiple of the relevant model’s chunk lengths (lsh’s, local’s or both). During evaluation, the indices are automatically padded to be a multiple of the chunk length.可以使用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.
- 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
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - num_hashes (
int
, optional) — The number of hashing rounds that should be performed during bucketing. Setting this argument overwrites the default defined inconfig.num_hashes
.有关更多信息,请参阅ReformerConfig中的
num_hashes
。 - past_buckets_states (
List[Tuple(torch.LongTensor, torch.FloatTensor)]
, optional) — List ofTuple(torch.LongTensor, torch.FloatTensor
of lengthconfig.n_layers
, with the first element being the previous buckets of shape(batch_size, num_heads, num_hashes, sequence_length)
) and the second being the previous hidden_states of shape(batch_size, sequence_length, hidden_size)
).包含预计算的隐藏状态和桶(仅与LSH自注意力相关)。可用于加速顺序解码。
- use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会被考虑用于计算损失。 - end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置在计算损失时不被考虑。
返回
transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(ReformerConfig)和输入。
-
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 之后,用于计算自注意力头中的加权平均值。
ReformerForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, ReformerForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("google/reformer-crime-and-punishment")
>>> model = ReformerForQuestionAnswering.from_pretrained("google/reformer-crime-and-punishment")
>>> 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