Transformers 文档

T5

T5

Models Spaces Paper page

概述

T5模型由探索迁移学习的极限与统一的文本到文本转换器一文中提出,作者包括Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li、Peter J. Liu

论文的摘要如下:

迁移学习,即模型首先在数据丰富的任务上进行预训练,然后在下游任务上进行微调,已成为自然语言处理(NLP)中的一项强大技术。迁移学习的有效性催生了多种方法、方法论和实践。在本文中,我们通过引入一个统一的框架,将每个语言问题转换为文本到文本的格式,探索了NLP中的迁移学习技术。我们的系统研究比较了预训练目标、架构、未标记数据集、迁移方法以及其他因素在数十种语言理解任务上的表现。通过将我们的探索见解与规模和我们新的“Colossal Clean Crawled Corpus”相结合,我们在涵盖摘要、问答、文本分类等多个基准测试中取得了最先进的结果。为了促进未来在NLP迁移学习方面的工作,我们发布了我们的数据集、预训练模型和代码。

所有检查点都可以在hub上找到。

该模型由thomwolf贡献。原始代码可以在这里找到。

使用提示

  • T5 是一种在无监督和有监督任务的多任务混合上预训练的编码器-解码器模型,每个任务都被转换为文本到文本的格式。T5 通过为每个任务对应的输入添加不同的前缀,在各种任务上表现良好,例如,对于翻译:将英语翻译成德语:…,对于摘要:摘要:…

  • 预训练包括监督学习和自监督学习。监督学习是在GLUE和SuperGLUE基准提供的下游任务上进行的(如上所述,将它们转换为文本到文本任务)。

  • 自监督训练使用损坏的标记,通过随机移除15%的标记并用单独的前哨标记替换它们(如果连续几个标记被标记为移除,则整个组被替换为一个前哨标记)。编码器的输入是损坏的句子,解码器的输入是原始句子,目标则是被前哨标记分隔的丢弃标记。

  • T5使用相对标量嵌入。编码器输入填充可以在左侧和右侧进行。

  • 请参阅下面的训练推理资源部分,了解有关使用的所有详细信息。

T5 有不同的大小:

基于原始的T5模型,谷歌发布了一些后续工作:

  • T5v1.1: T5v1.1 是 T5 的一个改进版本,进行了一些架构上的调整,并且仅在 C4 上进行预训练,没有混合监督任务。请参考 T5v1.1 的文档,可以在此处找到 here

  • mT5: mT5 是一个多语言的 T5 模型。它是在 mC4 语料库上进行预训练的,该语料库包含 101 种语言。请参考 mT5 的文档,文档可以在此处找到 here

  • byT5: byT5 是一个在字节序列而非 SentencePiece 子词标记序列上预训练的 T5 模型。请参考 byT5 的文档,文档可以在此处找到 here

  • UL2: UL2 是一个类似于 T5 的模型,预训练于各种去噪目标

  • Flan-T5: Flan 是一种基于提示的预训练方法。Flan-T5 是在 Flan 数据集集合上训练的 T5 模型,这些数据集包括:taskmaster2, djaym7/wiki_dialog, deepmind/code_contests, lambada, gsm8k, aqua_rat, esnli, quascqed

  • FLan-UL2 : 使用“Flan”提示调优和数据集集合进行微调的UL2模型。

  • UMT5: UmT5 是一个多语言的 T5 模型,使用新的采样方法 UniMax 在改进和更新的 mC4 多语言语料库上训练,涵盖 107 种语言的 29 万亿字符。请参考 mT5 的文档,可以在 这里 找到。

训练

T5 是一个编码器-解码器模型,并将所有 NLP 问题转换为文本到文本的格式。它使用教师强制进行训练。这意味着在训练时,我们总是需要一个输入序列和一个相应的目标序列。输入序列通过 input_ids 提供给模型。目标序列向右移动,即前面加上一个开始序列标记,并通过 decoder_input_ids 提供给解码器。在教师强制风格中,目标序列随后附加了 EOS 标记,并对应于 labels。PAD 标记在此用作开始序列标记。T5 可以在有监督和无监督的方式下进行训练/微调。

可以使用T5ForConditionalGeneration(或Tensorflow/Flax变体),它在解码器顶部包含了语言建模头。

  • 无监督去噪训练

在这种设置中,输入序列的跨度被所谓的哨兵标记(也称为 唯一掩码标记)所掩盖,输出序列则由相同的哨兵标记和真实的掩码标记连接而成。每个哨兵标记代表该句子中的一个唯一掩码标记,并且应该以,……直到开头。默认情况下,T5Tokenizer中提供了100个哨兵标记。

例如,句子“The cute dog walks in the park”在“cute dog”和“the”上加上掩码后,应按以下方式处理:

>>> from transformers import T5Tokenizer, T5ForConditionalGeneration

>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
>>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids

>>> # the forward function automatically creates the correct decoder_input_ids
>>> loss = model(input_ids=input_ids, labels=labels).loss
>>> loss.item()
3.7837

如果您有兴趣在新的语料库上预训练T5,请查看Examples目录中的run_t5_mlm_flax.py脚本。

  • 监督训练

在这种设置中,输入序列和输出序列是标准的序列到序列的输入输出映射。 假设我们想要微调模型以进行翻译,例如,我们有一个训练示例:输入 序列“The house is wonderful.”和输出序列“Das Haus ist wunderbar.”,那么它们应该为 模型准备如下:

>>> from transformers import T5Tokenizer, T5ForConditionalGeneration

>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt").input_ids
>>> labels = tokenizer("Das Haus ist wunderbar.", return_tensors="pt").input_ids

>>> # the forward function automatically creates the correct decoder_input_ids
>>> loss = model(input_ids=input_ids, labels=labels).loss
>>> loss.item()
0.2542

