LED
概述
LED模型由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-Encoder-Decoder(LED),这是一种支持长文档生成序列到序列任务的Longformer变体,并在arXiv摘要数据集上展示了其有效性。
使用提示
- LEDForConditionalGeneration 是 BartForConditionalGeneration 的扩展,它将传统的 self-attention 层替换为 Longformer 的 chunked self-attention 层。LEDTokenizer 是 BartTokenizer 的别名。
- LED在长距离序列到序列任务中表现非常好,其中
input_ids
的长度远远超过1024个标记。 - LED 在需要时将
input_ids
填充为config.attention_window
的倍数。因此,当 LEDTokenizer 与pad_to_multiple_of
参数一起使用时,可以获得小幅度的加速。 - LED通过
global_attention_mask
(参见LongformerModel)利用全局注意力。对于摘要任务,建议仅在第一个
标记上放置全局注意力。对于问答任务,建议在问题的所有标记上放置全局注意力。 - 要在所有16384个LED上进行微调,如果训练导致内存不足(OOM)错误,可以启用梯度检查点。这可以通过执行
model.gradient_checkpointing_enable()
来实现。此外,可以使用use_cache=False
标志来禁用缓存机制以节省内存。 - LED 是一个带有绝对位置嵌入的模型,因此通常建议在右侧而不是左侧填充输入。
该模型由patrickvonplaten贡献。
资源
LED配置
类 transformers.LEDConfig
< source >( 词汇大小 = 50265 最大编码器位置嵌入 = 16384 最大解码器位置嵌入 = 1024 编码器层数 = 12 编码器前馈网络维度 = 4096 编码器注意力头数 = 16 解码器层数 = 12 解码器前馈网络维度 = 4096 解码器注意力头数 = 16 编码器层丢弃率 = 0.0 解码器层丢弃率 = 0.0 使用缓存 = True 是编码器解码器 = True 激活函数 = 'gelu' 模型维度 = 1024 丢弃率 = 0.1 注意力丢弃率 = 0.0 激活丢弃率 = 0.0 初始化标准差 = 0.02 解码器起始标记ID = 2 分类器丢弃率 = 0.0 填充标记ID = 1 起始标记ID = 0 结束标记ID = 2 注意力窗口: typing.Union[typing.List[int], int] = 512 **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 50265) — LED 模型的词汇表大小。定义了调用 LEDModel 或 TFLEDModel 时传递的inputs_ids
可以表示的不同标记的数量。 - d_model (
int
, optional, 默认为 1024) — 层和池化层的维度。 - encoder_layers (
int
, optional, 默认为 12) — 编码器层数. - decoder_layers (
int
, optional, defaults to 12) — 解码器层数. - encoder_attention_heads (
int
, optional, defaults to 16) — Transformer编码器中每个注意力层的注意力头数量。 - decoder_attention_heads (
int
, optional, defaults to 16) — Transformer解码器中每个注意力层的注意力头数。 - decoder_ffn_dim (
int
, optional, defaults to 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_ffn_dim (
int
, optional, defaults to 4096) — 解码器中“中间”(通常称为前馈)层的维度。 - activation_function (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果是字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - dropout (
float
, optional, defaults to 0.1) — 嵌入层、编码器和池化器中所有全连接层的dropout概率。 - attention_dropout (
float
, optional, 默认为 0.0) — 注意力概率的丢弃比例。 - activation_dropout (
float
, optional, defaults to 0.0) — 全连接层内部激活的丢弃比例。 - classifier_dropout (
float
, optional, defaults to 0.0) — 分类器的丢弃比率。 - max_encoder_position_embeddings (
int
, 可选, 默认为 16384) — 编码器可能使用的最大序列长度。 - max_decoder_position_embeddings (
int
, optional, defaults to 16384) — 解码器可能使用的最大序列长度。 - init_std (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - encoder_layerdrop (
float
, optional, 默认为 0.0) — 编码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](see https://arxiv.org/abs/1909.11556)。 - decoder_layerdrop (
float
, 可选, 默认为 0.0) — 解码器的LayerDrop概率。有关更多详细信息,请参阅[LayerDrop论文](见 https://arxiv.org/abs/1909.11556)。 - use_cache (
bool
, 可选, 默认为True
) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)
这是用于存储LEDModel配置的配置类。它用于根据指定的参数实例化一个LED模型,定义模型架构。使用默认值实例化配置将产生类似于allenai/led-base-16384架构的配置。
配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。
示例:
>>> from transformers import LEDModel, LEDConfig
>>> # Initializing a LED allenai/led-base-16384 style configuration
>>> configuration = LEDConfig()
>>> # Initializing a model from the allenai/led-base-16384 style configuration
>>> model = LEDModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
LEDTokenizer
类 transformers.LEDTokenizer
< 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
, 可选, 默认为"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。" - pad_token (
str
, optional, defaults to"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。" - mask_token (
str
, optional, defaults to"
) — 用于屏蔽值的标记。这是在训练此模型时使用的标记,用于屏蔽语言建模。这是模型将尝试预测的标记。" - add_prefix_space (
bool
, 可选, 默认为False
) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(BART 分词器通过前面的空格检测词的开头)。
构建一个LED分词器,它类似于ROBERTa分词器,使用字节级别的字节对编码。
这个分词器已经被训练成将空格视为标记的一部分(有点像sentencepiece),因此一个单词将会
无论它是否在句子的开头(没有空格),编码方式都会有所不同:
>>> from transformers import LEDTokenizer
>>> tokenizer = LEDTokenizer.from_pretrained("allenai/led-base-16384")
>>> 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]
通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。LED序列具有以下格式:
- 单一序列:
X - 序列对:
AB
get_special_tokens_mask
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) → List[int]
从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model
方法添加特殊标记时,会调用此方法。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递给序列对分类任务的两个序列中创建一个掩码。LED不使用token类型ID,因此返回一个零列表。
LEDTokenizerFast
类 transformers.LEDTokenizerFast
< 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
, 可选, 默认为""
) — 分隔符标记,用于从多个序列构建序列时,例如用于序列分类的两个序列或用于问答的文本和问题。它也用作使用特殊标记构建的序列的最后一个标记。 - cls_token (
str
, 可选, 默认为"
) — 用于序列分类的分类器标记(对整个序列进行分类而不是对每个标记进行分类)。当使用特殊标记构建时,它是序列的第一个标记。" - unk_token (
str
, 可选, 默认为"
) — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。" - pad_token (
str
, optional, defaults to"
) — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。" - mask_token (
str
, 可选, 默认为"
) — 用于屏蔽值的标记。这是在训练此模型时用于屏蔽语言建模的标记。这是模型将尝试预测的标记。" - add_prefix_space (
bool
, 可选, 默认为False
) — 是否在输入前添加一个初始空格。这允许将前导词视为任何其他词。(LED 分词器通过前面的空格检测词的开头)。 - trim_offsets (
bool
, optional, defaults toTrue
) — 后处理步骤是否应修剪偏移量以避免包含空格。
构建一个“快速”的LED分词器(由HuggingFace的tokenizers库支持),该分词器源自GPT-2分词器,使用字节级别的字节对编码。
这个分词器已经被训练成将空格视为标记的一部分(有点像sentencepiece),因此一个单词将会
无论它是否在句子的开头(没有空格),编码方式都会有所不同:
>>> from transformers import LEDTokenizerFast
>>> tokenizer = LEDTokenizerFast.from_pretrained("allenai/led-base-16384")
>>> 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]
从传递给序列对分类任务的两个序列中创建一个掩码。LED不使用token类型ID,因此返回一个零列表。
LED 特定输出
类 transformers.models.led.modeling_led.LEDEncoderBaseModelOutput
< 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之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
LEDEncoder输出的基类,可能包含隐藏状态、局部和全局注意力。
类 transformers.models.led.modeling_led.LEDSeq2SeqModelOutput
< source >( last_hidden_state: FloatTensor = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None decoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the decoder of the model.如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 - past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可以用于(参见
past_key_values
输入)以加速顺序解码。 - decoder_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)
.解码器在每一层输出处的隐藏状态加上初始嵌入输出。
- decoder_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, sequence_length)
.解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- cross_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, sequence_length)
.解码器交叉注意力层的注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
- encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层输出的隐藏状态序列。 - encoder_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)
.编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- encoder_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, sequence_length)
.编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- encoder_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.led.modeling_led.LEDSeq2SeqLMOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None decoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_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.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可以用于(参见
past_key_values
输入)以加速顺序解码。 - decoder_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)
.解码器在每一层输出处的隐藏状态加上初始嵌入输出。
- decoder_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, sequence_length)
.解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- cross_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, sequence_length)
.解码器交叉注意力层的注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
- encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层输出的隐藏状态序列。 - encoder_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)
.编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- encoder_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, sequence_length)
.编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- encoder_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.led.modeling_led.LEDSeq2SeqSequenceClassifierOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None logits: FloatTensor = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None decoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_global_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None )
参数
- loss (
torch.FloatTensor
of shape(1,)
, optional, 当提供label
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 - logits (
torch.FloatTensor
of shape(batch_size, config.num_labels)
) — 分类(如果config.num_labels==1则为回归)得分(在SoftMax之前)。 - past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可以用于(参见
past_key_values
输入)以加速顺序解码。 - decoder_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)
.解码器在每一层输出处的隐藏状态加上初始嵌入输出。
- decoder_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, sequence_length)
.解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- cross_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, sequence_length)
.解码器交叉注意力层的注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
- encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层输出的隐藏状态序列。 - encoder_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)
.编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- encoder_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, sequence_length)
.编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- encoder_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.led.modeling_led.LEDSeq2SeqQuestionAnsweringModelOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None start_logits: FloatTensor = None end_logits: FloatTensor = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None decoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None decoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None cross_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_last_hidden_state: typing.Optional[torch.FloatTensor] = None encoder_hidden_states: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_attentions: typing.Optional[typing.Tuple[torch.FloatTensor, ...]] = None encoder_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之前)。 - past_key_values (
List[torch.FloatTensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftorch.FloatTensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可以用于(参见
past_key_values
输入)以加速顺序解码。 - decoder_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)
.解码器在每一层输出处的隐藏状态加上初始嵌入输出。
- decoder_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, sequence_length)
.解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- cross_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, sequence_length)
.解码器交叉注意力层的注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
- encoder_last_hidden_state (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层输出的隐藏状态序列。 - encoder_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)
.编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- encoder_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, sequence_length)
.编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- encoder_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.led.modeling_tf_led.TFLEDEncoderBaseModelOutput
< 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.led.modeling_tf_led.TFLEDSeq2SeqModelOutput
< source >( last_hidden_state: tf.Tensor = None past_key_values: List[tf.Tensor] | None = None decoder_hidden_states: Tuple[tf.Tensor, ...] | None = None decoder_attentions: Tuple[tf.Tensor, ...] | None = None cross_attentions: Tuple[tf.Tensor, ...] | None = None encoder_last_hidden_state: tf.Tensor | None = None encoder_hidden_states: Tuple[tf.Tensor, ...] | None = None encoder_attentions: Tuple[tf.Tensor, ...] | None = None encoder_global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) — Sequence of hidden-states at the output of the last layer of the decoder of the model.如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 - past_key_values (
List[tf.Tensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftf.Tensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可以用于(参见
past_key_values
输入)以加速顺序解码。 - decoder_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)
.解码器在每一层输出处的隐藏状态加上初始嵌入输出。
- decoder_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, sequence_length)
.解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- cross_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, sequence_length)
.解码器交叉注意力层的注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
- encoder_last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层输出的隐藏状态序列。 - encoder_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)
.编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- encoder_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, sequence_length)
.编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- encoder_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.led.modeling_tf_led.TFLEDSeq2SeqLMOutput
< source >( loss: tf.Tensor | None = None logits: tf.Tensor = None past_key_values: List[tf.Tensor] | None = None decoder_hidden_states: Tuple[tf.Tensor, ...] | None = None decoder_attentions: Tuple[tf.Tensor, ...] | None = None cross_attentions: Tuple[tf.Tensor, ...] | None = None encoder_last_hidden_state: tf.Tensor | None = None encoder_hidden_states: Tuple[tf.Tensor, ...] | None = None encoder_attentions: Tuple[tf.Tensor, ...] | None = None encoder_global_attentions: Tuple[tf.Tensor, ...] | None = None )
参数
- loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 语言建模损失. - logits (
tf.Tensor
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax之前每个词汇标记的分数)。 - past_key_values (
List[tf.Tensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — List oftf.Tensor
of lengthconfig.n_layers
, with each tensor of shape(2, batch_size, num_heads, sequence_length, embed_size_per_head)
).包含解码器的预计算隐藏状态(注意力块中的键和值),这些状态可以用于(参见
past_key_values
输入)以加速顺序解码。 - decoder_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)
.解码器在每一层输出处的隐藏状态加上初始嵌入输出。
- decoder_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, sequence_length)
.解码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- cross_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, sequence_length)
.解码器交叉注意力层的注意力权重,在注意力softmax之后,用于计算交叉注意力头中的加权平均值。
- encoder_last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层输出的隐藏状态序列。 - encoder_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)
.编码器在每一层输出处的隐藏状态加上初始嵌入输出。
- encoder_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, sequence_length)
.编码器的注意力权重,在注意力softmax之后,用于计算自注意力头中的加权平均值。
- encoder_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之后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是从每个具有全局注意力的标记到序列中每个标记的注意力权重。
序列到序列语言模型输出的基类。
LEDModel
类 transformers.LEDModel
< source >( config: LEDConfig )
参数
- config (LEDConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸LED模型输出原始隐藏状态,没有任何特定的头部。 该模型继承自PreTrainedModel。请参阅超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以了解一般用法和行为。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None global_attention_mask: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.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.
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用
LedTokenizer
获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。LED 使用
eos_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.如果你想改变填充行为,你应该阅读
modeling_led._prepare_decoder_inputs
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。 - 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 for the encoder. 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(encoder_layers, encoder_attention_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
形状为(decoder_layers, decoder_attention_heads)
, 可选) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择交叉注意力模块中特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
)last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
, 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力机制中。 - past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, target_sequence_length, hidden_size)
, optional) — Optionally, instead of passingdecoder_input_ids
you can choose to directly pass an embedded representation. Ifpast_key_values
is used, optionally only the lastdecoder_inputs_embeds
have to be input (seepast_key_values
). This is useful if you want more control over how to convertdecoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.如果
decoder_input_ids
和decoder_inputs_embeds
都未设置,decoder_inputs_embeds
将取inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,将返回past_key_values
键值状态,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
返回
transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LEDConfig)和输入。
-
last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层输出的隐藏状态序列。如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递了use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。解码器每层输出的隐藏状态加上可选的初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。编码器每层输出的隐藏状态加上可选的初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor)
, 可选, 当传递了output_attentions=True
或当config.output_attentions=True
时返回) — 由torch.FloatTensor
组成的元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
LEDModel 的 forward 方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, LEDModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> model = LEDModel.from_pretrained("allenai/led-base-16384")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
LEDForConditionalGeneration
类 transformers.LEDForConditionalGeneration
< source >( config: LEDConfig )
参数
- config (LEDConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语言建模头的LED模型。可用于摘要生成。 该模型继承自PreTrainedModel。请参阅超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以了解一般用法和行为。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None global_attention_mask: typing.Optional[torch.FloatTensor] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.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.
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用
LedTokenizer
获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。LED 使用
eos_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.如果你想改变填充行为,你应该阅读
modeling_led._prepare_decoder_inputs
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。 - 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 for the encoder. 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(encoder_layers, encoder_attention_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择交叉注意力模块中特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
)last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
, 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力机制中。 - past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, target_sequence_length, hidden_size)
, optional) — Optionally, instead of passingdecoder_input_ids
you can choose to directly pass an embedded representation. Ifpast_key_values
is used, optionally only the lastdecoder_inputs_embeds
have to be input (seepast_key_values
). This is useful if you want more control over how to convertdecoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.如果
decoder_input_ids
和decoder_inputs_embeds
都未设置,decoder_inputs_embeds
将取inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回的张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算掩码语言建模损失的标签。索引应在[0, ..., config.vocab_size]
或 -100 之间(参见input_ids
文档字符串)。索引设置为-100
的标记将被忽略 (掩码),损失仅针对标签在[0, ..., config.vocab_size]
之间的标记计算。
返回
transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LEDConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 语言建模损失。 -
logits (
torch.FloatTensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
LEDForConditionalGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
条件生成示例:
>>> from transformers import AutoTokenizer, LEDForConditionalGeneration
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> TXT = "My friends are <mask> but they eat too many carbs."
>>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-base-16384")
>>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
>>> prediction = model.generate(input_ids)[0]
>>> print(tokenizer.decode(prediction, skip_special_tokens=True))
摘要示例:
>>> import torch
>>> from transformers import AutoTokenizer, LEDForConditionalGeneration
>>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-large-16384-arxiv")
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-large-16384-arxiv")
>>> ARTICLE_TO_SUMMARIZE = '''Transformers (Vaswani et al., 2017) have achieved state-of-the-art
... results in a wide range of natural language tasks including generative language modeling
... (Dai et al., 2019; Radford et al., 2019) and discriminative ... language understanding (Devlin et al., 2019).
... This success is partly due to the self-attention component which enables the network to capture contextual
... information from the entire sequence. While powerful, the memory and computational requirements of
... self-attention grow quadratically with sequence length, making it infeasible (or very expensive) to
... process long sequences. To address this limitation, we present Longformer, a modified Transformer
... architecture with a self-attention operation that scales linearly with the sequence length, making it
... versatile for processing long documents (Fig 1). This is an advantage for natural language tasks such as
... long document classification, question answering (QA), and coreference resolution, where existing approaches
... partition or shorten the long context into smaller sequences that fall within the typical 512 token limit
... of BERT-style pretrained models. Such partitioning could potentially result in loss of important
... cross-partition information, and to mitigate this problem, existing methods often rely on complex
... architectures to address such interactions. On the other hand, our proposed Longformer is able to build
... contextual representations of the entire context using multiple layers of attention, reducing the need for
... task-specific architectures.'''
>>> inputs = tokenizer.encode(ARTICLE_TO_SUMMARIZE, return_tensors="pt")
>>> # Global attention on the first token (cf. Beltagy et al. 2020)
>>> global_attention_mask = torch.zeros_like(inputs)
>>> global_attention_mask[:, 0] = 1
>>> # Generate Summary
>>> summary_ids = model.generate(inputs, global_attention_mask=global_attention_mask, num_beams=3, max_length=32)
>>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
LEDForSequenceClassification
类 transformers.LEDForSequenceClassification
< source >( config: LEDConfig **kwargs )
参数
- config (LEDConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
LED模型,顶部带有序列分类/头(在池化输出之上的线性层),例如用于GLUE任务。
该模型继承自 PreTrainedModel。请参阅超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以了解一般用法和行为。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None global_attention_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.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.
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用
LedTokenizer
获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。LED 使用
eos_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.如果你想改变填充行为,你应该阅读
modeling_led._prepare_decoder_inputs
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。 - 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 for the encoder. 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(encoder_layers, encoder_attention_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择交叉注意力模块中特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — 元组由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
, 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力机制中。 - past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, target_sequence_length, hidden_size)
, optional) — Optionally, instead of passingdecoder_input_ids
you can choose to directly pass an embedded representation. Ifpast_key_values
is used, optionally only the lastdecoder_inputs_embeds
have to be input (seepast_key_values
). This is useful if you want more control over how to convertdecoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.如果
decoder_input_ids
和decoder_inputs_embeds
都未设置,decoder_inputs_embeds
将取inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
范围内。如果config.num_labels > 1
,则计算分类损失(交叉熵)。
返回
transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LEDConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供label
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
logits (
torch.FloatTensor
形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
LEDForSequenceClassification 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
单标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, LEDForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> model = LEDForSequenceClassification.from_pretrained("allenai/led-base-16384")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> with torch.no_grad():
... logits = model(**inputs).logits
>>> predicted_class_id = logits.argmax().item()
>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = LEDForSequenceClassification.from_pretrained("allenai/led-base-16384", num_labels=num_labels)
>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
多标签分类示例:
>>> import torch
>>> from transformers import AutoTokenizer, LEDForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> model = LEDForSequenceClassification.from_pretrained("allenai/led-base-16384", 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 = LEDForSequenceClassification.from_pretrained(
... "allenai/led-base-16384", 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
LEDForQuestionAnswering
类 transformers.LEDForQuestionAnswering
< source >( config )
参数
- config (LEDConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
LED模型,顶部带有跨度分类头,用于抽取式问答任务,如SQuAD(在隐藏状态输出顶部有一个线性层,用于计算span start logits
和span end logits
)。
该模型继承自 PreTrainedModel。请参阅超类文档,了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。
该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以了解一般用法和行为。
前进
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None global_attention_mask: typing.Optional[torch.FloatTensor] = None start_positions: typing.Optional[torch.LongTensor] = None end_positions: typing.Optional[torch.LongTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
torch.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.
- decoder_input_ids (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用
LedTokenizer
获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。LED 使用
eos_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
of shape(batch_size, target_sequence_length)
, optional) — Default behavior: generate a tensor that ignores pad tokens indecoder_input_ids
. Causal mask will also be used by default.如果你想改变填充行为,你应该阅读
modeling_led._prepare_decoder_inputs
并根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。 - 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 for the encoder. 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(encoder_layers, encoder_attention_heads)
, optional) — 用于在编码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- decoder_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中屏蔽注意力模块中选定的头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被屏蔽,
- 0 表示头部 被屏蔽.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择交叉注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选的) — 元组由 (last_hidden_state
, 可选的:hidden_states
, 可选的:attentions
) 组成last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
, 可选的) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力机制中。 - past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — Tuple oftuple(torch.FloatTensor)
of lengthconfig.n_layers
, with each tuple having 2 tensors of shape(batch_size, num_heads, sequence_length, embed_size_per_head)
) and 2 additional tensors of shape(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
.包含预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),这些状态可用于(参见
past_key_values
输入)以加速顺序解码。如果使用了
past_key_values
,用户可以选择只输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - inputs_embeds (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望对如何将input_ids
索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。 - decoder_inputs_embeds (
torch.FloatTensor
of shape(batch_size, target_sequence_length, hidden_size)
, optional) — Optionally, instead of passingdecoder_input_ids
you can choose to directly pass an embedded representation. Ifpast_key_values
is used, optionally only the lastdecoder_inputs_embeds
have to be input (seepast_key_values
). This is useful if you want more control over how to convertdecoder_input_ids
indices into associated vectors than the model’s internal embedding lookup matrix.如果
decoder_input_ids
和decoder_inputs_embeds
都未设置,decoder_inputs_embeds
将取inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度起始位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会被考虑用于计算损失。 - end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算标记分类损失的标记跨度结束位置(索引)的标签。 位置被限制在序列长度内(sequence_length)。序列之外的位置不会用于计算损失。
返回
transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(LEDConfig)和输入。
-
loss (
torch.FloatTensor
形状为(1,)
,可选,当提供labels
时返回) — 总跨度提取损失是起始和结束位置的交叉熵之和。 -
start_logits (
torch.FloatTensor
形状为(batch_size, sequence_length)
) — 跨度起始分数(在 SoftMax 之前)。 -
end_logits (
torch.FloatTensor
形状为(batch_size, sequence_length)
) — 跨度结束分数(在 SoftMax 之前)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)。解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每层一个)。解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每层一个)。解码器交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
torch.FloatTensor
形状为(batch_size, sequence_length, hidden_size)
,可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每层的输出)。编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的torch.FloatTensor
元组(每层一个)。编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。
LEDForQuestionAnswering 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, LEDForQuestionAnswering
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> model = LEDForQuestionAnswering.from_pretrained("allenai/led-base-16384")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])
>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
TFLEDModel
类 transformers.TFLEDModel
< source >( config *inputs **kwargs )
参数
- config (LEDConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸LED模型输出原始隐藏状态,没有任何特定的头部。 此模型继承自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: tf.Tensor | None = None decoder_input_ids: tf.Tensor | None = None decoder_attention_mask: tf.Tensor | None = None head_mask: tf.Tensor | None = None decoder_head_mask: tf.Tensor | None = None encoder_outputs: tf.Tensor | None = None global_attention_mask: tf.Tensor | None = None past_key_values: Tuple[Tuple[tf.Tensor]] | None = None inputs_embeds: tf.Tensor | None = None decoder_inputs_embeds: tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None training: bool = False **kwargs ) → transformers.models.led.modeling_tf_led.TFLEDSeq2SeqModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
tf.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.
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用
LedTokenizer
获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。LED 使用
eos_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 默认情况下会生成并忽略填充标记。不建议在大多数用例中设置此选项。 - head_mask (
tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于在编码器中屏蔽注意力模块中选定的头。在[0, 1]
中选择的掩码值:- 1 表示头 未被屏蔽,
- 0 表示头 被屏蔽.
- decoder_head_mask (
tf.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头部的掩码。掩码值在[0, 1]
中选择:- 1 表示头部 未被掩码,
- 0 表示头部 被掩码.
- encoder_outputs (
tf.Tensor
, optional) — 编码器最后一层输出的隐藏状态。用于解码器的交叉注意力。 形状为(batch_size, sequence_length, hidden_size)
的序列 - past_key_values (
Tuple[Tuple[tf.Tensor]]
长度为config.n_layers
) — 包含预计算的关键和值隐藏状态的注意力块。可用于加速解码。 如果使用了past_key_values
,用户可以选择仅输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去的关键值状态提供给此模型的),而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。在训练期间设置为False
,在生成期间设置为True
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。
返回
transformers.models.led.modeling_tf_led.TFLEDSeq2SeqModelOutput 或 tuple(tf.Tensor)
一个 transformers.models.led.modeling_tf_led.TFLEDSeq2SeqModelOutput 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置(LEDConfig)和输入。
-
last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层的隐藏状态序列。如果使用了
past_key_values
,则只输出形状为(batch_size, 1, hidden_size)
的序列的最后一个隐藏状态。 -
past_key_values (
List[tf.Tensor]
, 可选, 当use_cache=True
被传递或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
。包含解码器的预计算隐藏状态(注意力块中的键和值),可以用于(参见
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。解码器每层输出的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器交叉注意力层的注意力权重,经过注意力 softmax 后,用于计算交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层的隐藏状态序列。 -
encoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当output_hidden_states=True
被传递或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。编码器每层输出的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。编码器的注意力权重,经过注意力 softmax 后,用于计算自注意力头中的加权平均值。
-
encoder_global_attentions (
tuple(tf.Tensor)
, 可选, 当output_attentions=True
被传递或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的令牌数量。经过注意力 softmax 后的全局注意力权重,用于计算自注意力头中的加权平均值。这些是每个具有全局注意力的令牌对序列中每个令牌的注意力权重。
TFLEDModel 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLEDModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
>>> model = TFLEDModel.from_pretrained("allenai/led-base-16384")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> last_hidden_states = outputs.last_hidden_state
TFLEDForConditionalGeneration
类 transformers.TFLEDForConditionalGeneration
< source >( config *inputs **kwargs )
参数
- config (LEDConfig) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
带有语言建模头的LED模型。可用于摘要生成。 该模型继承自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 decoder_input_ids: np.ndarray | tf.Tensor | None = None decoder_attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None decoder_head_mask: np.ndarray | tf.Tensor | None = None encoder_outputs: TFLEDEncoderBaseModelOutput | None = None global_attention_mask: np.ndarray | tf.Tensor | None = None past_key_values: Tuple[Tuple[Union[np.ndarray, tf.Tensor]]] | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None labels: tf.Tensor | None = None training: bool = False ) → transformers.models.led.modeling_tf_led.TFLEDSeq2SeqLMOutput 或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape({0})
) — Indices of input sequence tokens in the vocabulary.可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。
- attention_mask (
tf.Tensor
of shape({0})
, 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.
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — Indices of decoder input sequence tokens in the vocabulary.可以使用
LedTokenizer
获取索引。详情请参见PreTrainedTokenizer.encode()和 PreTrainedTokenizer.call()。LED 使用
eos_token_id
作为decoder_input_ids
生成的起始标记。如果使用了past_key_values
,则可以选择只输入最后一个decoder_input_ids
(参见past_key_values
)。 - decoder_attention_mask (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 默认情况下会生成并忽略填充标记。不建议在大多数用例中设置此参数。 - head_mask (
tf.Tensor
形状为(encoder_layers, encoder_attention_heads)
, 可选) — 用于在编码器中屏蔽注意力模块中选定的头。在[0, 1]
中选择的掩码值:- 1 表示头 未被屏蔽,
- 0 表示头 被屏蔽.
- decoder_head_mask (
tf.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于在解码器中取消选择注意力模块的特定头的掩码。掩码值在[0, 1]
中选择:- 1 表示头 未被掩码,
- 0 表示头 被掩码.
- encoder_outputs (
tf.Tensor
, 可选) — 编码器最后一层输出的隐藏状态。用于解码器的交叉注意力。 形状为(batch_size, sequence_length, hidden_size)
的序列 - past_key_values (
Tuple[Tuple[tf.Tensor]]
长度为config.n_layers
) — 包含预计算的注意力块的关键和值隐藏状态。可用于加速解码。 如果使用了past_key_values
,用户可以选择仅输入形状为(batch_size, 1)
的最后一个decoder_input_ids
(那些没有将其过去的关键值状态提供给此模型的),而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - use_cache (
bool
, 可选, 默认为True
) — 如果设置为True
,past_key_values
键值状态将被返回,并可用于加速解码(参见past_key_values
)。在训练期间设置为False
,在生成期间设置为True
- output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。这个参数可以在eager模式下使用,在graph模式下该值将始终设置为True. - 训练 (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。
返回
transformers.models.led.modeling_tf_led.TFLEDSeq2SeqLMOutput 或 tuple(tf.Tensor)
一个 transformers.models.led.modeling_tf_led.TFLEDSeq2SeqLMOutput 或一个 tf.Tensor
元组(如果
return_dict=False
被传递或当 config.return_dict=False
时)包含各种元素,具体取决于
配置 (LEDConfig) 和输入。
-
loss (
tf.Tensor
形状为(1,)
, 可选, 当提供labels
时返回) — 语言建模损失。 -
logits (
tf.Tensor
形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。 -
past_key_values (
List[tf.Tensor]
, 可选, 当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tf.Tensor
列表,每个张量的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算隐藏状态(注意力块中的键和值),可以 使用(参见
past_key_values
输入)来加速顺序解码。 -
decoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。解码器在每层输出处的隐藏状态加上初始嵌入输出。
-
decoder_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的注意力权重,在注意力 softmax 之后,用于计算 自注意力头中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算 交叉注意力头中的加权平均值。
-
encoder_last_hidden_state (
tf.Tensor
形状为(batch_size, sequence_length, hidden_size)
, 可选) — 模型编码器最后一层输出的隐藏状态序列。 -
encoder_hidden_states (
tuple(tf.Tensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
元组(一个用于嵌入的输出 + 一个用于每层的输出)形状为(batch_size, sequence_length, hidden_size)
。编码器在每层输出处的隐藏状态加上初始嵌入输出。
-
encoder_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, sequence_length)
。编码器的注意力权重,在注意力 softmax 之后,用于计算 自注意力头中的加权平均值。
-
encoder_global_attentions (
tuple(tf.Tensor)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —tf.Tensor
元组(每层一个)形状为(batch_size, num_heads, sequence_length, x)
,其中x
是具有全局注意力掩码的标记数量。全局注意力权重在注意力 softmax 之后,用于计算 自注意力头中的加权平均值。这些是每个具有全局注意力的标记对序列中每个标记的注意力权重。
TFLEDForConditionalGeneration 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用Module
实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。
示例:
>>> from transformers import AutoTokenizer, TFLEDForConditionalGeneration
>>> import tensorflow as tf
>>> mname = "allenai/led-base-16384"
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
>>> TXT = "My friends are <mask> but they eat too many carbs."
>>> model = TFLEDForConditionalGeneration.from_pretrained(mname)
>>> batch = tokenizer([TXT], return_tensors="tf")
>>> logits = model(inputs=batch.input_ids).logits
>>> probs = tf.nn.softmax(logits[0])
>>> # probs[5] is associated with the mask token