Longformer
概述
Longformer模型由Iz Beltagy、Matthew E. Peters和Arman Cohan在Longformer: The Long-Document Transformer中提出。
论文的摘要如下:
基于Transformer的模型由于其自注意力操作无法处理长序列,该操作与序列长度成二次方增长。为了解决这一限制,我们引入了Longformer,其注意力机制与序列长度成线性增长,使得处理数千个标记或更长的文档变得容易。Longformer的注意力机制是标准自注意力的直接替代品,并结合了局部窗口注意力和任务驱动的全局注意力。在之前的长序列Transformer工作的基础上,我们在字符级语言建模上评估了Longformer,并在text8和enwik8上取得了最先进的结果。与大多数之前的工作不同,我们还对Longformer进行了预训练,并在各种下游任务上进行了微调。我们的预训练Longformer在长文档任务上始终优于RoBERTa,并在WikiHop和TriviaQA上设定了新的最先进结果。
使用提示
- 由于Longformer基于RoBERTa,它没有
token_type_ids
。你不需要指明哪个token属于哪个段。只需用分隔符tokenizer.sep_token
(或)分隔你的段。
- 一种通过用稀疏矩阵替换注意力矩阵来加速的变压器模型。通常,局部上下文(例如,左右两个标记是什么?)足以对给定标记采取行动。一些预选的输入标记仍然被赋予全局注意力,但注意力矩阵的参数大大减少,从而实现了加速。有关更多信息,请参阅局部注意力部分。
Longformer 自注意力机制
Longformer自注意力机制在“局部”上下文和“全局”上下文中都采用了自注意力机制。大多数标记只“局部”关注彼此,这意味着每个标记关注其前一个标记和后一个标记,其中是config.attention_window
中定义的窗口长度。请注意,config.attention_window
可以是List
类型,以便为每一层定义不同的。少数选定的标记“全局”关注所有其他标记,就像在BertSelfAttention
中所有标记通常所做的那样。
请注意,“局部”和“全局”关注的标记由不同的查询、键和值矩阵投影。还要注意,每个“局部”关注的标记不仅关注其窗口内的标记,还关注所有“全局”关注的标记,以便全局关注是对称的。
用户可以通过在运行时适当设置张量global_attention_mask
来定义哪些标记“局部”关注,哪些标记“全局”关注。所有Longformer模型都采用以下逻辑来处理global_attention_mask
:
- 0: 该标记“局部”参与,
- 1: 该标记“全局”参与。
更多信息请参考forward()方法。
使用Longformer自注意力机制,查询-键矩阵乘法操作的内存和时间复杂度,通常代表内存和时间的瓶颈,可以从 降低到,其中 是序列长度, 是平均窗口大小。假设“全局”参与标记的数量与“局部”参与标记的数量相比微不足道。
更多信息,请参考官方论文。
训练
LongformerForMaskedLM 的训练方式与 RobertaForMaskedLM 完全相同,应按以下方式使用:
input_ids = tokenizer.encode("This is a sentence from [MASK] training data", return_tensors="pt")
mlm_labels = tokenizer.encode("This is a sentence from the training data", return_tensors="pt")
loss = model(input_ids, labels=input_ids, masked_lm_labels=mlm_labels)[0]
资源
LongformerConfig
类 transformers.LongformerConfig
< source >( attention_window: typing.Union[typing.List[int], int] = 512 sep_token_id: int = 2 pad_token_id: int = 1 bos_token_id: int = 0 eos_token_id: int = 2 vocab_size: int = 30522 hidden_size: int = 768 num_hidden_layers: int = 12 num_attention_heads: int = 12 intermediate_size: int = 3072 hidden_act: str = 'gelu' hidden_dropout_prob: float = 0.1 attention_probs_dropout_prob: float = 0.1 max_position_embeddings: int = 512 type_vocab_size: int = 2 initializer_range: float = 0.02 layer_norm_eps: float = 1e-12 onnx_export: bool = False **kwargs )
参数
- vocab_size (
int
, optional, 默认为 30522) — Longformer 模型的词汇表大小。定义了可以通过调用 LongformerModel 或 TFLongformerModel 时传递的inputs_ids
表示的不同标记的数量。 - hidden_size (
int
, optional, 默认为 768) — 编码器层和池化层的维度。 - num_hidden_layers (
int
, optional, 默认为 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
, 可选, 默认为 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) — 调用 LongformerModel 或 TFLongformerModel 时传递的token_type_ids
的词汇大小. - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。 - layer_norm_eps (
float
, optional, defaults to 1e-12) — 层归一化层使用的epsilon值。 - attention_window (
int
或List[int]
, 可选, 默认为 512) — 每个标记周围的注意力窗口大小。如果是int
,则所有层使用相同的大小。要为每层指定不同的窗口大小,请使用List[int]
,其中len(attention_window) == num_hidden_layers
.
这是用于存储LongformerModel或TFLongformerModel配置的配置类。它用于根据指定的参数实例化一个Longformer模型,定义模型架构。
这是用于存储LongformerModel配置的配置类。它用于根据指定的参数实例化一个Longformer模型,定义模型架构。使用默认值实例化配置将产生与allenai/longformer-base-4096架构类似的配置,序列长度为4,096。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import LongformerConfig, LongformerModel
>>> # Initializing a Longformer configuration
>>> configuration = LongformerConfig()
>>> # Initializing a model from the configuration
>>> model = LongformerModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
LongformerTokenizer
类 transformers.LongformerTokenizer
< source >( vocab_file merges_file errors = 'replace' bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '
参数
- vocab_file (
str
) — 词汇表文件的路径。 - merges_file (
str
) — 合并文件的路径。 - errors (
str
, 可选, 默认为"replace"
) — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode. - bos_token (
str
, optional, defaults to"<s>"
) — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是
cls_token
。 - eos_token (
str
, optional, defaults to"</s>"
) — The end of sequence token.在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是
sep_token
。 - sep_token (
str
, 可选, 默认为""
) — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - cls_token (
str
, 可选, 默认为"
) — 用于序列分类的分类器标记(对整个序列进行分类,而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。" - unk_token (
str
, optional, defaults to"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。" - pad_token (
str
, optional, defaults to"
) — 用于填充的标记,例如在批处理不同长度的序列时使用。" - mask_token (
str
, 可选, 默认为"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。" - add_prefix_space (
bool
, 可选, 默认为False
) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(Longformer 分词器通过前面的空格检测单词的开头)。
构建一个Longformer分词器,该分词器源自GPT-2分词器,使用字节级别的字节对编码。
这个分词器已经被训练成将空格视为标记的一部分(有点像sentencepiece),因此一个单词将会
无论它是否在句子的开头(没有空格),编码方式都会有所不同:
>>> from transformers import LongformerTokenizer
>>> tokenizer = LongformerTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> tokenizer("Hello world")["input_ids"]
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")["input_ids"]
[0, 20920, 232, 2]
你可以通过在实例化此分词器或在某些文本上调用它时传递add_prefix_space=True
来绕过这种行为,但由于模型不是以这种方式预训练的,这可能会导致性能下降。
当与is_split_into_words=True
一起使用时,此分词器将在每个单词(即使是第一个单词)前添加一个空格。
此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。一个Longformer序列具有以下格式:
- 单一序列:
X - 序列对:
AB
将一系列标记(字符串)转换为单个字符串。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。Longformer不使用token类型ID,因此返回一个零列表。
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
方法添加特殊标记时,会调用此方法。
LongformerTokenizerFast
类 transformers.LongformerTokenizerFast
< source >( vocab_file = None merges_file = None tokenizer_file = None errors = 'replace' bos_token = '' eos_token = '' sep_token = '' cls_token = '' unk_token = '
参数
- vocab_file (
str
) — 词汇表文件的路径。 - merges_file (
str
) — 合并文件的路径。 - errors (
str
, 可选, 默认为"replace"
) — 解码字节为UTF-8时遵循的范式。更多信息请参见 bytes.decode. - bos_token (
str
, optional, defaults to"<s>"
) — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.在使用特殊标记构建序列时,这不是用于序列开头的标记。使用的标记是
cls_token
。 - eos_token (
str
, optional, defaults to"</s>"
) — The end of sequence token.在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是
sep_token
。 - sep_token (
str
, optional, defaults to""
) — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - cls_token (
str
, 可选, 默认为"
) — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。" - unk_token (
str
, optional, defaults to"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为该标记。" - pad_token (
str
, optional, defaults to"
) — 用于填充的标记,例如在批处理不同长度的序列时使用。" - mask_token (
str
, 可选, 默认为"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。" - add_prefix_space (
bool
, 可选, 默认为False
) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(Longformer 分词器通过前面的空格检测单词的开头)。 - trim_offsets (
bool
, optional, defaults toTrue
) — 后处理步骤是否应修剪偏移量以避免包含空格。
构建一个“快速”的Longformer分词器(由HuggingFace的tokenizers库支持),该分词器源自GPT-2分词器,使用字节级字节对编码。
这个分词器已经被训练成将空格视为标记的一部分(有点像sentencepiece),因此一个单词将会
无论它是否在句子的开头(没有空格),编码方式都会有所不同:
>>> from transformers import LongformerTokenizerFast
>>> tokenizer = LongformerTokenizerFast.from_pretrained("allenai/longformer-base-4096")
>>> tokenizer("Hello world")["input_ids"]
[0, 31414, 232, 2]
>>> tokenizer(" Hello world")["input_ids"]
[0, 20920, 232, 2]
你可以通过在实例化此分词器或在某些文本上调用它时传递add_prefix_space=True
来绕过这种行为,但由于模型不是以这种方式预训练的,这可能会导致性能下降。
当与is_split_into_words=True
一起使用时,此分词器需要使用add_prefix_space=True
进行实例化。
这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。Longformer不使用token类型ID,因此返回一个零列表。
Longformer 特定输出
类 transformers.models.longformer.modeling_longformer.LongformerBaseModelOutput
< source >( last_hidden_state: FloatTensor hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
Longformer 输出的基类,可能包含隐藏状态、局部和全局注意力。
类 transformers.models.longformer.modeling_longformer.LongformerBaseModelOutputWithPooling
< source >( last_hidden_state: FloatTensor pooler_output: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 - pooler_output (
torch.FloatTensor
of shape(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和Tanh激活函数的进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标进行训练的。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
Longformer 输出的基类,还包含最后隐藏状态的池化。
类 transformers.models.longformer.modeling_longformer.LongformerMaskedLMOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当提供labels
时返回) — 掩码语言建模(MLM)损失. - logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
用于掩码语言模型输出的基类。
类 transformers.models.longformer.modeling_longformer.LongformerQuestionAnsweringModelOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None start_logits: FloatTensor = None end_logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当提供labels
时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。 - start_logits (
torch.FloatTensor
of shape(batch_size, sequence_length)
) — 跨度起始分数(在SoftMax之前)。 - end_logits (
torch.FloatTensor
of shape(batch_size, sequence_length)
) — 跨度结束分数(在SoftMax之前)。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
用于问答Longformer模型输出的基类。
类 transformers.models.longformer.modeling_longformer.LongformerSequenceClassifierOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 - logits (
torch.FloatTensor
of shape(batch_size, config.num_labels)
) — 分类(如果 config.num_labels==1 则为回归)分数(在 SoftMax 之前)。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
句子分类模型输出的基类。
类 transformers.models.longformer.modeling_longformer.LongformerMultipleChoiceModelOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape (1,), optional, 当提供labels
时返回) — 分类损失. - logits (
torch.FloatTensor
of shape(batch_size, num_choices)
) — num_choices is the second dimension of the input tensors. (see input_ids above).分类分数(在SoftMax之前)。
- hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
多选Longformer模型输出的基类。
类 transformers.models.longformer.modeling_longformer.LongformerTokenClassifierOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当提供labels
时返回) — 分类损失. - logits (
torch.FloatTensor
of shape(batch_size, sequence_length, config.num_labels)
) — 分类分数(在SoftMax之前)。 - hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftorch.FloatTensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftorch.FloatTensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
用于标记分类模型输出的基类。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerBaseModelOutput
< source >( last_hidden_state: tf.Tensor = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
Longformer 输出的基类,可能包含隐藏状态、局部和全局注意力。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerBaseModelOutputWithPooling
< source >( last_hidden_state: tf.Tensor = None pooler_output: tf.Tensor = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 - pooler_output (
tf.Tensor
of shape(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和Tanh激活函数的进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标进行训练的。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
Longformer 输出的基类,还包含最后隐藏状态的池化。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerMaskedLMOutput
< source >( loss: tf.Tensor | None = None logits: tf.Tensor = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- loss (
tf.Tensor
of shape(1,)
, optional, 当提供labels
时返回) — 掩码语言建模(MLM)损失。 - logits (
tf.Tensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
用于掩码语言模型输出的基类。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerQuestionAnsweringModelOutput
< source >( loss: tf.Tensor | None = None start_logits: tf.Tensor = None end_logits: tf.Tensor = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- loss (
tf.Tensor
of shape(1,)
, optional, returned whenlabels
is provided) — 总跨度提取损失是起始和结束位置的交叉熵之和。 - start_logits (
tf.Tensor
of shape(batch_size, sequence_length)
) — 跨度起始分数(在SoftMax之前)。 - end_logits (
tf.Tensor
of shape(batch_size, sequence_length)
) — 跨度结束分数(在SoftMax之前)。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
用于问答Longformer模型输出的基类。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerSequenceClassifierOutput
< source >( loss: tf.Tensor | None = None logits: tf.Tensor = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 分类(如果 config.num_labels==1 则为回归)损失. - logits (
tf.Tensor
of shape(batch_size, config.num_labels)
) — 分类(如果 config.num_labels==1 则为回归)分数(在 SoftMax 之前)。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
句子分类模型输出的基类。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerMultipleChoiceModelOutput
< source >( 损失: tf.Tensor | None = None 逻辑: tf.Tensor = None 隐藏状态: Tuple[tf.Tensor, ...] | None = None 注意力: Tuple[tf.Tensor, ...] | None = None 全局注意力: Tuple[tf.Tensor, ...] | None = None )
参数
- loss (
tf.Tensor
形状为 (1,), 可选, 当提供labels
时返回) — 分类损失. - logits (
tf.Tensor
of shape(batch_size, num_choices)
) — num_choices is the second dimension of the input tensors. (see input_ids above).分类分数(在SoftMax之前)。
- hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
多选模型输出的基类。
类 transformers.models.longformer.modeling_tf_longformer.TFLongformerTokenClassifierOutput
< source >( loss: tf.Tensor | None = None logits: tf.Tensor = None hidden_states: Tuple[tf.Tensor, ...] | None = None attentions: Tuple[tf.Tensor, ...] | None = None global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 分类损失. - logits (
tf.Tensor
of shape(batch_size, sequence_length, config.num_labels)
) — 分类分数(在SoftMax之前)。 - hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) — Tuple oftf.Tensor
(one for the output of the embeddings + one for the output of each layer) of shape(batch_size, sequence_length, hidden_size)
.模型在每一层输出处的隐藏状态加上初始嵌入输出。
- attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x + attention_window + 1)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的`attention_window`)的注意力权重。- 1
values). Note that the first
xvalues refer to tokens with fixed positions in the text, but the remaining
attention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at index
x + attention_window / 2and the
attention_window / 2preceding (succeeding) values are the attention weights to the
attention_window / 2preceding (succeeding) tokens. If the attention window contains a token with global attention, the attention weight at the corresponding index is set to 0; the value should be accessed from the first
xattention weights. If a token has global attention, the attention weights to all other tokens in
attentionsis set to 0, the values should be accessed from
global_attentions`.
- 1
- global_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) — Tuple oftf.Tensor
(one for each layer) of shape(batch_size, num_heads, sequence_length, x)
, wherex
is the number of tokens with global attention mask.在注意力softmax之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
用于标记分类模型输出的基类。
LongformerModel
类 transformers.LongformerModel
< source >( config add_pooling_layer = True )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的Longformer模型输出原始隐藏状态,没有任何特定的头部。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
该类从RobertaModel复制了代码,并用长格式自注意力覆盖了标准的自注意力,以提供处理长序列的能力,遵循了Iz Beltagy、Matthew E. Peters和Arman Cohan在Longformer: the Long-Document Transformer中描述的自注意力方法。长格式自注意力结合了局部(滑动窗口)和全局注意力,以扩展到长文档,而不会导致内存和计算的O(n^2)增加。
这里实现的LongformerSelfAttention
自注意力模块支持局部和全局注意力的结合,但它缺乏对自回归注意力和扩张注意力的支持。自回归和扩张注意力对于自回归语言建模比在下游任务上的微调更为相关。未来的版本将增加对自回归注意力的支持,但对扩张注意力的支持需要自定义的CUDA内核以实现内存和计算效率。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None global_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None inputs_embeds: 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.models.longformer.modeling_longformer.LongformerBaseModelOutputWithPooling 或 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.
- global_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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]
. - 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
, optional) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.models.longformer.modeling_longformer.LongformerBaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一个 transformers.models.longformer.modeling_longformer.LongformerBaseModelOutputWithPooling 或一个包含各种元素的 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),具体取决于配置(LongformerConfig)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
形状为(batch_size, hidden_size)
) — 序列的第一个标记(分类标记)的最后一层隐藏状态,经过线性层和 Tanh 激活函数进一步处理。线性层的权重是在预训练期间通过下一个句子预测(分类)目标进行训练的。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(一个用于嵌入的输出,一个用于每一层的输出)。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, x + attention_window + 1)
的torch.FloatTensor
元组(每一层一个),其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是序列中每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x个值指的是文本中位置固定的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记到自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2个前(后)值是到
attention_window / 2个前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x个注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, x)
的torch.FloatTensor
元组(每一层一个),其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是具有全局注意力的每个标记到序列中每个标记的注意力权重。
LongformerModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> import torch
>>> from transformers import LongformerModel, AutoTokenizer
>>> model = LongformerModel.from_pretrained("allenai/longformer-base-4096")
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> SAMPLE_TEXT = " ".join(["Hello world! "] * 1000) # long input document
>>> input_ids = torch.tensor(tokenizer.encode(SAMPLE_TEXT)).unsqueeze(0) # batch of size 1
>>> attention_mask = torch.ones(
... input_ids.shape, dtype=torch.long, device=input_ids.device
... ) # initialize to local attention
>>> global_attention_mask = torch.zeros(
... input_ids.shape, dtype=torch.long, device=input_ids.device
... ) # initialize to global attention to be deactivated for all tokens
>>> global_attention_mask[
... :,
... [
... 1,
... 4,
... 21,
... ],
... ] = 1 # Set global attention to random tokens for the sake of this example
>>> # Usually, set global attention based on the task. For example,
>>> # classification: the <s> token
>>> # QA: question tokens
>>> # LM: potentially on the beginning of sentences and paragraphs
>>> outputs = model(input_ids, attention_mask=attention_mask, global_attention_mask=global_attention_mask)
>>> sequence_output = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output
LongformerForMaskedLM
类 transformers.LongformerForMaskedLM
< source >( config )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有language modeling
头。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None global_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: 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.models.longformer.modeling_longformer.LongformerMaskedLMOutput 或 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.
- global_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在编码器中取消选择注意力模块中的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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]
. - 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]
范围内的标记进行计算 - kwargs (
Dict[str, any]
, 可选, 默认为{}
) — 用于隐藏已被弃用的旧参数.
返回
transformers.models.longformer.modeling_longformer.LongformerMaskedLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.longformer.modeling_longformer.LongformerMaskedLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LongformerConfig)和输入。
-
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, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)。请注意,前
x个值指的是文本中固定位置的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记对其自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2个前(后)值是到
attention_window / 2个前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x个注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, x)
, 其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中每个标记的注意力权重。
LongformerForMaskedLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
掩码填充示例:
>>> from transformers import AutoTokenizer, LongformerForMaskedLM
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = LongformerForMaskedLM.from_pretrained("allenai/longformer-base-4096")
让我们尝试一个非常长的输入。
>>> TXT = (
... "My friends are <mask> but they eat too many carbs."
... + " That's why I decide not to eat with them." * 300
... )
>>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
>>> logits = model(input_ids).logits
>>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
>>> probs = logits[0, masked_index].softmax(dim=0)
>>> values, predictions = probs.topk(5)
>>> tokenizer.decode(predictions).split()
['healthy', 'skinny', 'thin', 'good', 'vegetarian']
LongformerForSequenceClassification
类 transformers.LongformerForSequenceClassification
< source >( config )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 GLUE 任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None global_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: 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.models.longformer.modeling_longformer.LongformerSequenceClassifierOutput 或 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.
- global_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在解码器中取消选择注意力模块的头部。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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]
. - 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,)
, optional) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels == 1
,则计算回归损失(均方损失),如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回
transformers.models.longformer.modeling_longformer.LongformerSequenceClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.longformer.modeling_longformer.LongformerSequenceClassifierOutput 或一个包含各种元素的 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),具体取决于配置(LongformerConfig)和输入。
-
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, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)和到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x值指的是文本中固定位置的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记对其自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2前(后)的值是对
attention_window / 2前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x注意力权重中访问。如果一个标记具有全局注意力,则对
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中的每个标记的注意力权重。
LongformerForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
单标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, LongformerForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("jpwahle/longformer-base-plagiarism-detection")
>>> model = LongformerForSequenceClassification.from_pretrained("jpwahle/longformer-base-plagiarism-detection")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
'ORIGINAL'
>>> # 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 = LongformerForSequenceClassification.from_pretrained("jpwahle/longformer-base-plagiarism-detection", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
5.44
多标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, LongformerForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("jpwahle/longformer-base-plagiarism-detection")
>>> model = LongformerForSequenceClassification.from_pretrained("jpwahle/longformer-base-plagiarism-detection", 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 = LongformerForSequenceClassification.from_pretrained(
... "jpwahle/longformer-base-plagiarism-detection", 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
LongformerForMultipleChoice
类 transformers.LongformerForMultipleChoice
< source >( config )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有多项选择分类头(在池化输出之上的线性层和 softmax),例如用于 RocStories/SWAG 任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None global_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.Tensor] = None inputs_embeds: 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.models.longformer.modeling_longformer.LongformerMultipleChoiceModelOutput 或 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.
- global_attention_mask (
torch.FloatTensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- head_mask (
torch.Tensor
形状为(num_layers, num_heads)
, 可选) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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]
. - inputs_embeds (
torch.FloatTensor
of shape(batch_size, num_choices, 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,)
, optional) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices-1]
范围内,其中num_choices
是输入张量第二维的大小。(参见上面的input_ids
)
返回
transformers.models.longformer.modeling_longformer.LongformerMultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.longformer.modeling_longformer.LongformerMultipleChoiceModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LongformerConfig)和输入。
-
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, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x个值指的是文本中位置固定的标记,但剩余的
attention_window + 1个值指的是相对位置的标记:一个标记对其自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2个前(后)值是到
attention_window / 2个前(后)标记的注意力权重。如果注意力窗口包含一个具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x个注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x)
, 其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中的每个标记的注意力权重。
LongformerForMultipleChoice 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, LongformerForMultipleChoice
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = LongformerForMultipleChoice.from_pretrained("allenai/longformer-base-4096")
>>> 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
LongformerForTokenClassification
类 transformers.LongformerForTokenClassification
< source >( config )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None global_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: 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.models.longformer.modeling_longformer.LongformerTokenClassifierOutput 或 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.
- global_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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]
. - 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.models.longformer.modeling_longformer.LongformerTokenClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.longformer.modeling_longformer.LongformerTokenClassifierOutput 或一个包含各种元素的 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),具体取决于配置(LongformerConfig)和输入。
-
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, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x值指的是文本中位置固定的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记对自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2前(后)的值是对
attention_window / 2前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x注意力权重中访问。如果一个标记具有全局注意力,则对
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中每个标记的注意力权重。
LongformerForTokenClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, LongformerForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("brad1141/Longformer-finetuned-norm")
>>> model = LongformerForTokenClassification.from_pretrained("brad1141/Longformer-finetuned-norm")
>>> 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]]
>>> predicted_tokens_classes
['Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence', 'Evidence']
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
0.63
LongformerForQuestionAnswering
类 transformers.LongformerForQuestionAnswering
< source >( config )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有用于抽取式问答任务(如 SQuAD / TriviaQA)的跨度分类头(在隐藏状态输出之上的线性层,用于计算 span start logits
和 span end logits
)。
该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None global_attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None token_type_ids: typing.Optional[torch.Tensor] = None position_ids: 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.models.longformer.modeling_longformer.LongformerQuestionAnsweringModelOutput 或 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.
- global_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- head_mask (
torch.Tensor
形状为(num_layers, num_heads)
, 可选) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(num_layers, num_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- 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]
. - 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而不是一个普通的元组。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会用于计算损失。 - end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length
)。序列之外的位置不会被考虑用于计算损失。
返回
transformers.models.longformer.modeling_longformer.LongformerQuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.models.longformer.modeling_longformer.LongformerQuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LongformerConfig)和输入。
-
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, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是序列中每个标记到每个具有全局注意力的标记(前
x
个值)和到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x值指的是文本中固定位置的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记到自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2前(后)的值是到
attention_window / 2前(后)标记的注意力权重。如果注意力窗口包含一个具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, x)
, 其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是每个具有全局注意力的标记到序列中每个标记的注意力权重。
LongformerForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, LongformerForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-large-4096-finetuned-triviaqa")
>>> model = LongformerForQuestionAnswering.from_pretrained("allenai/longformer-large-4096-finetuned-triviaqa")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> encoding = tokenizer(question, text, return_tensors="pt")
>>> input_ids = encoding["input_ids"]
>>> # default is local attention everywhere
>>> # the forward method will automatically set global attention on question tokens
>>> attention_mask = encoding["attention_mask"]
>>> outputs = model(input_ids, attention_mask=attention_mask)
>>> start_logits = outputs.start_logits
>>> end_logits = outputs.end_logits
>>> all_tokens = tokenizer.convert_ids_to_tokens(input_ids[0].tolist())
>>> answer_tokens = all_tokens[torch.argmax(start_logits) : torch.argmax(end_logits) + 1]
>>> answer = tokenizer.decode(
... tokenizer.convert_tokens_to_ids(answer_tokens)
... ) # remove space prepending space token
TFLongformerModel
类 transformers.TFLongformerModel
< source >( config *inputs **kwargs )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的Longformer模型输出原始隐藏状态,没有任何特定的头部。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
这个类从TFRobertaModel复制代码,并用长格式自注意力覆盖标准自注意力,以提供处理长序列的能力,遵循Iz Beltagy、Matthew E. Peters和Arman Cohan在Longformer: the Long-Document Transformer中描述的自注意力方法。长格式自注意力结合了局部(滑动窗口)和全局注意力,以扩展到长文档,而不会导致内存和计算的O(n^2)增加。
这里实现的self-attention模块TFLongformerSelfAttention
支持局部和全局注意力的结合,但它缺乏对自回归注意力和扩张注意力的支持。自回归和扩张注意力对于自回归语言建模比在下游任务上的微调更为相关。未来的版本将增加对自回归注意力的支持,但对扩张注意力的支持需要自定义的CUDA内核以实现内存和计算效率。
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False )
参数
- input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
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.
- head_mask (
np.ndarray
或tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- global_attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- token_type_ids (
np.ndarray
ortf.Tensor
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 (
np.ndarray
ortf.Tensor
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]
. - inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估之间有不同的行为)。
TFLongformerModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
TFLongformerForMaskedLM
类 transformers.TFLongformerForMaskedLM
< source >( config *inputs **kwargs )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有language modeling
头。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.models.longformer.modeling_tf_longformer.TFLongformerMaskedLMOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
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.
- head_mask (
np.ndarray
或tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- global_attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- token_type_ids (
np.ndarray
ortf.Tensor
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 (
np.ndarray
ortf.Tensor
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]
. - inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
形状为(batch_size, sequence_length)
, 可选) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]
范围内(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略(掩码), 损失仅针对标签在[0, ..., config.vocab_size]
范围内的标记进行计算
返回
transformers.models.longformer.modeling_tf_longformer.TFLongformerMaskedLMOutput 或 tuple(tf.Tensor)
一个 transformers.models.longformer.modeling_tf_longformer.TFLongformerMaskedLMOutput 或一个包含各种元素的 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),具体取决于配置(LongformerConfig)和输入。
-
loss (
tf.Tensor
形状为(1,)
,可选,当提供labels
时返回) — 掩码语言建模(MLM)损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇标记的分数)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, x + attention_window + 1)
的tf.Tensor
元组(每层一个),其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x值指的是文本中固定位置的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记到自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2前(后)的值是到
attention_window / 2前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, x)
的tf.Tensor
元组(每层一个),其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中每个标记的注意力权重。
TFLongformerForMaskedLM 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLongformerForMaskedLM
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = TFLongformerForMaskedLM.from_pretrained("allenai/longformer-base-4096")
>>> inputs = tokenizer("The capital of France is <mask>.", return_tensors="tf")
>>> logits = model(**inputs).logits
>>> # retrieve index of <mask>
>>> mask_token_index = tf.where((inputs.input_ids == tokenizer.mask_token_id)[0])
>>> selected_logits = tf.gather_nd(logits[0], indices=mask_token_index)
>>> predicted_token_id = tf.math.argmax(selected_logits, axis=-1)
>>> tokenizer.decode(predicted_token_id)
' Paris'
TFLongformerForQuestionAnswering
类 transformers.TFLongformerForQuestionAnswering
< source >( config *inputs **kwargs )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有用于抽取式问答任务(如 SQuAD / TriviaQA)的跨度分类头(在隐藏状态输出之上的线性层,用于计算 span start logits
和 span end logits
)。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None start_positions: np.ndarray | tf.Tensor | None = None end_positions: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.models.longformer.modeling_tf_longformer.TFLongformerQuestionAnsweringModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
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.
- head_mask (
np.ndarray
或tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- global_attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- token_type_ids (
np.ndarray
ortf.Tensor
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 (
np.ndarray
ortf.Tensor
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]
. - inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估时具有不同的行为)。 - start_positions (
tf.Tensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置 不会被考虑用于计算损失。 - end_positions (
tf.Tensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
返回
transformers.models.longformer.modeling_tf_longformer.TFLongformerQuestionAnsweringModelOutput 或 tuple(tf.Tensor)
一个 transformers.models.longformer.modeling_tf_longformer.TFLongformerQuestionAnsweringModelOutput 或一个 tf.Tensor
的元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置 (LongformerConfig) 和输入的各种元素。
-
loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。 -
start_logits (
tf.Tensor
形状为(batch_size, sequence_length)
) — 跨度起始分数(在 SoftMax 之前)。 -
end_logits (
tf.Tensor
形状为(batch_size, sequence_length)
) — 跨度结束分数(在 SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
的元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
的元组(每层一个)形状为(batch_size, num_heads, sequence_length, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是序列中每个标记到具有全局注意力的每个标记(前
x
个值)和到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)。请注意,前
x个值指的是文本中固定位置的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记到自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2前(后)的值是到
attention_window / 2前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
的元组(每层一个)形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是每个具有全局注意力的标记到序列中每个标记的注意力权重。
TFLongformerForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLongformerForQuestionAnswering
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-large-4096-finetuned-triviaqa")
>>> model = TFLongformerForQuestionAnswering.from_pretrained("allenai/longformer-large-4096-finetuned-triviaqa")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="tf")
>>> outputs = model(**inputs)
>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> tokenizer.decode(predict_answer_tokens)
' puppet'
TFLongformerForSequenceClassification
类 transformers.TFLongformerForSequenceClassification
< source >( config *inputs **kwargs )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型转换器,顶部带有序列分类/回归头(在池化输出之上的线性层),例如用于 GLUE 任务。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.models.longformer.modeling_tf_longformer.TFLongformerSequenceClassifierOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
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.
- head_mask (
np.ndarray
或tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于屏蔽注意力模块中选定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部未被屏蔽,
- 0 表示头部被屏蔽。
- global_attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- token_type_ids (
np.ndarray
ortf.Tensor
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 (
np.ndarray
ortf.Tensor
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]
. - inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(某些模块如 dropout 模块在训练和评估之间有不同的行为)。
返回
transformers.models.longformer.modeling_tf_longformer.TFLongformerSequenceClassifierOutput 或 tuple(tf.Tensor)
一个 transformers.models.longformer.modeling_tf_longformer.TFLongformerSequenceClassifierOutput 或一个由 tf.Tensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含根据配置(LongformerConfig)和输入的各种元素。
-
loss (
tf.Tensor
形状为(1,)
,可选,当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
logits (
tf.Tensor
形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由tf.Tensor
组成的元组(一个用于嵌入层的输出,一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x值指的是文本中位置固定的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记对其自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2前(后)的值是对
attention_window / 2前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x注意力权重中访问。如果一个标记具有全局注意力,则对
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中的每个标记的注意力权重。
TFLongformerForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLongformerForSequenceClassification
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = TFLongformerForSequenceClassification.from_pretrained("allenai/longformer-base-4096")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> logits = model(**inputs).logits
>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = TFLongformerForSequenceClassification.from_pretrained("allenai/longformer-base-4096", num_labels=num_labels)
>>> labels = tf.constant(1)
>>> loss = model(**inputs, labels=labels).loss
TFLongformerForTokenClassification
类 transformers.TFLongformerForTokenClassification
< source >( config *inputs **kwargs )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: Optional[Union[np.array, tf.Tensor]] = None training: Optional[bool] = False ) → transformers.models.longformer.modeling_tf_longformer.TFLongformerTokenClassifierOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
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.
- head_mask (
np.ndarray
或tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- global_attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- token_type_ids (
np.ndarray
ortf.Tensor
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 (
np.ndarray
ortf.Tensor
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]
. - inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。这个参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(某些模块如dropout模块在训练和评估时具有不同的行为)。 - labels (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于计算令牌分类损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。
返回
transformers.models.longformer.modeling_tf_longformer.TFLongformerTokenClassifierOutput 或 tuple(tf.Tensor)
一个 transformers.models.longformer.modeling_tf_longformer.TFLongformerTokenClassifierOutput 或一个由 tf.Tensor
组成的元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置 (LongformerConfig) 和输入的各种元素。
-
loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 分类损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.num_labels)
) — 分类分数(在 SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由tf.Tensor
组成的元组(一个用于嵌入层的输出 + 一个用于每一层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是从序列中的每个标记到具有全局注意力的每个标记(前
x
个值)以及到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x个值指的是文本中固定位置的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记对其自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2个前(后)值是到
attention_window / 2个前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x个注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每一层一个),形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从具有全局注意力的每个标记到序列中的每个标记的注意力权重。
TFLongformerForTokenClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLongformerForTokenClassification
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = TFLongformerForTokenClassification.from_pretrained("allenai/longformer-base-4096")
>>> inputs = tokenizer(
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="tf"
... )
>>> logits = model(**inputs).logits
>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-1)
>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t] for t in predicted_token_class_ids[0].numpy().tolist()]
TFLongformerForMultipleChoice
类 transformers.TFLongformerForMultipleChoice
< source >( config *inputs **kwargs )
参数
- config (LongformerConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,顶部带有多项选择分类头(在池化输出之上的线性层和 softmax),例如用于 RocStories/SWAG 任务。
该模型继承自 TFPreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个keras.Model子类。可以将其作为常规的TF 2.0 Keras模型使用,并参考TF 2.0文档以了解与一般使用和行为相关的所有事项。
TensorFlow 模型和层在 transformers
中接受两种格式作为输入:
- 将所有输入作为关键字参数(如PyTorch模型),或
- 将所有输入作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用像 model.fit()
这样的方法时,事情应该“正常工作”——只需以 model.fit()
支持的任何格式传递你的输入和标签!然而,如果你想在 Keras 方法之外使用第二种格式,比如在使用 Keras Functional
API 创建自己的层或模型时,有三种方法可以用来将所有输入张量收集到第一个位置参数中:
- 仅包含
input_ids
的单个张量,没有其他内容:model(input_ids)
- 一个长度不定的列表,包含一个或多个输入张量,按照文档字符串中给出的顺序:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,包含一个或多个与文档字符串中给出的输入名称相关联的输入张量:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用子类化创建模型和层时,您不需要担心这些,因为您可以像传递任何其他Python函数一样传递输入!
调用
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None token_type_ids: np.ndarray | tf.Tensor | None = None position_ids: np.ndarray | tf.Tensor | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.models.longformer.modeling_tf_longformer.TFLongformerMultipleChoiceModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
np.ndarray
ortf.Tensor
of shape(batch_size, num_choices, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()和 PreTrainedTokenizer.encode()。
- attention_mask (
np.ndarray
ortf.Tensor
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.
- head_mask (
np.ndarray
或tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- global_attention_mask (
np.ndarray
ortf.Tensor
of shape(batch_size, num_choices, sequence_length)
, optional) — Mask to decide the attention given on each token, local attention or global attention. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is important for task-specific finetuning because it makes the model more flexible at representing the task. For example, for classification, thetoken should be given global attention. For QA, all question tokens should also have global attention. Please refer to the Longformer paper for more details. Mask values selected in[0, 1]
:- 0 for local attention (a sliding window attention),
- 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- token_type_ids (
np.ndarray
ortf.Tensor
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 (
np.ndarray
ortf.Tensor
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]
. - inputs_embeds (
np.ndarray
或tf.Tensor
形状为(batch_size, num_choices, sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在急切模式下使用,在图形模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。 - labels (
tf.Tensor
形状为(batch_size,)
, 可选) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices]
范围内, 其中num_choices
是输入张量第二维的大小。(参见上面的input_ids
)
返回
transformers.models.longformer.modeling_tf_longformer.TFLongformerMultipleChoiceModelOutput 或 tuple(tf.Tensor)
一个 transformers.models.longformer.modeling_tf_longformer.TFLongformerMultipleChoiceModelOutput 或一个由 tf.Tensor
组成的元组(如果
return_dict=False
被传递或当 config.return_dict=False
时),包含根据配置 (LongformerConfig) 和输入而定的各种元素。
-
loss (
tf.Tensor
形状为 (1,), 可选, 当提供labels
时返回) — 分类损失。 -
logits (
tf.Tensor
形状为(batch_size, num_choices)
) — num_choices 是输入张量的第二维度。(见上面的 input_ids)。分类分数(在 SoftMax 之前)。
-
hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由tf.Tensor
组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态加上初始嵌入输出。
-
attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的局部注意力权重,用于计算自注意力头中的加权平均值。这些是序列中每个标记到具有全局注意力的每个标记(前
x
个值)和到注意力窗口中的每个标记(剩余的 `attention_window- 1
值)的注意力权重。请注意,前
x个值指的是文本中位置固定的标记,但剩余的
attention_window + 1值指的是相对位置的标记:一个标记到自身的注意力权重位于索引
x + attention_window / 2处,而
attention_window / 2个前(后)值是到
attention_window / 2个前(后)标记的注意力权重。如果注意力窗口包含具有全局注意力的标记,则相应索引处的注意力权重设置为 0;该值应从第一个
x个注意力权重中访问。如果一个标记具有全局注意力,则到
attentions中所有其他标记的注意力权重设置为 0,这些值应从
global_attentions` 中访问。
- 1
-
global_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) — 由tf.Tensor
组成的元组(每层一个),形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。在注意力 softmax 之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是每个具有全局注意力的标记到序列中每个标记的注意力权重。
TFLongformerForMultipleChoice 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLongformerForMultipleChoice
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = TFLongformerForMultipleChoice.from_pretrained("allenai/longformer-base-4096")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="tf", padding=True)
>>> inputs = {k: tf.expand_dims(v, 0) for k, v in encoding.items()}
>>> outputs = model(inputs) # batch size is 1
>>> # the linear classifier still needs to be trained
>>> logits = outputs.logits