如你所见,模型只需要2个输入来计算损失:input_ids(即编码后的输入序列的input_ids)和labels(即编码后的目标序列的input_ids)。模型将基于labels自动创建decoder_input_ids,通过将它们向右移动一个位置并在前面添加config.decoder_start_token_id,对于T5来说,这个值等于0(即填充标记的id)。还要注意任务前缀:我们在编码输入序列之前,在前面加上‘translate English to German: ’。这将有助于提高性能,因为在T5的预训练期间使用了这个任务前缀。

然而,上面的例子只展示了一个训练样本。实际上,深度学习模型是以批次进行训练的。这意味着我们必须对样本进行填充/截断,使其长度相同。对于编码器-解码器模型,通常会定义max_source_lengthmax_target_length,它们分别决定了输入和输出序列的最大长度(否则会被截断)。这些参数应根据任务仔细设置。

此外,我们必须确保损失函数不考虑labels的填充标记ID。在PyTorch和Tensorflow中,可以通过将它们替换为-100来实现,这是CrossEntropyLossignore_index。在Flax中,可以使用decoder_attention_mask来忽略损失中的填充标记(详情请参见Flax summarization script)。我们还将attention_mask作为附加输入传递给模型,以确保忽略输入的填充标记。下面的代码示例说明了所有这些内容。

>>> from transformers import T5Tokenizer, T5ForConditionalGeneration
>>> import torch

>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> # the following 2 hyperparameters are task-specific
>>> max_source_length = 512
>>> max_target_length = 128

>>> # Suppose we have the following 2 training examples:
>>> input_sequence_1 = "Welcome to NYC"
>>> output_sequence_1 = "Bienvenue à NYC"

>>> input_sequence_2 = "HuggingFace is a company"
>>> output_sequence_2 = "HuggingFace est une entreprise"

>>> # encode the inputs
>>> task_prefix = "translate English to French: "
>>> input_sequences = [input_sequence_1, input_sequence_2]

>>> encoding = tokenizer(
...     [task_prefix + sequence for sequence in input_sequences],
...     padding="longest",
...     max_length=max_source_length,
...     truncation=True,
...     return_tensors="pt",
... )

>>> input_ids, attention_mask = encoding.input_ids, encoding.attention_mask

>>> # encode the targets
>>> target_encoding = tokenizer(
...     [output_sequence_1, output_sequence_2],
...     padding="longest",
...     max_length=max_target_length,
...     truncation=True,
...     return_tensors="pt",
... )
>>> labels = target_encoding.input_ids

>>> # replace padding token id's of the labels by -100 so it's ignored by the loss
>>> labels[labels == tokenizer.pad_token_id] = -100

>>> # forward pass
>>> loss = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels).loss
>>> loss.item()
0.188

额外的训练提示:

  • T5模型在使用AdamW优化器时,需要比Trainer中设置的默认学习率稍高一些。通常,1e-4和3e-4对于大多数问题(分类、摘要、翻译、问答、问题生成)效果良好。请注意,T5是使用AdaFactor优化器进行预训练的。

根据这个论坛帖子,任务前缀在以下情况下很重要: (1) 进行多任务训练时 (2) 你的任务与T5预训练混合中使用的监督任务之一相似或相关(参见论文的附录D以了解使用的任务前缀)。

如果在TPU上进行训练,建议将数据集中的所有示例填充到相同的长度,或者使用pad_to_multiple_of来设置少量预定义的桶大小以容纳所有示例。在TPU上不推荐动态地将批次填充到最长的示例,因为这会导致每次遇到不同的批次形状时触发重新编译,从而显著减慢训练速度。仅填充到批次中最长的示例会导致在TPU上的训练非常缓慢。

推理

在推理时,建议使用generate()。该方法负责编码输入并通过交叉注意力层将编码的隐藏状态传递给解码器,并自回归生成解码器输出。查看这篇博客文章以了解使用Transformers生成文本的所有细节。还有这篇博客文章解释了编码器-解码器模型中的生成工作原理。

>>> from transformers import T5Tokenizer, T5ForConditionalGeneration

>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer("translate English to German: The house is wonderful.", return_tensors="pt").input_ids
>>> outputs = model.generate(input_ids)
>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
Das Haus ist wunderbar.

请注意,T5 使用 pad_token_id 作为 decoder_start_token_id,因此在不使用 generate() 进行生成时,请确保以 pad_token_id 开始。

上面的例子只展示了一个单一的例子。你也可以进行批量推理,如下所示:

>>> from transformers import T5Tokenizer, T5ForConditionalGeneration

>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> task_prefix = "translate English to German: "
>>> # use different length sentences to test batching
>>> sentences = ["The house is wonderful.", "I like to work in NYC."]

>>> inputs = tokenizer([task_prefix + sentence for sentence in sentences], return_tensors="pt", padding=True)

>>> output_sequences = model.generate(
...     input_ids=inputs["input_ids"],
...     attention_mask=inputs["attention_mask"],
...     do_sample=False,  # disable sampling to test if batching affects output
... )

>>> print(tokenizer.batch_decode(output_sequences, skip_special_tokens=True))
['Das Haus ist wunderbar.', 'Ich arbeite gerne in NYC.']

因为T5已经通过span-mask去噪目标进行了训练,它可以在推理过程中用于预测哨兵(被屏蔽的)标记。预测的标记随后将被放置在哨兵标记之间。

>>> from transformers import T5Tokenizer, T5ForConditionalGeneration

>>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids

>>> sequence_ids = model.generate(input_ids)
>>> sequences = tokenizer.batch_decode(sequence_ids)
>>> sequences
['<pad> <extra_id_0> park offers <extra_id_1> the <extra_id_2> park.</s>']

性能

如果您希望获得更快的训练和推理性能,请为NVIDIA GPU安装NVIDIA APEX,或为AMD GPU安装ROCm APEX,然后模型将自动使用apex.normalization.FusedRMSNorm而不是T5LayerNorm。前者使用了优化的融合内核,比后者快几倍。

资源

一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用T5。如果您有兴趣提交资源以包含在此处,请随时打开一个Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。

