Transformers documentation
Longformer
该模型于 2020-04-10 在 HF papers 上发布,并于 2020-11-16 贡献给 Hugging Face Transformers。
Longformer
Longformer 是一种专为处理长文档而设计的 Transformer 模型。自注意力操作的计算复杂度通常随序列长度呈二次方增长,这限制了 Transformer 处理更长序列的能力。Longformer 的注意力机制通过使计算复杂度随序列长度线性增长来克服这一限制。它将局部窗口注意力与特定任务的全局注意力相结合,从而能够高效处理包含数千个 token 的文档。
您可以在 Ai2 组织下找到所有原始的 Longformer 检查点。
点击右侧边栏中的 Longformer 模型,以查看更多将 Longformer 应用于不同语言任务的示例。
下面的示例演示了如何使用 Pipeline、AutoModel 以及命令行来填充 <mask> 标记。
from transformers import pipeline
pipeline = pipeline(
task="fill-mask",
model="allenai/longformer-base-4096",
device=0
)
pipeline("""San Francisco 49ers cornerback Shawntae Spencer will miss the rest of the <mask> with a torn ligament in his left knee.
Spencer, a fifth-year pro, will be placed on injured reserve soon after undergoing surgery Wednesday to repair the ligament. He injured his knee late in the 49ers’ road victory at Seattle on Sept. 14, and missed last week’s victory over Detroit.
Tarell Brown and Donald Strickland will compete to replace Spencer with the 49ers, who kept 12 defensive backs on their 53-man roster to start the season. Brown, a second-year pro, got his first career interception last weekend while filling in for Strickland, who also sat out with a knee injury.""")from transformers import AutoModelForMaskedLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
model = AutoModelForMaskedLM.from_pretrained("allenai/longformer-base-4096", device_map="auto")
text = (
"""
San Francisco 49ers cornerback Shawntae Spencer will miss the rest of the <mask> with a torn ligament in his left knee.
Spencer, a fifth-year pro, will be placed on injured reserve soon after undergoing surgery Wednesday to repair the ligament. He injured his knee late in the 49ers’ road victory at Seattle on Sept. 14, and missed last week’s victory over Detroit.
Tarell Brown and Donald Strickland will compete to replace Spencer with the 49ers, who kept 12 defensive backs on their 53-man roster to start the season. Brown, a second-year pro, got his first career interception last weekend while filling in for Strickland, who also sat out with a knee injury.
"""
)
input_ids = tokenizer([text], return_tensors="pt").to(model.device)["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()备注
Longformer 基于 RoBERTa,不包含
token_type_ids。您无需指明每个 token 属于哪个片段,只需使用分隔符</s>或tokenizer.sep_token来分隔各个片段即可。在推理时,您可以通过
global_attention_mask设置哪些 token 进行局部注意力,哪些 token 进行全局注意力(更多详情请参见此 示例)。值为0表示该 token 进行局部注意力,值为1表示该 token 进行全局注意力。LongformerForMaskedLM 的训练方式与 RobertaForMaskedLM 相同,应如下所示使用。
input_ids = tokenizer.encode("This is a sentence from [MASK] training data", return_tensors="pt").to(model.device) mlm_labels = tokenizer.encode("This is a sentence from the training data", return_tensors="pt").to(model.device) loss = model(input_ids, labels=input_ids, masked_lm_labels=mlm_labels)[0]
LongformerConfig
class transformers.LongformerConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Noneattention_window: list[int] | int = 512sep_token_id: int | None = 2pad_token_id: int | None = 1bos_token_id: int | None = 0eos_token_id: int | list[int] | None = 2vocab_size: int = 30522hidden_size: int = 768num_hidden_layers: int = 12num_attention_heads: int = 12intermediate_size: int = 3072hidden_act: str = 'gelu'hidden_dropout_prob: float | int = 0.1attention_probs_dropout_prob: float | int = 0.1max_position_embeddings: int = 512type_vocab_size: int = 2initializer_range: float = 0.02layer_norm_eps: float = 1e-12onnx_export: bool = Falsetie_word_embeddings: bool = True )
参数
- attention_window (
int或list[int],可选,默认值为 512) — 每个 token 周围的注意力窗口大小。如果为int,则所有层使用相同的大小。若要为每一层指定不同的窗口大小,请使用list[int],其中len(attention_window) == num_hidden_layers。 - sep_token_id (
int,可选,默认为2) — 词汇表中用于分隔符的 Token id。 - pad_token_id (
int,可选,默认为1) — 词表中用于填充的 token id。 - bos_token_id (
int,可选,默认为0) — 词汇表中用于表示流起始的 Token id。 - eos_token_id (
Union[int, list[int]],可选,默认为2) — 词汇表中用于表示流结束(end-of-stream)的 token id。 - vocab_size (
int,可选,默认为30522) — 模型的词汇表大小。定义了input_ids可以表示的不同 token 数量。 - hidden_size (
int,可选,默认为768) — 隐藏表示的维度。 - num_hidden_layers (
int, 可选, 默认为12) — Transformer 解码器中的隐藏层数量。 - num_attention_heads (
int,可选,默认为12) — Transformer 解码器中每个注意力层的注意力头数量。 - intermediate_size (
int,可选,默认为3072) — MLP 表示的维度。 - hidden_act (
str,可选,默认为gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu"等。 - hidden_dropout_prob (
Union[float, int],可选,默认为0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。 - attention_probs_dropout_prob (
Union[float, int],可选,默认为0.1) — 注意力概率的 dropout 比率。 - max_position_embeddings (
int,可选,默认为512) — 该模型可能使用的最大序列长度。 - type_vocab_size (
int,可选,默认为2) —token_type_ids的词汇表大小。 - initializer_range (
float,可选,默认为0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float,可选,默认为1e-12) — 层归一化层所使用的 epsilon 值。 - onnx_export (
bool,可选,默认为 False) — 是否创建一个支持 ONNX 导出的模型。 - tie_word_embeddings (
bool,可选,默认为True) — 是否根据模型的tied_weights_keys映射来绑定权重嵌入。
这是用于存储 LongformerModel 配置的类。它根据指定的参数实例化 Longformer 模型,并定义模型架构。使用默认值实例化配置将生成与 allenai/longformer-base-4096 类似的配置。
配置对象继承自 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.configLongformerTokenizer
class transformers.RobertaTokenizer
< source >( vocab: str | dict[str, int] | None = Nonemerges: str | list[str] | None = Noneerrors: str = 'replace'bos_token: str = '<s>'eos_token: str = '</s>'sep_token: str = '</s>'cls_token: str = '<s>'unk_token: str = '<unk>'pad_token: str = '<pad>'mask_token: str = '<mask>'add_prefix_space: bool = Falsetrim_offsets: bool = True**kwargs )
参数
- vocab (
str、dict或list,可选) — 自定义词汇表。如果未提供,则从 vocab_file 加载词汇表。 - merges(
str或list,可选)— 自定义 merges 列表。如果未提供,则从 merges_file 加载 merges。 - errors (
str,可选,默认为"replace") — 将字节解码为 UTF-8 时遵循的策略。更多信息请参阅 bytes.decode。 - bos_token (
str, 可选, 默认为"<s>") — 预训练期间使用的序列起始标记。也可用作序列分类标记。在构建序列时,如果使用了特殊标记,序列开头使用的并不是这个标记。实际使用的标记是
cls_token。 - eos_token (
str, 可选, 默认为"</s>") — 序列结束标记。在构建包含特殊标记的序列时,序列结束使用的并非此标记,而是 sep_token。在构建包含特殊标记的序列时,序列末尾使用的并不是这个标记。 实际使用的是
sep_token。 - sep_token (
str,可选,默认为"</s>") — 分隔符 token,用于从多个序列构建序列时,例如用于序列分类的两个序列,或用于问答的文本和问题。它也用作使用特殊 token 构建的序列的最后一个 token。 - cls_token (
str,可选,默认为"<s>") — 用于序列分类(对整个序列进行分类,而非逐 token 分类)的分类器 token。当使用特殊 token 构建序列时,它是序列的第一个 token。 - unk_token (
str,可选,默认为"<unk>") — 未知标记。不在词汇表中的标记无法转换为 ID,因此会被设置为该标记。 - pad_token (
str,可选,默认为"<pad>") — 用于填充的标记,例如在对长度不同的序列进行批处理时。 - mask_token (
str, 可选,默认为"<mask>") — 用于掩码值的标记。这是在以掩码语言建模方式训练该模型时所使用的标记,也是模型将尝试预测的标记。 - add_prefix_space (
bool,可选,默认为False) — 是否要在输入前添加一个初始空格。这样可以将开头的单词视为与其他单词相同。(RoBERTa 分词器通过前面的空格来检测单词的开头)。 - trim_offsets (
bool,可选,默认为True) — 后处理步骤是否应裁剪偏移量,以避免包含空白字符。
构建一个 RoBERTa 分词器(基于 HuggingFace 的 tokenizers 库)。基于字节对编码(Byte-Pair-Encoding)。
该分词器经过训练,将空格视为标记的一部分(类似于 sentencepiece),因此一个单词将
无论是否位于句首(无空格),其编码方式均有所不同:
>>> from transformers import RobertaTokenizer
>>> tokenizer = RobertaTokenizer.from_pretrained("FacebookAI/roberta-base")
>>> 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进行实例化。
该分词器继承自 TokenizersBackend,其中包含了大部分主要方法。用户应参考该父类以获取有关这些方法的更多信息。
Longformer 特定输出
class transformers.models.longformer.modeling_longformer.LongformerBaseModelOutput
< source >( last_hidden_state: Tensorhidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- last_hidden_state (
torch.Tensor,形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。 - hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
Longformer 输出的基类,包含潜在的隐藏状态、局部注意力和全局注意力。
class transformers.models.longformer.modeling_longformer.LongformerBaseModelOutputWithPooling
< source >( last_hidden_state: Tensorpooler_output: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- last_hidden_state (
torch.Tensor,形状为(batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。 - pooler_output (
torch.Tensor,形状为(batch_size, hidden_size)) — 序列中第一个 token(分类 token)的最后一层隐藏状态,经过一个 Linear 层和 Tanh 激活函数进一步处理。该 Linear 层的权重在预训练期间通过下一句预测(分类)目标进行训练。 - hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
Longformer 输出的基类,同时包含最后一个隐藏状态的池化结果。
class transformers.models.longformer.modeling_longformer.LongformerMaskedLMOutput
< source >( loss: typing.Optional[torch.Tensor] = Nonelogits: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — 掩码语言建模(MLM)损失。 - logits (
torch.Tensor,形状为(batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。 - hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
掩码语言模型输出的基类。
class transformers.models.longformer.modeling_longformer.LongformerQuestionAnsweringModelOutput
< source >( loss: typing.Optional[torch.Tensor] = Nonestart_logits: typing.Optional[torch.Tensor] = Noneend_logits: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — 总跨度提取损失是起始位置和结束位置的交叉熵之和。 - start_logits(形状为
(batch_size, sequence_length)的torch.Tensor,可选)— 跨度起始分数(SoftMax 之前)。 - end_logits(形状为
(batch_size, sequence_length)的torch.Tensor,可选)— 跨度结束分数(SoftMax 之前)。 - hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
问答 Longformer 模型输出的基类。
class transformers.models.longformer.modeling_longformer.LongformerSequenceClassifierOutput
< source >( loss: typing.Optional[torch.Tensor] = Nonelogits: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。 - logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 分类(如果 config.num_labels==1 则为回归)得分(SoftMax 之前)。 - hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
句子分类模型输出的基类。
class transformers.models.longformer.modeling_longformer.LongformerMultipleChoiceModelOutput
< source >( loss: typing.Optional[torch.Tensor] = Nonelogits: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- loss (
torch.Tensor,形状为 (1,),可选,在提供labels时返回) — 分类损失。 - logits (
torch.Tensor形状为(batch_size, num_choices)) — num_choices 是输入张量的第二维。(参见 input_ids )。分类分数(SoftMax 之前)。
- hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
用于多选 Longformer 模型输出的基类。
class transformers.models.longformer.modeling_longformer.LongformerTokenClassifierOutput
< source >( loss: typing.Optional[torch.Tensor] = Nonelogits: typing.Optional[torch.Tensor] = Nonehidden_states: tuple[torch.Tensor, ...] | None = Noneattentions: tuple[torch.Tensor, ...] | None = Noneglobal_attentions: tuple[torch.Tensor, ...] | None = None )
参数
- loss (
torch.Tensor,形状为(1,),可选,在提供labels时返回) — 分类损失。 - logits(形状为
(batch_size, sequence_length, config.num_labels)的torch.Tensor)— 分类分数(SoftMax 之前)。 - hidden_states (
tuple[torch.Tensor, ...], 可选, 在传入output_hidden_states=True或config.output_hidden_states=True) — 的元组torch.Tensor((如果模型有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size).模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
- attentions (
tuple(torch.Tensor), 可选, 在传入output_attentions=True或config.output_attentions=True) — 的元组torch.Tensor((每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1), 其中x是带有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
- global_attentions (
tuple(torch.Tensor), 可选, 当output_attentions=True被传入或config.output_attentions=True) — 元组torch.Tensor(,每个层一个,形状为(batch_size, num_heads, sequence_length, x), ,其中x是带有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
用于标记分类模型输出的基类。
LongformerModel
class transformers.LongformerModel
< source >( config: LongformerConfigadd_pooling_layer = True )
参数
- config (LongformerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
- add_pooling_layer (
bool,可选,默认为True) — 是否添加池化层
未附加任何特定头部的裸 Longformer 模型,输出原始隐藏状态。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneglobal_attention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → LongformerBaseModelOutputWithPooling or tuple(torch.Tensor)
参数
- input_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- global_attention_mask (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 用于决定每个 token 的注意力机制,即局部注意力还是全局注意力的掩码。具有全局注意力的 token 会关注所有其他 token,且所有其他 token 也会关注它们。这对于特定任务的微调非常重要,因为它使模型在表示任务时更加灵活。例如,对于分类任务,token 应被赋予全局注意力。对于问答任务,所有问题 token 也应具有全局注意力。请参阅 Longformer 论文 以获取更多详细信息。掩码值选自[0, 1]:- 0 表示局部注意力(滑动窗口注意力),
- 1 表示全局注意力(这些 token 会关注所有其他 token,且所有其他 token 也会关注它们)。
- token_type_ids (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自[0, 1]:- 0 对应 sentence A 标记,
- 1 对应于 sentence B 标记。
- position_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LongformerBaseModelOutputWithPooling 或 tuple(torch.Tensor)
一个 LongformerBaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(LongformerConfig)和输入。
LongformerModel 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
last_hidden_state(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor)— 模型最后一层输出的隐藏状态序列。pooler_output(形状为
(batch_size, hidden_size)的torch.Tensor)— 序列中第一个 token(分类 token)的最后一层隐藏状态,经过一个 Linear 层和 Tanh 激活函数进一步处理。该 Linear 层的权重在预训练期间通过下一句预测(分类)目标进行训练。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1),其中x为具有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
global_attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x),其中x为具有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
示例:
>>> 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_outputLongformerForMaskedLM
class transformers.LongformerForMaskedLM
< source >( config: LongformerConfig )
参数
- config (LongformerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
带有 language modeling 头的 Longformer 模型。”
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneglobal_attention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → LongformerMaskedLMOutput or tuple(torch.Tensor)
参数
- input_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- global_attention_mask (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 用于决定每个 token 的注意力机制,即局部注意力还是全局注意力的掩码。具有全局注意力的 token 会关注所有其他 token,且所有其他 token 也会关注它们。这对于特定任务的微调非常重要,因为它使模型在表示任务时更加灵活。例如,对于分类任务,token 应被赋予全局注意力。对于问答任务,所有问题 token 也应具有全局注意力。请参阅 Longformer 论文 以获取更多详细信息。掩码值选自[0, 1]:- 0 表示局部注意力(滑动窗口注意力),
- 1 表示全局注意力(这些 token 会关注所有其他 token,且所有其他 token 也会关注它们)。
- token_type_ids (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自[0, 1]:- 0 对应 sentence A 标记,
- 1 对应于 sentence B 标记。
- position_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - labels (
torch.LongTensor,形状为(batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引应在[-100, 0, ..., config.vocab_size]范围内(参见input_ids的文档字符串)。索引设置为-100的 token 将被忽略(即被掩码),损失仅针对标签在[0, ..., config.vocab_size]范围内的 token 进行计算。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LongformerMaskedLMOutput 或 tuple(torch.Tensor)
一个 LongformerMaskedLMOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(LongformerConfig)和输入。
LongformerForMaskedLM 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 掩码语言建模(MLM)损失。logits(形状为
(batch_size, sequence_length, config.vocab_size)的torch.Tensor)— 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1),其中x为具有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
global_attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x),其中x为具有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
示例 Mask 填充:
>>> 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
class transformers.LongformerForSequenceClassification
< source >( config: LongformerConfig )
参数
- config (LongformerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Longformer 模型,在顶部添加了一个序列分类/回归头(在池化输出之上添加了一个线性层),例如用于 GLUE 任务。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneglobal_attention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → LongformerSequenceClassifierOutput or tuple(torch.Tensor)
参数
- input_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- global_attention_mask (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 用于决定每个 token 的注意力机制,即局部注意力还是全局注意力的掩码。具有全局注意力的 token 会关注所有其他 token,且所有其他 token 也会关注它们。这对于特定任务的微调非常重要,因为它使模型在表示任务时更加灵活。例如,对于分类任务,token 应被赋予全局注意力。对于问答任务,所有问题 token 也应具有全局注意力。请参阅 Longformer 论文 以获取更多详细信息。掩码值选自[0, 1]:- 0 表示局部注意力(滑动窗口注意力),
- 1 表示全局注意力(这些 token 会关注所有其他 token,且所有其他 token 也会关注它们)。
- token_type_ids (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自[0, 1]:- 0 对应 sentence A 标记,
- 1 对应于 sentence B 标记。
- position_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - labels (
torch.LongTensor,形状为(batch_size,),可选) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。如果config.num_labels == 1,则计算回归损失(均方损失);如果config.num_labels > 1,则计算分类损失(交叉熵)。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LongformerSequenceClassifierOutput 或 tuple(torch.Tensor)
一个 LongformerSequenceClassifierOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(LongformerConfig)和输入。
LongformerForSequenceClassification 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。logits(形状为
(batch_size, config.num_labels)的torch.Tensor)— 分类(或当 config.num_labels==1 时为回归)得分(SoftMax 之前)。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1),其中x为具有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
global_attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x),其中x为具有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
单标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, LongformerForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = LongformerForSequenceClassification.from_pretrained("allenai/longformer-base-4096")
>>> 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]
...
>>> # 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("allenai/longformer-base-4096", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...多标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, LongformerForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = LongformerForSequenceClassification.from_pretrained("allenai/longformer-base-4096", 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(
... "allenai/longformer-base-4096", 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).lossLongformerForMultipleChoice
class transformers.LongformerForMultipleChoice
< source >( config: LongformerConfig )
参数
- config (LongformerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
在 Longformer 模型顶部添加一个多项选择分类头(即在池化输出之上添加一个线性层和一个 softmax),例如用于 RocStories/SWAG 任务。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneglobal_attention_mask: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → LongformerMultipleChoiceModelOutput or tuple(torch.Tensor)
参数
- input_ids (
torch.LongTensor形状为(batch_size, num_choices, sequence_length)) — 输入序列 token 在词汇表中的索引。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- token_type_ids (
torch.LongTensor形状为(batch_size, num_choices, sequence_length), 可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取值范围为[0, 1]:- 0 对应 sentence A 标记,
- 1 对应于 sentence B 标记。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- global_attention_mask (
torch.Tensor形状为(batch_size, num_choices, sequence_length), 可选) — 用于决定每个 token 的注意力机制,即局部注意力还是全局注意力。具有全局注意力的 token 会关注所有其他 token,且所有其他 token 也会关注它们。这对于任务特定的微调非常重要,因为它使模型在表示任务时更加灵活。例如,对于分类任务,token 应被赋予全局注意力。对于问答任务,所有问题 token 也应具有全局注意力。请参阅 Longformer 论文 以获取更多详细信息。掩码值选自[0, 1]:- 0 表示局部注意力(滑动窗口注意力),
- 1 表示全局注意力(这些 token 会关注所有其他 token,且所有其他 token 也会关注它们)。
- labels(形状为
(batch_size,)的torch.LongTensor,可选) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices-1]范围内,其中num_choices是输入张量第二维的大小。(参见上文中的input_ids) - position_ids (
torch.LongTensor形状为(batch_size, num_choices, sequence_length), ,可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.max_position_embeddings - 1]. - inputs_embeds (
torch.Tensor,形状为(batch_size, num_choices, sequence_length, hidden_size),可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LongformerMultipleChoiceModelOutput 或 tuple(torch.Tensor)
一个 LongformerMultipleChoiceModelOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LongformerConfig)和输入。
LongformerForMultipleChoice 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss(形状为 (1,) 的
torch.Tensor,可选,在提供labels时返回) — 分类损失。logits(形状为
(batch_size, num_choices)的torch.Tensor)— num_choices 是输入张量的第二维(参见上文中的 input_ids)。分类分数(SoftMax 之前)。
hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1),其中x为具有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
global_attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x),其中x为具有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
示例:
>>> 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.logitsLongformerForTokenClassification
class transformers.LongformerForTokenClassification
< source >( config: LongformerConfig )
参数
- config (LongformerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
Longformer 变压器,其顶部带有一个用于命名实体识别(NER)等任务的 token 分类头(即在隐藏状态输出之上的一个线性层)。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneglobal_attention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonelabels: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → LongformerTokenClassifierOutput or tuple(torch.Tensor)
参数
- input_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- global_attention_mask (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 用于决定每个 token 的注意力机制,即局部注意力还是全局注意力的掩码。具有全局注意力的 token 会关注所有其他 token,且所有其他 token 也会关注它们。这对于特定任务的微调非常重要,因为它使模型在表示任务时更加灵活。例如,对于分类任务,token 应被赋予全局注意力。对于问答任务,所有问题 token 也应具有全局注意力。请参阅 Longformer 论文 以获取更多详细信息。掩码值选自[0, 1]:- 0 表示局部注意力(滑动窗口注意力),
- 1 表示全局注意力(这些 token 会关注所有其他 token,且所有其他 token 也会关注它们)。
- token_type_ids (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自[0, 1]:- 0 对应 sentence A 标记,
- 1 对应于 sentence B 标记。
- position_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - labels(形状为
(batch_size, sequence_length)的torch.LongTensor,可选) — 用于计算 token 分类损失的标签。索引应在[0, ..., config.num_labels - 1]范围内。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LongformerTokenClassifierOutput 或 tuple(torch.Tensor)
一个 LongformerTokenClassifierOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(LongformerConfig)和输入。
LongformerForTokenClassification 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss(形状为
(1,)的torch.Tensor,可选,在提供labels时返回) — 分类损失。logits(形状为
(batch_size, sequence_length, config.num_labels)的torch.Tensor)— 分类分数(SoftMax 之前)。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1),其中x为具有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
global_attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x),其中x为具有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
示例:
>>> from transformers import AutoTokenizer, LongformerForTokenClassification
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
>>> model = LongformerForTokenClassification.from_pretrained("allenai/longformer-base-4096")
>>> 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
...
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...LongformerForQuestionAnswering
class transformers.LongformerForQuestionAnswering
< source >( config: LongformerConfig )
参数
- config (LongformerConfig) — 模型的配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。
用于抽取式问答任务(如 SQuAD)的 Longformer 变压器,其顶部带有跨度分类头(在隐藏状态输出之上添加一个线性层,用于计算 span start logits 和 span end logits)。
该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Noneglobal_attention_mask: typing.Optional[torch.Tensor] = Nonetoken_type_ids: typing.Optional[torch.Tensor] = Noneposition_ids: typing.Optional[torch.Tensor] = Noneinputs_embeds: typing.Optional[torch.Tensor] = Nonestart_positions: typing.Optional[torch.Tensor] = Noneend_positions: typing.Optional[torch.Tensor] = Noneoutput_attentions: bool | None = Noneoutput_hidden_states: bool | None = Nonereturn_dict: bool | None = None**kwargs ) → LongformerQuestionAnsweringModelOutput or tuple(torch.Tensor)
参数
- input_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中各 token 在词表中的索引。默认情况下,填充(padding)将被忽略。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自[0, 1]:- 1 表示未被屏蔽的 token,
- 对于被掩码的 token,值为 0。
- global_attention_mask (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 用于决定每个 token 的注意力机制,即局部注意力还是全局注意力的掩码。具有全局注意力的 token 会关注所有其他 token,且所有其他 token 也会关注它们。这对于特定任务的微调非常重要,因为它使模型在表示任务时更加灵活。例如,对于分类任务,token 应被赋予全局注意力。对于问答任务,所有问题 token 也应具有全局注意力。请参阅 Longformer 论文 以获取更多详细信息。掩码值选自[0, 1]:- 0 表示局部注意力(滑动窗口注意力),
- 1 表示全局注意力(这些 token 会关注所有其他 token,且所有其他 token 也会关注它们)。
- token_type_ids (
torch.Tensor形状为(batch_size, sequence_length), ,可选) — 用于指示输入中第一和第二部分的片段标记索引。索引取自[0, 1]:- 0 对应 sentence A 标记,
- 1 对应于 sentence B 标记。
- position_ids (
torch.Tensor形状为(batch_size, sequence_length), 可选) — 输入序列中每个 token 在位置嵌入中的位置索引。取值范围为[0, config.n_positions - 1]. - inputs_embeds(形状为
(batch_size, sequence_length, hidden_size)的torch.Tensor,可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入input_ids。如果您希望对input_ids索引如何转换为相应向量拥有比模型内部嵌入查找矩阵更多的控制权,这将非常有用。 - start_positions (
torch.Tensor,形状为(batch_size,),可选) — 用于计算 token 分类损失的标注片段起始位置(索引)的标签。 位置会被截断到序列长度(sequence_length)。序列之外的位置在计算损失时不予考虑。 - end_positions (
torch.Tensor,形状为(batch_size,),可选) — 用于计算 token 分类损失的标注片段结束位置(索引)的标签。 位置会被截断到序列长度(sequence_length)。序列之外的位置在计算损失时不予考虑。 - output_attentions (
bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量中的attentions。 - output_hidden_states (
bool,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量中的hidden_states。 - return_dict (
bool, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
LongformerQuestionAnsweringModelOutput 或 tuple(torch.Tensor)
一个 LongformerQuestionAnsweringModelOutput 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(LongformerConfig)和输入。
LongformerForQuestionAnswering 的 forward 方法重写了 __call__ 特殊方法。
尽管前向传播的实现需要在此函数中定义,但之后应调用
Module实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。
loss (
torch.Tensor,形状为(1,),可选,当提供labels时返回) — 总跨度提取损失是起始位置和结束位置的交叉熵之和。start_logits(形状为
(batch_size, sequence_length)的torch.Tensor,可选)— 跨度起始分数(SoftMax 之前)。end_logits(形状为
(batch_size, sequence_length)的torch.Tensor,可选)— 跨度结束分数(SoftMax 之前)。hidden_states (
tuple[torch.Tensor, ...],可选,当传入output_hidden_states=True或config.output_hidden_states=True时返回) — 一个torch.Tensor元组(如果模型具有嵌入层,则包含嵌入层输出的一个张量,以及每个层输出的一个张量),形状为(batch_size, sequence_length, hidden_size)。模型在每一层输出处的隐藏状态,以及可选的初始嵌入输出。
attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x + attention_window + 1),其中x为具有全局注意力掩码的 token 数量。自注意力头中用于计算加权平均的局部注意力权重,即注意力 softmax 之后的权重。这些权重包括序列中每个 token 到所有具有全局注意力的 token(前
x个值)以及注意力窗口内每个 token(剩余的 `attention_window- 1
values). Note that the firstxvalues refer to tokens with fixed positions in the text, but the remainingattention_window + 1values refer to tokens with relative positions: the attention weight of a token to itself is located at indexx + attention_window / 2and theattention_window / 2preceding (succeeding) values are the attention weights to theattention_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 firstxattention weights. If a token has global attention, the attention weights to all other tokens inattentionsis set to 0, the values should be accessed fromglobal_attentions`.
- 1
global_attentions (
tuple(torch.Tensor),可选,当传入output_attentions=True或config.output_attentions=True时返回) — 一个torch.Tensor元组(每层一个),形状为(batch_size, num_heads, sequence_length, x),其中x为具有全局注意力掩码的 token 数量。经过注意力 softmax 后的全局注意力权重,用于在自注意力头中计算加权平均值。这些权重表示具有全局注意力的每个 token 到序列中每个 token 的注意力权重。
示例:
>>> 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