Text Classification
Token Classification
Text Generation
Summarization
Fill-Mask
Translation
Question Answering

🚀 部署

T5Config

transformers.T5Config

< >

( vocab_size = 32128 d_model = 512 d_kv = 64 d_ff = 2048 num_layers = 6 num_decoder_layers = None num_heads = 8 relative_attention_num_buckets = 32 relative_attention_max_distance = 128 dropout_rate = 0.1 layer_norm_epsilon = 1e-06 initializer_factor = 1.0 feed_forward_proj = 'relu' is_encoder_decoder = True use_cache = True pad_token_id = 0 eos_token_id = 1 classifier_dropout = 0.0 **kwargs )

参数

  • vocab_size (int, 可选, 默认为 32128) — T5模型的词汇表大小。定义了调用T5ModelTFT5Model时传递的inputs_ids可以表示的不同令牌的数量。
  • d_model (int, optional, 默认为 512) — 编码器层和池化层的大小.
  • d_kv (int, 可选, 默认为 64) — 每个注意力头的键、查询、值投影的大小。投影层的 inner_dim 将被定义为 num_heads * d_kv.
  • d_ff (int, 可选, 默认为 2048) — 每个 T5Block 中中间前馈层的大小.
  • num_layers (int, optional, defaults to 6) — Transformer编码器中的隐藏层数。
  • num_decoder_layers (int, optional) — Transformer解码器中的隐藏层数。如果未设置,将使用与num_layers相同的值。
  • num_heads (int, optional, defaults to 8) — Transformer编码器中每个注意力层的注意力头数量。
  • relative_attention_num_buckets (int, optional, defaults to 32) — 用于每个注意力层的桶的数量。
  • relative_attention_max_distance (int, optional, 默认为 128) — 用于桶分离的较长序列的最大距离。
  • dropout_rate (float, optional, defaults to 0.1) — 所有 dropout 层的比率。
  • classifier_dropout (float, optional, 默认为 0.0) — 分类器的 dropout 比率。
  • layer_norm_eps (float, optional, defaults to 1e-6) — 层归一化层使用的epsilon值。
  • initializer_factor (float, 可选, 默认为 1) — 用于初始化所有权重矩阵的因子(应保持为1,内部用于初始化测试)。
  • feed_forward_proj (string, 可选, 默认为 "relu") — 要使用的前馈层类型。应为 "relu""gated-gelu" 之一。T5v1.1 使用 "gated-gelu" 前馈投影。原始 T5 使用 "relu".
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回最后的键/值注意力(并非所有模型都使用)。

这是用于存储T5ModelTFT5Model配置的配置类。它用于根据指定的参数实例化一个T5模型,定义模型架构。使用默认值实例化配置将产生与google-t5/t5-small架构类似的配置。

配置对象继承自PretrainedConfig,可用于控制模型输出。阅读PretrainedConfig的文档以获取更多信息。

T5Tokenizer

transformers.T5Tokenizer

< >

( vocab_file eos_token = '' unk_token = '' pad_token = '' extra_ids = 100 additional_special_tokens = None sp_model_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None legacy = None add_prefix_space = True **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。
  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为该标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在批处理不同长度的序列时使用。
  • extra_ids (int, optional, 默认为 100) — 添加一些额外的 id 到词汇表中,用作哨兵。这些令牌可以通过 “id{%d}>” 访问,其中 ”{%d}” 是 0 到 extra_ids-1 之间的数字。这些令牌可以通过调用 get_sentinel_tokens 方法获取,令牌 id 可以通过调用 get_sentinel_token_ids 方法获取。 additional_special_tokens (List[str], optional): 由分词器使用的额外特殊令牌。
  • sp_model_kwargs (dict, optional) — Will be passed to the SentencePieceProcessor.__init__() method. The Python wrapper for SentencePiece can be used, among other things, to set:
    • enable_sampling: 启用子词正则化。

    • nbest_size: 用于unigram的采样参数。对于BPE-Dropout无效。

      • nbest_size = {0,1}: No sampling is performed.
      • nbest_size > 1: samples from the nbest_size results.
      • nbest_size < 0: assuming that nbest_size is infinite and samples from the all hypothesis (lattice) using forward-filtering-and-backward-sampling algorithm.
    • alpha: 用于单字采样的平滑参数,以及BPE-dropout的合并操作丢弃概率。

  • legacy (bool, optional) — 是否应使用分词器的legacy行为。Legacy是指在合并#24622和#25224之前的行为,这些合并包括修复以正确处理特殊标记后出现的标记。一个简单的例子:
    • legacy=True:

构建一个T5分词器。基于SentencePiece

此分词器继承自PreTrainedTokenizer,其中包含了大部分主要方法。用户应参考此超类以获取有关这些方法的更多信息。

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表。
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。序列的格式如下:

  • 单个序列: X
  • 序列对:A B

get_special_tokens_mask

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。
  • already_has_special_tokens (bool, optional, defaults to False) — 是否已经为模型格式化了包含特殊标记的标记列表。

返回

List[int]

一个整数列表,范围在[0, 1]:1表示特殊标记,0表示序列标记。

从没有添加特殊标记的标记列表中检索序列ID。当使用标记器的prepare_for_model方法添加特殊标记时,会调用此方法。

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

零的列表。

从传递给序列对分类任务的两个序列中创建一个掩码。T5不使用标记类型ID,因此返回一个零列表。

保存词汇表

< >

( 保存目录: str 文件名前缀: typing.Optional[str] = None )

T5TokenizerFast

transformers.T5TokenizerFast

< >

( vocab_file = None tokenizer_file = None eos_token = '' unk_token = '' pad_token = '' extra_ids = 100 additional_special_tokens = None add_prefix_space = None **kwargs )

参数

  • vocab_file (str) — SentencePiece 文件(通常具有 .spm 扩展名),包含实例化分词器所需的词汇表。
  • eos_token (str, optional, defaults to "</s>") — The end of sequence token.

    在使用特殊标记构建序列时,这不是用于序列结束的标记。 使用的标记是sep_token

  • unk_token (str, optional, defaults to "") — 未知标记。不在词汇表中的标记无法转换为ID,而是设置为这个标记。
  • pad_token (str, optional, defaults to "") — 用于填充的标记,例如在对不同长度的序列进行批处理时使用。
  • extra_ids (int, optional, 默认为 100) — 添加一些额外的 id 到词汇表中,用作哨兵。这些令牌可以通过 “id{%d}>” 访问,其中 ”{%d}” 是一个介于 0 和 extra_ids-1 之间的数字。这些令牌可以通过 调用 get_sentinel_tokens 方法获取,令牌 id 可以通过调用 get_sentinel_token_ids 方法获取
  • additional_special_tokens (List[str], optional) — 分词器使用的额外特殊标记。
  • add_prefix_space (bool, optional) — 是否应该自动添加前缀空格
  • from_slow (book, 可选, 默认为 False) — 是否应将分词器从慢速分词器转换。如果设置了 add_prefix_space,则此选项将设置为 True.

构建一个“快速”的T5分词器(由HuggingFace的tokenizers库支持)。基于 Unigram

这个分词器继承自PreTrainedTokenizerFast,其中包含了大部分主要方法。用户应参考这个超类以获取有关这些方法的更多信息。

build_inputs_with_special_tokens

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — 特殊令牌将被添加到的ID列表。
  • token_ids_1 (List[int], 可选) — 可选的第二个序列对的ID列表。

返回

List[int]

带有适当特殊标记的输入ID列表。

通过连接和添加特殊标记,从序列或序列对构建序列分类任务的模型输入。序列的格式如下:

  • 单个序列: X
  • 序列对:A B

create_token_type_ids_from_sequences

< >

( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) List[int]

参数

  • token_ids_0 (List[int]) — ID列表.
  • token_ids_1 (List[int], optional) — 可选的第二个序列对的ID列表。

返回

List[int]

零的列表。

从传递给序列对分类任务的两个序列中创建一个掩码。T5不使用标记类型ID,因此返回一个零列表。

Pytorch
Hide Pytorch content

T5模型

transformers.T5Model

< >

( config: T5Config )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸T5模型变压器输出原始隐藏状态,顶部没有任何特定头部。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None decoder_head_mask: typing.Optional[torch.FloatTensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.FloatTensor]]] = None inputs_embeds: typing.Optional[torch.Tensor] = None decoder_inputs_embeds: typing.Optional[torch.Tensor] = 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 cache_position: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.Seq2SeqModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中取消选择交叉注意力模块的特定头部的掩码。掩码值在 [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)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了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 passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。

返回

transformers.modeling_outputs.Seq2SeqModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • 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_layerstuple(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 后,用于计算自注意力头中的加权平均值。

T5Model 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, T5Model

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5Model.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer(
...     "Studies have been shown that owning a dog is good for you", return_tensors="pt"
... ).input_ids  # Batch size 1
>>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids  # Batch size 1

>>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.
>>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.
>>> decoder_input_ids = model._shift_right(decoder_input_ids)

>>> # forward pass
>>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
>>> last_hidden_states = outputs.last_hidden_state

T5ForConditionalGeneration

transformers.T5ForConditionalGeneration

< >

( config: T5Config )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

T5 模型顶部带有language modeling头。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None decoder_head_mask: typing.Optional[torch.FloatTensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = None past_key_values: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = 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 cache_position: typing.Optional[torch.LongTensor] = None ) transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (torch.FloatTensor of shape (num_heads,) or (num_layers, num_heads), optional) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中取消选择交叉注意力模块的特定头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被掩码,
    • 0 表示头部 被掩码.
  • encoder_outputs (tuple(tuple(torch.FloatTensor), optional) — 元组由 (last_hidden_state, optional: hidden_states, optional: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(torch.FloatTensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了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 passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 [-100, 0, ..., config.vocab_size - 1] 范围内。所有设置为 -100 的标签将被忽略(掩码),损失仅计算在 [0, ..., config.vocab_size] 范围内的标签

返回

transformers.modeling_outputs.Seq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • 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_layerstuple(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 之后,用于计算自注意力头中的加权平均值。

T5ForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, T5ForConditionalGeneration

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> # training
>>> input_ids = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="pt").input_ids
>>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="pt").input_ids
>>> outputs = model(input_ids=input_ids, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits

>>> # inference
>>> input_ids = tokenizer(
...     "summarize: studies have shown that owning a dog is good for you", return_tensors="pt"
... ).input_ids  # Batch size 1
>>> outputs = model.generate(input_ids)
>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
>>> # studies have shown that owning a dog is good for you.

T5EncoderModel

transformers.T5EncoderModel

< >

( config: T5Config )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸T5模型变压器输出编码器的原始隐藏状态,顶部没有任何特定的头部。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • last_hidden_state (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层的输出的隐藏状态序列。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出的隐藏状态加上可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每一层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

T5EncoderModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, T5EncoderModel

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = T5EncoderModel.from_pretrained("google-t5/t5-small")
>>> input_ids = tokenizer(
...     "Studies have been shown that owning a dog is good for you", return_tensors="pt"
... ).input_ids  # Batch size 1
>>> outputs = model(input_ids=input_ids)
>>> last_hidden_states = outputs.last_hidden_state

T5ForSequenceClassification

transformers.T5ForSequenceClassification

< >

( config: T5Config )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

T5模型,顶部带有序列分类/头(在池化输出之上的线性层),例如用于GLUE任务。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: 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.List[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.Seq2SeqSequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor of shape (num_heads,) or (num_layers, num_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)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了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 passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。
  • labels (torch.LongTensor of shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels > 1,则计算分类损失(交叉熵)。

返回

transformers.modeling_outputs.Seq2SeqSequenceClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqSequenceClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • 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_layerstuple(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 之后,用于计算自注意力头中的加权平均值。

T5ForSequenceClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

T5ForTokenClassification

transformers.T5ForTokenClassification

< >

( config: T5Config )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

T5编码器模型,顶部带有标记分类头(在隐藏状态输出之上的线性层),例如用于命名实体识别(NER)任务。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头。掩码值在 [0, 1] 中选择:
    • 1 表示头 未被屏蔽,
    • 0 表示头 被屏蔽.
  • decoder_head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor of shape (num_heads,) or (num_layers, num_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)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • inputs_embeds (torch.FloatTensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • decoder_inputs_embeds (torch.FloatTensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — 用于计算标记分类损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.TokenClassifierOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • loss (torch.FloatTensor 形状为 (1,), 可选, 当提供 labels 时返回) — 分类损失。

  • logits (torch.FloatTensor 形状为 (batch_size, sequence_length, config.num_labels)) — 分类分数(在 SoftMax 之前)。

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 torch.FloatTensor 组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 torch.FloatTensor 组成的元组(每一层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

T5ForTokenClassification 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

T5ForQuestionAnswering

transformers.T5ForQuestionAnswering

< >

( config: T5Config )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

T5模型,顶部带有用于抽取式问答任务(如SQuAD)的跨度分类头(在隐藏状态输出之上的线性层用于计算span start logitsspan end logits)。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自PreTrainedModel。请查看超类文档以了解库为其所有模型实现的通用方法(如下载或保存、调整输入嵌入的大小、修剪头部等)。

该模型也是一个PyTorch torch.nn.Module 子类。 将其作为常规的PyTorch模块使用,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。

前进

< >

( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.FloatTensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.BoolTensor] = None head_mask: typing.Optional[torch.FloatTensor] = None decoder_head_mask: typing.Optional[torch.FloatTensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Optional[typing.Tuple[typing.Tuple[torch.Tensor]]] = 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.Seq2SeqQuestionAnsweringModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:
    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    什么是注意力掩码?

  • decoder_input_ids (torch.LongTensor of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (torch.BoolTensor of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头。屏蔽值在 [0, 1] 中选择:
    • 1 表示头 未被屏蔽,
    • 0 表示头 被屏蔽.
  • decoder_head_mask (torch.FloatTensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • cross_attn_head_mask (torch.Tensor of shape (num_heads,) or (num_layers, num_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)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了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 passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — 表示输入序列标记在序列中的位置的索引。它用于在正确的位置更新缓存并推断完整的序列长度。
  • 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.Seq2SeqQuestionAnsweringModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.Seq2SeqQuestionAnsweringModelOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • 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_layerstuple(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 之后,用于计算自注意力头中的加权平均值。

T5ForQuestionAnswering 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

TensorFlow
Hide TensorFlow content

TFT5Model

transformers.TFT5Model

< >

( config *inputs **kwargs )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸T5模型变压器输出原始隐藏状态,顶部没有任何特定的头部。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自 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函数一样传递输入!

调用

< >

( 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: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None inputs_embeds: np.ndarray | tf.Tensor | None = None decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFSeq2SeqModelOutputtuple(tf.Tensor)

参数

  • input_ids (tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on the right or the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

    要了解更多关于如何为预训练准备inputs的信息,请查看T5 Training.

  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Provide for sequence to sequence training. T5 uses the pad_token_id as the starting token for decoder_input_ids generation. If past_key_values is used, optionally only the last decoder_input_ids have to be input (see past_key_values).

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • 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_attention_mask (tf.Tensor of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个张量,忽略decoder_input_ids中的填充标记。默认情况下也会使用因果掩码。
  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • decoder_head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(tf.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力机制中。
  • past_key_values (tuple(tuple(tf.Tensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • inputs_embeds (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • decoder_inputs_embeds (tf.Tensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选, 默认为 True) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • 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.modeling_tf_outputs.TFSeq2SeqModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时),包含根据配置 (T5Config) 和输入的各种元素。

  • 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_layerstf.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 后,用于计算自注意力头中的加权平均值。

TFT5Model 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFT5Model

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = TFT5Model.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer(
...     "Studies have been shown that owning a dog is good for you", return_tensors="tf"
... ).input_ids  # Batch size 1
>>> decoder_input_ids = tokenizer("Studies show that", return_tensors="tf").input_ids  # Batch size 1

>>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.
>>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.
>>> decoder_input_ids = model._shift_right(decoder_input_ids)

>>> # forward pass
>>> outputs = model(input_ids, decoder_input_ids=decoder_input_ids)
>>> last_hidden_states = outputs.last_hidden_state

TFT5ForConditionalGeneration

transformers.TFT5ForConditionalGeneration

< >

( config *inputs **kwargs )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

T5 模型顶部带有language modeling头。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自 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函数一样传递输入!

调用

< >

( 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: np.ndarray | tf.Tensor | None = None past_key_values: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None inputs_embeds: np.ndarray | tf.Tensor | None = None decoder_inputs_embeds: np.ndarray | tf.Tensor | None = None labels: np.ndarray | tf.Tensor | None = None use_cache: Optional[bool] = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFSeq2SeqLMOutputtuple(tf.Tensor)

参数

  • input_ids (tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on the right or the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    什么是输入ID?

    要了解更多关于如何为预训练准备inputs的信息,请查看T5 Training.

  • decoder_input_ids (tf.Tensor of shape (batch_size, target_sequence_length), optional) — Provide for sequence to sequence training. T5 uses the pad_token_id as the starting token for decoder_input_ids generation. If past_key_values is used, optionally only the last decoder_input_ids have to be input (see past_key_values).

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • 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_attention_mask (tf.Tensor of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个张量,忽略decoder_input_ids中的填充标记。默认情况下也会使用因果掩码。
  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在编码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部未被屏蔽,
    • 0 表示头部被屏蔽.
  • decoder_head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于在解码器中屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • encoder_outputs (tuple(tuple(tf.FloatTensor), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(tf.Tensor)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

  • inputs_embeds (tf.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您希望对如何将input_ids索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • decoder_inputs_embeds (tf.Tensor of shape (batch_size, target_sequence_length, hidden_size), optional) — Optionally, instead of passing decoder_input_ids you can choose to directly pass an embedded representation. If past_key_values is used, optionally only the last decoder_inputs_embeds have to be input (see past_key_values). This is useful if you want more control over how to convert decoder_input_ids indices into associated vectors than the model’s internal embedding lookup matrix.

    如果decoder_input_idsdecoder_inputs_embeds都未设置,decoder_inputs_embeds将取inputs_embeds的值。

  • use_cache (bool, 可选, 默认为 True) — 如果设置为 Truepast_key_values 键值状态将被返回,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions。此参数只能在eager模式下使用,在graph模式下将使用配置中的值。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的 hidden_states。此参数只能在急切模式下使用,在图模式下将使用配置中的值。
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。此参数可以在eager模式下使用,在graph模式下该值将始终设置为True.
  • 训练 (bool, 可选, 默认为 False) — 是否在训练模式下使用模型(一些模块如 dropout 模块在训练和评估之间有不同的行为)。
  • labels (tf.Tensor of shape (batch_size, sequence_length), optional) — 用于计算交叉熵分类损失的标签。索引应在 [0, ..., config.vocab_size - 1] 范围内。

返回

transformers.modeling_tf_outputs.TFSeq2SeqLMOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或一个 tf.Tensor 元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (T5Config) 和输入。

  • loss (tf.Tensor 形状为 (n,), 可选, 其中 n 是非掩码标签的数量,当 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_layerstf.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 之后,用于计算加权平均值 自注意力头中。

TFT5ForConditionalGeneration 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFT5ForConditionalGeneration

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = TFT5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> # training
>>> inputs = tokenizer("The <extra_id_0> walks in <extra_id_1> park", return_tensors="tf").input_ids
>>> labels = tokenizer("<extra_id_0> cute dog <extra_id_1> the <extra_id_2>", return_tensors="tf").input_ids
>>> outputs = model(inputs, labels=labels)
>>> loss = outputs.loss
>>> logits = outputs.logits

>>> # inference
>>> inputs = tokenizer(
...     "summarize: studies have shown that owning a dog is good for you", return_tensors="tf"
... ).input_ids  # Batch size 1
>>> outputs = model.generate(inputs)
>>> print(tokenizer.decode(outputs[0], skip_special_tokens=True))
>>> # studies have shown that owning a dog is good for you

TFT5EncoderModel

transformers.TFT5EncoderModel

< >

( config *inputs **kwargs )

参数

  • config (T5Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。

裸T5模型变压器输出编码器的原始隐藏状态,顶部没有任何特定的头部。

T5模型是由Colin Raffel、Noam Shazeer、Adam Roberts、Katherine Lee、Sharan Narang、Michael Matena、Yanqi Zhou、Wei Li和Peter J. Liu在Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer中提出的。它是一个在文本到文本去噪生成设置中预训练的编码器解码器变换器。

该模型继承自 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函数一样传递输入!

调用

< >

( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False ) transformers.modeling_tf_outputs.TFBaseModelOutputtuple(tf.Tensor)

参数

  • inputs (tf.Tensor of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on the right or the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.call()PreTrainedTokenizer.encode()

    要了解更多关于如何为预训练准备inputs的信息,请查看T5 Training.

  • 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.

    什么是注意力掩码?

  • inputs_embeds (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您希望对如何将 input_ids 索引转换为相关向量有更多控制,而不是使用模型的内部嵌入查找矩阵,这将非常有用。
  • head_mask (tf.Tensor 形状为 (num_heads,)(num_layers, num_heads), 可选) — 用于屏蔽自注意力模块中选定的头部的掩码。掩码值在 [0, 1] 中选择:
    • 1 表示头部 未被屏蔽,
    • 0 表示头部 被屏蔽.
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。
  • 训练 (bool, 可选, 默认为 False) — 是否在训练模式下使用模型(一些模块如dropout模块在训练和评估时有不同的行为)。

返回

transformers.modeling_tf_outputs.TFBaseModelOutputtuple(tf.Tensor)

一个 transformers.modeling_tf_outputs.TFBaseModelOutput 或一个 tf.Tensor 的元组(如果 return_dict=False 被传递或当 config.return_dict=False 时)包含各种元素,具体取决于 配置 (T5Config) 和输入。

  • last_hidden_state (tf.Tensor 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple(tf.FloatTensor), 可选, 当 output_hidden_states=True 被传递或当 config.output_hidden_states=True 时返回) — tf.Tensor 的元组(一个用于嵌入的输出 + 一个用于每一层的输出)形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(tf.Tensor), 可选, 当 output_attentions=True 被传递或当 config.output_attentions=True 时返回) — tf.Tensor 的元组(每一层一个)形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

TFT5EncoderModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, TFT5EncoderModel

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = TFT5EncoderModel.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer(
...     "Studies have been shown that owning a dog is good for you", return_tensors="tf"
... ).input_ids  # Batch size 1
>>> outputs = model(input_ids)
JAX
Hide JAX content

FlaxT5Model

transformers.FlaxT5Model

< >

( config: T5Config input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True gradient_checkpointing: bool = False **kwargs )

__call__

< >

( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 decoder_input_ids: 数组 = 无 decoder_attention_mask: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: = 无 ) transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (jnp.ndarray of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (jnp.ndarray 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 (jnp.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (jnp.ndarray of shape (batch_size, target_sequence_length), 可选) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • encoder_outputs (tuple(tuple(jnp.ndarray), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size) 是编码器最后一层的隐藏状态序列。用于解码器的交叉注意力中。
  • past_key_values (tuple(tuple(jnp.ndarray)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

返回

transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置(T5Config)和输入。

  • logits (jnp.ndarray 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (tuple(tuple(jnp.ndarray)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(jnp.ndarray) 元组,每个元组包含 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(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (jnp.ndarray 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

FlaxT5PreTrainedModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxT5Model

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = FlaxT5Model.from_pretrained("google-t5/t5-small")

>>> input_ids = tokenizer(
...     "Studies have been shown that owning a dog is good for you", return_tensors="np"
... ).input_ids
>>> decoder_input_ids = tokenizer("Studies show that", return_tensors="np").input_ids

>>> # preprocess: Prepend decoder_input_ids with start token which is pad token for T5Model.
>>> # This is not needed for torch's T5ForConditionalGeneration as it does this internally using labels arg.
>>> decoder_input_ids = model._shift_right(decoder_input_ids)

>>> # forward pass
>>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
>>> last_hidden_states = outputs.last_hidden_state

编码

< >

( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: = 无 ) transformers.modeling_flax_outputs.FlaxBaseModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (jnp.ndarray of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (jnp.ndarray 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.

    什么是注意力掩码?

  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxBaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxBaseModelOutput 或一个包含各种元素的 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),具体取决于配置()和输入。

  • last_hidden_state (jnp.ndarray 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple(jnp.ndarray), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入层的输出,一个用于每一层的输出)。

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

示例:

>>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = FlaxT5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)

解码

< >

( decoder_input_ids encoder_outputs encoder_attention_mask: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None past_key_values: dict = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None train: bool = False params: dict = None dropout_rng: = None ) transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

参数

  • decoder_input_ids (jnp.ndarray of shape (batch_size, target_sequence_length)) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    对于训练,应提供decoder_input_ids

  • encoder_outputs (tuple(tuple(jnp.ndarray)) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层的输出隐藏状态序列。用于解码器的交叉注意力中。
  • encoder_attention_mask (jnp.ndarray 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_attention_mask (jnp.ndarray of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • past_key_values (Dict[str, np.ndarray], 可选, 由 init_cache 返回或传递先前的 past_key_values) — 预计算的隐藏状态字典(注意力块中的键和值),可用于快速自回归解码。预计算的键和值隐藏状态的形状为 [batch_size, max_length].
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置()和输入。

  • last_hidden_state (jnp.ndarray,形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

    如果使用了 past_key_values,则只输出形状为 (batch_size, 1, hidden_size) 的序列的最后一个隐藏状态。

  • past_key_values (tuple(tuple(jnp.ndarray))可选,当传递了 use_cache=True 或当 config.use_cache=True 时返回)— 长度为 config.n_layerstuple(jnp.ndarray) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量,并且如果 config.is_encoder_decoder=True,则还包含 2 个形状为 (batch_size, num_heads, encoder_sequence_length, embed_size_per_head) 的额外张量。

    包含预先计算的隐藏状态(自注意力块中的键和值,并且如果 config.is_encoder_decoder=True,则还包含交叉注意力块中的键和值),这些隐藏状态可以用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple(jnp.ndarray)可选,当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回)— 由 jnp.ndarray 组成的元组(一个用于嵌入的输出,一个用于每一层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray)可选,当传递了 output_attentions=True 或当 config.output_attentions=True 时返回)— 由 jnp.ndarray 组成的元组(每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力权重在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(jnp.ndarray)可选,当传递了 output_attentions=Trueconfig.add_cross_attention=True 或当 config.output_attentions=True 时返回)— 由 jnp.ndarray 组成的元组(每一层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

示例:

>>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration
>>> import jax.numpy as jnp

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = FlaxT5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)

>>> decoder_start_token_id = model.config.decoder_start_token_id
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
>>> logits = outputs.logits

FlaxT5ForConditionalGeneration

transformers.FlaxT5ForConditionalGeneration

< >

( config: T5Config input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True gradient_checkpointing: bool = False **kwargs )

__call__

< >

( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 decoder_input_ids: 数组 = 无 decoder_attention_mask: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: = 无 ) transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

参数

  • input_ids (jnp.ndarray of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入ID?

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (jnp.ndarray 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 (jnp.ndarray of shape (batch_size, target_sequence_length), optional) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    T5 使用 pad_token_id 作为 decoder_input_ids 生成的起始标记。如果使用了 past_key_values,则可以选择只输入最后一个 decoder_input_ids(参见 past_key_values)。

    要了解更多关于如何为预训练准备decoder_input_ids的信息,请查看T5训练

  • decoder_attention_mask (jnp.ndarray of shape (batch_size, target_sequence_length), optional) — 默认行为:生成一个忽略decoder_input_ids中填充标记的张量。默认情况下也会使用因果掩码。
  • encoder_outputs (tuple(tuple(jnp.ndarray), 可选) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size) 是编码器最后一层的隐藏状态序列。用于解码器的交叉注意力机制中。
  • past_key_values (tuple(tuple(jnp.ndarray)) of length config.n_layers with each tuple having 4 tensors of shape (batch_size, num_heads, sequence_length - 1, embed_size_per_head)) — Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.

    如果使用了past_key_values,用户可以选择只输入形状为(batch_size, 1)的最后一个decoder_input_ids(那些没有将其过去键值状态提供给此模型的),而不是形状为(batch_size, sequence_length)的所有decoder_input_ids

返回

transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,取决于配置(T5Config)和输入。

  • logits (jnp.ndarray 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (tuple(tuple(jnp.ndarray)), 可选, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(jnp.ndarray) 元组,每个元组包含 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(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    解码器在每层输出处的隐藏状态加上初始嵌入输出。

  • decoder_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    解码器的交叉注意力层的注意力权重,在注意力 softmax 之后,用于计算交叉注意力头中的加权平均值。

  • encoder_last_hidden_state (jnp.ndarray 形状为 (batch_size, sequence_length, hidden_size), 可选) — 模型编码器最后一层输出的隐藏状态序列。

  • encoder_hidden_states (tuple(jnp.ndarray), 可选, 当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入的输出 + 一个用于每层的输出)。

    编码器在每层输出处的隐藏状态加上初始嵌入输出。

  • encoder_attentions (tuple(jnp.ndarray), 可选, 当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每层一个)。

    编码器的注意力权重,在注意力 softmax 之后,用于计算自注意力头中的加权平均值。

FlaxT5PreTrainedModel 的 forward 方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = FlaxT5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> ARTICLE_TO_SUMMARIZE = "summarize: My friends are cool but they eat too many carbs."
>>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], return_tensors="np")

>>> # Generate Summary
>>> summary_ids = model.generate(inputs["input_ids"]).sequences
>>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=False))

编码

< >

( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 output_attentions: 可选的[bool] = 无 output_hidden_states: 可选的[bool] = 无 return_dict: 可选的[bool] = 无 train: bool = 假 params: 字典 = 无 dropout_rng: = 无 ) transformers.modeling_flax_outputs.FlaxBaseModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (jnp.ndarray of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (jnp.ndarray 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.

    什么是注意力掩码?

  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量中的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxBaseModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxBaseModelOutput 或一个包含各种元素的 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),具体取决于配置 () 和输入。

  • last_hidden_state (jnp.ndarray 形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层输出的隐藏状态序列。

  • hidden_states (tuple(jnp.ndarray), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)jnp.ndarray 元组(一个用于嵌入层的输出,一个用于每一层的输出)。

    模型在每一层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)jnp.ndarray 元组(每一层一个)。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

示例:

>>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = FlaxT5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)

解码

< >

( decoder_input_ids encoder_outputs encoder_attention_mask: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None past_key_values: dict = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None train: bool = False params: dict = None dropout_rng: = None ) transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentionstuple(torch.FloatTensor)

参数

  • decoder_input_ids (jnp.ndarray of shape (batch_size, target_sequence_length)) — Indices of decoder input sequence tokens in the vocabulary.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是解码器输入ID?

    对于训练,应提供decoder_input_ids

  • encoder_outputs (tuple(tuple(jnp.ndarray)) — 元组由 (last_hidden_state, 可选: hidden_states, 可选: attentions) 组成 last_hidden_state 的形状为 (batch_size, sequence_length, hidden_size), 可选) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。
  • encoder_attention_mask (jnp.ndarray 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_attention_mask (jnp.ndarray of shape (batch_size, target_sequence_length), optional) — Default behavior: generate a tensor that ignores pad tokens in decoder_input_ids. Causal mask will also be used by default.

    如果你想改变填充行为,你应该根据你的需求进行修改。有关默认策略的更多信息,请参见论文中的图1。

  • past_key_values (Dict[str, np.ndarray], 可选, 由 init_cache 返回或传递先前的 past_key_values) — 预计算的隐藏状态字典(注意力块中的键和值),可用于快速自回归解码。预计算的键和值隐藏状态的形状为 [batch_size, max_length].
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

返回

transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentionstuple(torch.FloatTensor)

一个 transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions 或一个由 torch.FloatTensor 组成的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种 元素,具体取决于配置()和输入。

  • logits (jnp.ndarray 形状为 (batch_size, sequence_length, config.vocab_size)) — 语言建模头的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • hidden_states (tuple(jnp.ndarray), 可选, 当传递了 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 由 jnp.ndarray 组成的元组(一个用于嵌入的输出 + 一个用于每层的输出),形状为 (batch_size, sequence_length, hidden_size)

    模型在每层输出处的隐藏状态加上初始嵌入输出。

  • attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 jnp.ndarray 组成的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • cross_attentions (tuple(jnp.ndarray), 可选, 当传递了 output_attentions=True 或当 config.output_attentions=True 时返回) — 由 jnp.ndarray 组成的元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)

    交叉注意力 softmax 后的交叉注意力权重,用于计算交叉注意力头中的加权平均值。

  • past_key_values (tuple(tuple(jnp.ndarray)), 可选, 当传递了 use_cache=True 或当 config.use_cache=True 时返回) — 由长度为 config.n_layersjnp.ndarray 元组组成的元组,每个元组包含自注意力和交叉注意力层的缓存键、值 状态,如果模型用于编码器-解码器设置。 仅在 config.is_decoder = True 时相关。

    包含预计算的隐藏状态(注意力块中的键和值),可用于(参见 past_key_values 输入)以加速顺序解码。

示例:

>>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration
>>> import jax.numpy as jnp

>>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small")
>>> model = FlaxT5ForConditionalGeneration.from_pretrained("google-t5/t5-small")

>>> text = "summarize: My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)

>>> decoder_start_token_id = model.config.decoder_start_token_id
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
>>> logits = outputs.logits

FlaxT5EncoderModel

transformers.FlaxT5EncoderModel

< >

( config: T5Config input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = _do_init: bool = True gradient_checkpointing: bool = False **kwargs )

__call__

< >

( input_ids: 数组 attention_mask: 可选的[jax.Array] = 无 output_attentions: 可选的[布尔] = 无 output_hidden_states: 可选的[布尔] = 无 return_dict: 可选的[布尔] = 无 train: 布尔 = 假 params: 字典 = 无 dropout_rng: <函数 PRNGKey 在 0x7f50727b7640> = 无 )

参数

  • input_ids (jnp.ndarray of shape (batch_size, sequence_length)) — Indices of input sequence tokens in the vocabulary. T5 is a model with relative position embeddings so you should be able to pad the inputs on both the right and the left.

    可以使用AutoTokenizer获取索引。详情请参见PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    要了解更多关于如何为预训练准备input_ids的信息,请查看T5 Training.

  • attention_mask (jnp.ndarray 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.

    什么是注意力掩码?

  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
  • return_dict (bool, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。

FlaxT5EncoderModel 的前向方法,重写了 __call__ 特殊方法。

尽管前向传递的配方需要在此函数内定义,但之后应该调用Module实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会默默地忽略它们。

< > Update on GitHub