Transformers 文档
Blenderbot Small
并获得增强的文档体验
开始使用
Blenderbot Small
请注意,BlenderbotSmallModel 和 BlenderbotSmallForConditionalGeneration 仅与检查点 facebook/blenderbot-90M 结合使用。更大的 Blenderbot 检查点应与 BlenderbotModel 和 BlenderbotForConditionalGeneration 一起使用
概述
Blender 聊天机器人模型在 构建开放域聊天机器人的秘诀 中被提出,作者是 Stephen Roller、Emily Dinan、Naman Goyal、Da Ju、Mary Williamson、Yinhan Liu、Jing Xu、Myle Ott、Kurt Shuster、Eric M. Smith、Y-Lan Boureau、Jason Weston,于 2020 年 4 月 30 日发布。
该论文的摘要如下
构建开放域聊天机器人是机器学习研究中一个具有挑战性的领域。虽然先前的工作表明,在参数数量和训练数据规模上扩展神经模型可以提高结果,但我们表明,其他要素对于高性能聊天机器人也很重要。良好的对话需要许多技能,一位专业的对话者会以无缝的方式融合这些技能:提供引人入胜的谈话要点并倾听伙伴的意见,并适当地展示知识、同理心和个性,同时保持一致的人格。我们表明,当给予适当的训练数据和生成策略选择时,大规模模型可以学习这些技能。我们使用 90M、2.7B 和 9.4B 参数模型构建了这些方案的变体,并将我们的模型和代码公开提供。人工评估表明,就吸引力和人性化指标而言,我们最好的模型优于现有的多轮对话方法。然后,我们通过分析模型的失败案例来讨论这项工作的局限性。
此模型由 patrickvonplaten 贡献。作者的代码可以在 这里 找到。
使用技巧
Blenderbot Small 是一个带有绝对位置嵌入的模型,因此通常建议在右侧而不是左侧填充输入。
资源
BlenderbotSmallConfig
class transformers.BlenderbotSmallConfig
< source >( vocab_size = 50265 max_position_embeddings = 512 encoder_layers = 8 encoder_ffn_dim = 2048 encoder_attention_heads = 16 decoder_layers = 8 decoder_ffn_dim = 2048 decoder_attention_heads = 16 encoder_layerdrop = 0.0 decoder_layerdrop = 0.0 use_cache = True is_encoder_decoder = True activation_function = 'gelu' d_model = 512 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 init_std = 0.02 decoder_start_token_id = 1 scale_embedding = False pad_token_id = 0 bos_token_id = 1 eos_token_id = 2 forced_eos_token_id = 2 **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 50265) — BlenderbotSmall 模型的词汇表大小。定义了在调用 BlenderbotSmallModel 或 TFBlenderbotSmallModel 时,可以通过inputs_ids
传递的不同标记的数量。 - d_model (
int
, 可选, 默认为 512) — 层和池化器层的维度。 - encoder_layers (
int
, 可选, 默认为 8) — 编码器层数。 - decoder_layers (
int
, 可选, 默认为 8) — 解码器层数。 - encoder_attention_heads (
int
, 可选, 默认为 16) — Transformer 编码器中每个注意力层的注意力头数。 - decoder_attention_heads (
int
, 可选, 默认为 16) — Transformer 解码器中每个注意力层的注意力头数。 - decoder_ffn_dim (
int
, 可选, 默认为 2048) — 解码器中“中间”(通常称为前馈)层的维度。 - encoder_ffn_dim (
int
, 可选, 默认为 2048) — 解码器中“中间”(通常称为前馈)层的维度。 - activation_function (
str
或function
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - dropout (
float
, 可选, 默认为 0.1) — 嵌入、编码器和池化器中所有全连接层的 dropout 概率。 - attention_dropout (
float
, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。 - activation_dropout (
float
, 可选, 默认为 0.0) — 全连接层内部激活的 dropout 比率。 - max_position_embeddings (
int
, 可选, 默认为 512) — 此模型可能使用的最大序列长度。通常将其设置为较大的值以防万一(例如,512 或 1024 或 2048)。 - init_std (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - encoder_layerdrop (
float
, 可选, 默认为 0.0) — 编码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)。 - decoder_layerdrop (
float
, 可选, 默认为 0.0) — 解码器的 LayerDrop 概率。有关更多详细信息,请参阅 [LayerDrop 论文](see https://arxiv.org/abs/1909.11556)。 - scale_embedding (
bool
, 可选, 默认为False
) — 通过除以 sqrt(d_model) 来缩放嵌入。 - use_cache (
bool
, 可选, 默认为True
) — 模型是否应返回上次的键/值注意力(并非所有模型都使用) - forced_eos_token_id (
int
, 可选, 默认为 2) — 当达到max_length
时,强制作为最后一个生成的标记的标记 ID。通常设置为eos_token_id
。
这是用于存储 BlenderbotSmallModel 配置的配置类。它用于根据指定的参数实例化 BlenderbotSmall 模型,从而定义模型架构。使用默认值实例化配置将产生与 BlenderbotSmall facebook/blenderbot_small-90M 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> from transformers import BlenderbotSmallConfig, BlenderbotSmallModel
>>> # Initializing a BlenderbotSmall facebook/blenderbot_small-90M style configuration
>>> configuration = BlenderbotSmallConfig()
>>> # Initializing a model (with random weights) from the facebook/blenderbot_small-90M style configuration
>>> model = BlenderbotSmallModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
BlenderbotSmallTokenizer
class transformers.BlenderbotSmallTokenizer
< source >( vocab_file merges_file bos_token = '__start__' eos_token = '__end__' unk_token = '__unk__' pad_token = '__null__' **kwargs )
参数
- vocab_file (
str
) — 包含词汇表的文件。 - merges_file (
str
) — 合并文件的路径。 - bos_token (
str
, 可选, 默认为"__start__"
) — 句子的开始标记。 - eos_token (
str
, 可选, 默认为"__end__"
) — 句子的结束标记。 - unk_token (
str
, 可选, 默认为"__unk__"
) — 未知标记。词汇表中不存在的标记无法转换为 ID,而是设置为此标记。 - pad_token (
str
, 可选, 默认为"__null__"
) — 用于填充的标记,例如在批量处理不同长度的序列时。 - kwargs (可选) — 传递给 PreTrainedTokenizer 的其他关键字参数
基于 BPE (Byte-Pair-Encoding) 构建 Blenderbot-90M 分词器
此分词器继承自 PreTrainedTokenizer,其中包含大多数主要方法。用户应参考超类以获取有关方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
通过连接和添加特殊标记,从序列或序列对构建用于序列分类任务的模型输入。
此实现不添加特殊标记,此方法应在子类中被覆盖。
get_special_tokens_mask
< source >( token_ids_0: list token_ids_1: typing.Optional[list] = None already_has_special_tokens: bool = False ) → 一个整数列表,范围为 [0, 1]
从没有添加特殊标记的标记列表中检索序列 ID。当使用分词器的 prepare_for_model
或 encode_plus
方法添加特殊标记时,将调用此方法。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
创建与传递的序列相对应的标记类型 ID。 什么是标记类型 ID?
如果模型具有构建这些 ID 的特殊方式,则应在子类中覆盖此方法。
BlenderbotSmallTokenizerFast
class transformers.BlenderbotSmallTokenizerFast
< source >( vocab_file = None merges_file = None unk_token = '<|endoftext|>' bos_token = '<|endoftext|>' eos_token = '<|endoftext|>' add_prefix_space = False trim_offsets = True **kwargs )
构建一个“快速” BlenderbotSmall 分词器(由 HuggingFace 的 tokenizers 库支持)。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递的两个序列创建一个掩码,用于序列对分类任务。 BlenderbotSmall 不使用标记类型 ID,因此返回零列表。
BlenderbotSmallModel
class transformers.BlenderbotSmallModel
< source >( config: BlenderbotSmallConfig )
参数
- config (BlenderbotSmallConfig) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸 BlenderbotSmall 模型,输出原始隐藏状态,顶部没有任何特定的头部。此模型继承自 PreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头部等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Union[typing.Tuple, transformers.modeling_outputs.BaseModelOutput, NoneType] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.Tensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.Seq2SeqModelOutput or tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的torch.LongTensor
) — 词汇表中输入序列 tokens 的索引。如果您提供填充,默认情况下填充将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (形状为
(batch_size, sequence_length)
的torch.Tensor
,可选) — 用于避免在填充 token 索引上执行 attention 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 token 未被掩盖,
- 0 表示 token 被掩盖。
- decoder_input_ids (形状为
(batch_size, target_sequence_length)
的torch.LongTensor
,可选) — 词汇表中 decoder 输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
BlenderbotSmall 使用
bos_token_id
作为decoder_input_ids
生成的起始 token。 如果使用past_key_values
,则可以选择仅输入最后一个decoder_input_ids
(请参阅past_key_values
)。 - decoder_attention_mask (形状为
(batch_size, target_sequence_length)
的torch.LongTensor
,可选) — 默认行为:生成一个 tensor,该 tensor 忽略decoder_input_ids
中的填充 tokens。 默认情况下,也将使用因果掩码。 - head_mask (形状为
(encoder_layers, encoder_attention_heads)
的torch.Tensor
,可选) — 用于 nullify encoder 中 attention 模块的选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- decoder_head_mask (形状为
(decoder_layers, decoder_attention_heads)
的torch.Tensor
,可选) — 用于 nullify decoder 中 attention 模块的选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- cross_attn_head_mask (形状为
(decoder_layers, decoder_attention_heads)
的torch.Tensor
,可选) — 用于 nullify decoder 中 cross-attention 模块的选定 head 的掩码。 掩码值在[0, 1]
中选择:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — Tuple 由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成,last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
,可选) 是 encoder 最后一层的输出端的 hidden-states 序列。 在 decoder 的 cross-attention 中使用。 - past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
的 Tuple,其中每个 tuple 都有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
) 的 tensors 和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的附加 tensors。包含预先计算的 hidden-states(self-attention 块和 cross-attention 块中的 key 和 values),可以用于(请参阅
past_key_values
输入)加速顺序解码。如果使用
past_key_values
,则用户可以选择仅输入最后一个decoder_input_ids
(那些没有将其过去的 key value states 提供给此模型的)形状为(batch_size, 1)
而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - decoder_inputs_embeds (形状为
(batch_size, target_sequence_length, hidden_size)
的torch.FloatTensor
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递decoder_input_ids
。 如果使用past_key_values
,则可以选择仅输入最后一个decoder_inputs_embeds
(请参阅past_key_values
)。 如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将decoder_input_ids
索引转换为关联的向量,这将非常有用。如果
decoder_input_ids
和decoder_inputs_embeds
均未设置,则decoder_inputs_embeds
采用inputs_embeds
的值。 - use_cache (
bool
,可选) — 如果设置为True
,则返回past_key_values
key value states,并且可以用于加速解码(请参阅past_key_values
)。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。
返回
transformers.modeling_outputs.Seq2SeqModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqModelOutput 或一个 torch.FloatTensor
的 tuple(如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (BlenderbotSmallConfig) 和输入。
-
last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
) — 模型 decoder 的最后一层的输出端的 hidden-states 序列。如果使用
past_key_values
,则仅输出形状为(batch_size, 1, hidden_size)
的序列的最后一个 hidden-state。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
的 Tuple,其中每个 tuple 都有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
) 的 tensors 和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的附加 tensors。包含预先计算的 hidden-states(self-attention 块和 cross-attention 块中的 key 和 values),可以用于(请参阅
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出,+ 每个层的输出各一个),形状为(batch_size, sequence_length, hidden_size)
。decoder 在每层输出端的 Hidden-states 加上可选的初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
-
encoder_last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
,可选) — 模型 encoder 的最后一层的输出端的 hidden-states 序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor)
, 可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出,+ 每个层的输出各一个),形状为(batch_size, sequence_length, hidden_size)
。encoder 在每层输出端的 Hidden-states 加上可选的初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。encoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
BlenderbotSmallModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, BlenderbotSmallModel
>>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt") # Batch size 1
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3, 512]
BlenderbotSmallForConditionalGeneration
class transformers.BlenderbotSmallForConditionalGeneration
< source >( config: BlenderbotSmallConfig )
参数
- config (BlenderbotSmallConfig) — 模型配置类,其中包含模型的所有参数。 使用配置文件初始化不会加载与模型关联的权重,而只会加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有语言建模 head 的 BlenderbotSmall 模型。 可用于摘要。 此模型继承自 PreTrainedModel。 查看超类文档以获取库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.LongTensor] = None attention_mask: typing.Optional[torch.Tensor] = None decoder_input_ids: typing.Optional[torch.LongTensor] = None decoder_attention_mask: typing.Optional[torch.LongTensor] = None head_mask: typing.Optional[torch.Tensor] = None decoder_head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None encoder_outputs: typing.Union[typing.Tuple, transformers.modeling_outputs.BaseModelOutput, NoneType] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.Tensor] = None decoder_inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。如果您提供填充,默认情况下填充将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
, 可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。Mask 值在[0, 1]
中选择:- 1 表示 tokens 未被 Mask,
- 0 表示 tokens 被 Mask。
- decoder_input_ids (
torch.LongTensor
,形状为(batch_size, target_sequence_length)
, 可选) — 词汇表中解码器输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
BlenderbotSmall 使用
bos_token_id
作为decoder_input_ids
生成的起始 token。如果使用past_key_values
,则可以选择仅输入最后的decoder_input_ids
(请参阅past_key_values
)。 - decoder_attention_mask (
torch.LongTensor
,形状为(batch_size, target_sequence_length)
, 可选) — 默认行为:生成一个忽略decoder_input_ids
中的 pad tokens 的 tensor。默认情况下也会使用因果 mask。 - head_mask (
torch.Tensor
,形状为(encoder_layers, encoder_attention_heads)
, 可选) — Mask,用于 nullify 编码器中 attention 模块的选定 head。Mask 值在[0, 1]
中选择:- 1 表示 head 未被 Mask,
- 0 表示 head 被 Mask。
- decoder_head_mask (
torch.Tensor
,形状为(decoder_layers, decoder_attention_heads)
, 可选) — Mask,用于 nullify 解码器中 attention 模块的选定 head。Mask 值在[0, 1]
中选择:- 1 表示 head 未被 Mask,
- 0 表示 head 被 Mask。
- cross_attn_head_mask (
torch.Tensor
,形状为(decoder_layers, decoder_attention_heads)
, 可选) — Mask,用于 nullify 解码器中 cross-attention 模块的选定 head。Mask 值在[0, 1]
中选择:- 1 表示 head 未被 Mask,
- 0 表示 head 被 Mask。
- encoder_outputs (
tuple(tuple(torch.FloatTensor)
, 可选) — Tuple 由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成,其中last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
,可选) 是编码器最后一层输出的 hidden-states 序列。在解码器的 cross-attention 中使用。 - past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选, 当传递use_cache=True
或config.use_cache=True
时返回) —tuple(torch.FloatTensor)
的 tuple,长度为config.n_layers
,其中每个 tuple 都有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的 tensors 和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外 tensors。包含预先计算的 hidden-states(自注意力模块和 cross-attention 模块中的 key 和 values),这些 hidden-states 可以使用(参见
past_key_values
输入)以加速顺序解码。如果使用
past_key_values
,用户可以选择仅输入最后的decoder_input_ids
(那些没有将其过去的 key value states 提供给此模型的)形状为(batch_size, 1)
,而不是所有形状为(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
,形状为(batch_size, target_sequence_length, hidden_size)
, 可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递decoder_input_ids
。如果使用past_key_values
,则可以选择仅输入最后的decoder_inputs_embeds
(请参阅past_key_values
)。如果您希望比模型的内部嵌入查找矩阵更好地控制如何将decoder_input_ids
索引转换为关联的向量,这将非常有用。如果
decoder_input_ids
和decoder_inputs_embeds
均未设置,则decoder_inputs_embeds
采用inputs_embeds
的值。 - use_cache (
bool
, 可选) — 如果设置为True
,则返回past_key_values
键值状态,并且可以用于加速解码(请参阅past_key_values
)。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通的 tuple。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 用于计算 masked language modeling loss 的标签。索引应为[0, ..., config.vocab_size]
或 -100(请参阅input_ids
docstring)。索引设置为-100
的 tokens 将被忽略(masked),loss 仅针对标签在[0, ..., config.vocab_size]
中的 tokens 计算。
返回
transformers.modeling_outputs.Seq2SeqLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.Seq2SeqLMOutput 或一个 torch.FloatTensor
的 tuple (如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (BlenderbotSmallConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
, 可选, 当提供labels
时返回) — 语言建模损失。 -
logits (
torch.FloatTensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
, 可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
的 Tuple,其中每个 tuple 都有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
) 的 tensors 和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的附加 tensors。包含预先计算的 hidden-states(self-attention 块和 cross-attention 块中的 key 和 values),可以用于(请参阅
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(torch.FloatTensor)
, 可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出,+ 每个层的输出各一个),形状为(batch_size, sequence_length, hidden_size)
。解码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
decoder_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
-
encoder_last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的torch.FloatTensor
,可选) — 模型 encoder 的最后一层的输出端的 hidden-states 序列。 -
encoder_hidden_states (
tuple(torch.FloatTensor)
, 可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出,+ 每个层的输出各一个),形状为(batch_size, sequence_length, hidden_size)
。编码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
encoder_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。encoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
BlenderbotSmallForConditionalGeneration 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
对话示例
>>> from transformers import AutoTokenizer, BlenderbotSmallForConditionalGeneration
>>> mname = "facebook/blenderbot_small-90M"
>>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
>>> print("Human: ", UTTERANCE)
Human: My friends are cool but they eat too many carbs.
>>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
>>> reply_ids = model.generate(**inputs)
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
Bot: what kind of carbs do they eat? i don't know much about carbs.
>>> REPLY = "I'm not sure"
>>> print("Human: ", REPLY)
Human: I'm not sure
>>> NEXT_UTTERANCE = (
... "My friends are cool but they eat too many carbs.__end__ __start__what kind of carbs do they eat? "
... "i don't know much about carbs__end__ "
... "__start__ I'm not sure."
... )
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
>>> next_reply_ids = model.generate(**inputs)
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
Bot: they eat a lot of carbs. carbs are high in fat, protein, and fats.
BlenderbotSmallForCausalLM
forward
< source >( input_ids: LongTensor = None attention_mask: typing.Optional[torch.Tensor] = None encoder_hidden_states: typing.Optional[torch.FloatTensor] = None encoder_attention_mask: typing.Optional[torch.FloatTensor] = None head_mask: typing.Optional[torch.Tensor] = None cross_attn_head_mask: typing.Optional[torch.Tensor] = None past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None 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.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。如果您提供填充,默认情况下填充将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在 padding token 索引上执行 attention 的掩码。Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- encoder_hidden_states (
torch.FloatTensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 编码器最后一层的输出端的隐藏状态序列。如果模型配置为解码器,则在 cross-attention 中使用。 - encoder_attention_mask (
torch.FloatTensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在编码器输入的 padding token 索引上执行 attention 的掩码。如果模型配置为解码器,则此掩码在 cross-attention 中使用。Mask values selected in[0, 1]
: - head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于 nullify attention 模块的 selected heads 的掩码。Mask values selected in[0, 1]
:- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- cross_attn_head_mask (
torch.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于 nullify cross-attention 模块的 selected heads 的掩码。Mask values selected in[0, 1]
:- 1 indicates the head is not masked,
- 0 indicates the head is masked.
- past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — 长度为config.n_layers
的tuple(torch.FloatTensor)
元组,其中每个元组包含 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的 tensors 和 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的附加 tensors。当模型在 Sequence to Sequence 模型中用作解码器时,才需要这两个附加 tensors。包含预先计算的隐藏状态(self-attention 块和 cross-attention 块中的 key 和 values),这些状态可以用于(参见
past_key_values
输入)加速顺序解码。如果使用
past_key_values
,则用户可以选择仅输入最后一次的decoder_input_ids
(那些没有将其 past key value 状态提供给此模型的),形状为(batch_size, 1)
,而不是形状为(batch_size, sequence_length)
的所有decoder_input_ids
。 - labels (
torch.LongTensor
of shape(batch_size, sequence_length)
, optional) — 用于计算 masked language modeling loss 的标签。索引应在[0, ..., config.vocab_size]
或 -100 中(参见input_ids
文档字符串)。索引设置为-100
的 tokens 将被忽略(masked),loss 仅针对标签在[0, ..., config.vocab_size]
中的 tokens 计算。 - use_cache (
bool
, optional) — 如果设置为True
,则返回past_key_values
key value 状态,并可用于加速解码(参见past_key_values
)。- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- output_attentions (
bool
, optional) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通的元组。
返回
transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.CausalLMOutputWithCrossAttentions 或 torch.FloatTensor
的元组 (如果传递 return_dict=False
或当 config.return_dict=False
时),包括各种元素,具体取决于配置 (BlenderbotSmallConfig) 和输入。
-
loss (
torch.FloatTensor
of shape(1,)
, optional, returned whenlabels
is provided) — 语言建模 loss (用于 next-token prediction)。 -
logits (
torch.FloatTensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —torch.FloatTensor
的元组 (如果模型具有嵌入层,则为嵌入输出之一;+ 每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出端的 Hidden-states,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —torch.FloatTensor
的元组 (每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention weights,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(torch.FloatTensor)
, 可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Cross attentions weights,用于计算 cross-attention heads 中的加权平均值。
-
past_key_values (
tuple(tuple(torch.FloatTensor))
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) — 长度为config.n_layers
的torch.FloatTensor
元组的元组,其中每个元组包含 self-attention 和 cross-attention 层的缓存 key、value 状态(如果模型在 encoder-decoder 设置中使用)。仅当config.is_decoder = True
时相关。包含预先计算的隐藏状态(attention 块中的 key 和 values),这些状态可以用于(参见
past_key_values
输入)加速顺序解码。
示例
>>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> model = BlenderbotSmallForCausalLM.from_pretrained("facebook/blenderbot_small-90M", add_cross_attention=False)
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
>>> list(logits.shape) == expected_shape
True
TFBlenderbotSmallModel
class transformers.TFBlenderbotSmallModel
< source >( config: BlenderbotSmallConfig *inputs **kwargs )
参数
- config (BlenderbotSmallConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
裸机 BLENDERBOT_SMALL 模型输出原始 hidden-states,顶部没有任何特定的 head。此模型继承自 TFPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,下载或保存、调整输入嵌入大小、pruning heads 等)。
此模型也是 keras.Model 子类。像使用常规 TF 2.0 Keras 模型一样使用它,并参考 TF 2.0 文档以了解与常规用法和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 将所有输入作为关键字参数(如 PyTorch 模型),或者
- 将所有输入作为第一个位置参数中的列表、元组或字典。
支持第二种格式的原因是,当将输入传递给模型和层时,Keras 方法首选此格式。 由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该 “just work” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可! 但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如,当使用 Keras Functional
API 创建自己的层或模型时,可以使用三种可能性来收集第一个位置参数中的所有输入 Tensors
- 仅使用
input_ids
且不包含其他内容的单个 Tensor:model(input_ids)
- 长度可变的列表,其中包含一个或多个输入 Tensors,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 字典,其中包含一个或多个与文档字符串中给出的输入名称关联的输入 Tensors:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 subclassing 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( input_ids: tf.Tensor | None = None attention_mask: tf.Tensor | None = None decoder_input_ids: tf.Tensor | None = None decoder_attention_mask: tf.Tensor | None = None decoder_position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None decoder_head_mask: tf.Tensor | None = None cross_attn_head_mask: tf.Tensor | None = None encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None past_key_values: List[tf.Tensor] | None = None inputs_embeds: tf.Tensor | None = None decoder_inputs_embeds: 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 **kwargs ) → transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于避免在 padding token 索引上执行 attention 的掩码。Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 词汇表中解码器输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 以了解详情。
BlenderbotSmall 使用
bos_token_id
作为decoder_input_ids
生成的起始 token。 如果使用past_key_values
,则可以选择仅输入最后的decoder_input_ids
(请参阅past_key_values
)。 - decoder_attention_mask (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 默认情况下会创建,并忽略 pad tokens。 大多数用例不建议设置此项。 - decoder_position_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 位置嵌入中每个解码器输入序列 tokens 的位置索引。 在范围[0, config.max_position_embeddings - 1]
中选择。 - head_mask (
tf.Tensor
of shape(encoder_layers, encoder_attention_heads)
, optional) — 用于使编码器中注意力模块的选定 head 失效的 Mask。 在[0, 1]
中选择的 Mask 值:- 1 表示 head 未被 Mask,
- 0 表示 head 被 Mask。
- decoder_head_mask (
tf.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于使解码器中注意力模块的选定 head 失效的 Mask。 在[0, 1]
中选择的 Mask 值:- 1 表示 head 未被 Mask,
- 0 表示 head 被 Mask。
- cross_attn_head_mask (
tf.Tensor
of shape(decoder_layers, decoder_attention_heads)
, optional) — 用于使 cross-attention 模块的选定 head 失效的 Mask。 在[0, 1]
中选择的 Mask 值:- 1 表示 head 未被 Mask,
- 0 表示 head 被 Mask。
- encoder_outputs (
tf.FloatTensor
, optional) — 编码器最后一层的输出 hidden states。 在解码器的 cross-attention 中使用。 形状为(batch_size, sequence_length, hidden_size)
的序列是 - past_key_values (
Tuple[Tuple[tf.Tensor]]
of lengthconfig.n_layers
) — 包含注意力模块的预计算 key 和 value hidden states。 可用于加速解码。 如果使用past_key_values
,用户可以选择仅输入最后的decoder_input_ids
(那些没有将其 past key value states 提供给此模型的)形状为(batch_size, 1)
而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - use_cache (
bool
, optional, defaults toTrue
) — 如果设置为True
,则返回past_key_values
key value states,可用于加速解码(请参阅past_key_values
)。 在训练期间设置为False
,在生成期间设置为True
- output_attentions (
bool
, optional) — 是否返回所有注意力层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - output_hidden_states (
bool
, optional) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通的 tuple。 此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。 - training (
bool
, optional, defaults toFalse
) — 是否在训练模式下使用模型(dropout 模块等某些模块在训练和评估之间具有不同的行为)。
返回
transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSeq2SeqModelOutput 或 tf.Tensor
的 tuple (如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (BlenderbotSmallConfig) 和输入。
-
last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层的输出 hidden-states 序列。如果使用
past_key_values
,则仅输出形状为(batch_size, 1, hidden_size)
的序列的最后一个 hidden-state。 -
past_key_values (
List[tf.Tensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) —tf.Tensor
列表,长度为config.n_layers
,每个 tensor 的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算 hidden-states(注意力模块中的 key 和 values),可用于加速顺序解码(请参阅
past_key_values
输入)。 -
decoder_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —tf.Tensor
的 tuple (embeddings 的输出 + 每个层的输出),形状为(batch_size, sequence_length, hidden_size)
。解码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
decoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的 tuple (每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的 tuple (每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
-
encoder_last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层的输出 hidden-states 序列。 -
encoder_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —tf.Tensor
的 tuple (embeddings 的输出 + 每个层的输出),形状为(batch_size, sequence_length, hidden_size)
。编码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
encoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的 tuple (每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。encoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
TFBlenderbotSmallModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFBlenderbotSmallModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> model = TFBlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> last_hidden_states = outputs.last_hidden_state
TFBlenderbotSmallForConditionalGeneration
class transformers.TFBlenderbotSmallForConditionalGeneration
< source >( config *inputs **kwargs )
参数
- config (BlenderbotSmallConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有语言建模 head 的 BLENDERBOT_SMALL 模型。 可用于摘要。 此模型继承自 TFPreTrainedModel。 查看超类文档,了解库为其所有模型实现的通用方法(例如,下载或保存、调整输入 embeddings 大小、剪枝 head 等)。
此模型也是 keras.Model 子类。像使用常规 TF 2.0 Keras 模型一样使用它,并参考 TF 2.0 文档以了解与常规用法和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 将所有输入作为关键字参数(如 PyTorch 模型),或者
- 将所有输入作为第一个位置参数中的列表、元组或字典。
支持第二种格式的原因是,当将输入传递给模型和层时,Keras 方法首选此格式。 由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该 “just work” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可! 但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如,当使用 Keras Functional
API 创建自己的层或模型时,可以使用三种可能性来收集第一个位置参数中的所有输入 Tensors
- 仅使用
input_ids
且不包含其他内容的单个 Tensor:model(input_ids)
- 长度可变的列表,其中包含一个或多个输入 Tensors,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 字典,其中包含一个或多个与文档字符串中给出的输入名称关联的输入 Tensors:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 subclassing 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( input_ids: tf.Tensor | None = None attention_mask: tf.Tensor | None = None decoder_input_ids: tf.Tensor | None = None decoder_attention_mask: tf.Tensor | None = None decoder_position_ids: tf.Tensor | None = None head_mask: tf.Tensor | None = None decoder_head_mask: tf.Tensor | None = None cross_attn_head_mask: tf.Tensor | None = None encoder_outputs: Optional[TFBaseModelOutput] = None past_key_values: List[tf.Tensor] | None = None inputs_embeds: tf.Tensor | None = None decoder_inputs_embeds: 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 labels: tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或 tuple(tf.Tensor)
参数
- input_ids (
tf.Tensor
of shape({0})
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 以了解详情。
- attention_mask (
tf.Tensor
of shape({0})
, optional) — Mask,用于避免在 padding token 索引上执行注意力机制。 在[0, 1]
中选择的 Mask 值:- 1 表示 tokens 未被 Mask,
- 0 表示 tokens 被 Mask。
- decoder_input_ids (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 词汇表中解码器输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 以了解详情。
BlenderbotSmall 使用
bos_token_id
作为decoder_input_ids
生成的起始 token。 如果使用past_key_values
,则可以选择仅输入最后的decoder_input_ids
(请参阅past_key_values
)。 - decoder_attention_mask (
tf.Tensor
of shape(batch_size, target_sequence_length)
, optional) — 默认情况下会创建,并忽略 pad tokens。 大多数用例不建议设置此项。 - decoder_position_ids (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 位置嵌入中每个解码器输入序列 tokens 的位置索引。 在范围[0, config.max_position_embeddings - 1]
中选择。 - head_mask (
tf.Tensor
,形状为(encoder_layers, encoder_attention_heads)
,可选) — 用于置空编码器中注意力模块所选 head 的掩码。掩码值选自[0, 1]
:- 1 表示 head 不被掩盖,
- 0 表示 head 被掩盖。
- decoder_head_mask (
tf.Tensor
,形状为(decoder_layers, decoder_attention_heads)
,可选) — 用于置空解码器中注意力模块所选 head 的掩码。掩码值选自[0, 1]
:- 1 表示 head 不被掩盖,
- 0 表示 head 被掩盖。
- cross_attn_head_mask (
tf.Tensor
,形状为(decoder_layers, decoder_attention_heads)
,可选) — 用于置空交叉注意力模块所选 head 的掩码。掩码值选自[0, 1]
:- 1 表示 head 不被掩盖,
- 0 表示 head 被掩盖。
- encoder_outputs (
tf.FloatTensor
,可选) — 编码器最后一层的输出的隐藏状态。在解码器的交叉注意力中使用。形状为(batch_size, sequence_length, hidden_size)
的序列 - past_key_values (
Tuple[Tuple[tf.Tensor]]
,长度为config.n_layers
) — 包含注意力块的预计算键和值隐藏状态。可用于加速解码。如果使用了past_key_values
,用户可以选择仅输入最后的decoder_input_ids
(那些没有将其过去的键值状态提供给此模型的),形状为(batch_size, 1)
,而不是所有形状为(batch_size, sequence_length)
的decoder_input_ids
。 - use_cache (
bool
,可选,默认为True
) — 如果设置为True
,则返回past_key_values
键值状态,可用于加速解码(参见past_key_values
)。训练期间设置为False
,生成期间设置为True
- output_attentions (
bool
,可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回的张量下的attentions
。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回的张量下的hidden_states
。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下,该值将始终设置为 True。 - training (
bool
,可选,默认为False
) — 是否在训练模式下使用模型(某些模块,如 dropout 模块,在训练和评估之间具有不同的行为)。 - labels (
tf.tensor
,形状为(batch_size, sequence_length)
,可选) — 用于计算掩码语言建模损失的标签。索引应为[0, ..., config.vocab_size]
或 -100(参见input_ids
文档字符串)。索引设置为-100
的 tokens 将被忽略(掩码),损失仅针对标签在[0, ..., config.vocab_size]
中的 tokens 计算。
返回
transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSeq2SeqLMOutput 或 tf.Tensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (BlenderbotSmallConfig) 和输入。
-
loss (
tf.Tensor
,形状为(n,)
,可选,其中 n 是非掩码标签的数量,当提供labels
时返回) — 语言建模损失。 -
logits (
tf.Tensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
past_key_values (
List[tf.Tensor]
, optional, returned whenuse_cache=True
is passed or whenconfig.use_cache=True
) —tf.Tensor
列表,长度为config.n_layers
,每个 tensor 的形状为(2, batch_size, num_heads, sequence_length, embed_size_per_head)
)。包含解码器的预计算 hidden-states(注意力模块中的 key 和 values),可用于加速顺序解码(请参阅
past_key_values
输入)。 -
decoder_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —tf.Tensor
的 tuple (embeddings 的输出 + 每个层的输出),形状为(batch_size, sequence_length, hidden_size)
。解码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
decoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的 tuple (每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的 tuple (每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
-
encoder_last_hidden_state (
tf.Tensor
of shape(batch_size, sequence_length, hidden_size)
, optional) — 模型编码器最后一层的输出 hidden-states 序列。 -
encoder_hidden_states (
tuple(tf.Tensor)
, optional, returned whenoutput_hidden_states=True
is passed or whenconfig.output_hidden_states=True
) —tf.Tensor
的 tuple (embeddings 的输出 + 每个层的输出),形状为(batch_size, sequence_length, hidden_size)
。编码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
encoder_attentions (
tuple(tf.Tensor)
, optional, returned whenoutput_attentions=True
is passed or whenconfig.output_attentions=True
) —tf.Tensor
的 tuple (每个层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。encoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
TFBlenderbotSmallForConditionalGeneration 前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
对话示例:
>>> from transformers import AutoTokenizer, TFBlenderbotSmallForConditionalGeneration
>>> mname = "facebook/blenderbot_small-90M"
>>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
>>> tokenizer = AutoTokenizer.from_pretrained(mname)
>>> UTTERANCE = "My friends are cool but they eat too many carbs."
>>> print("Human: ", UTTERANCE)
>>> inputs = tokenizer([UTTERANCE], return_tensors="tf")
>>> reply_ids = model.generate(**inputs)
>>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
what kind of carbs do they eat? i don't know much about carbs.
>>> REPLY = "I'm not sure"
>>> print("Human: ", REPLY)
>>> NEXT_UTTERANCE = (
... "My friends are cool but they eat too many carbs.</s> "
... "<s>what kind of carbs do they eat? i don't know much about carbs.</s> "
... "<s>I'm not sure."
... )
>>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="tf")
>>> inputs.pop("token_type_ids")
>>> next_reply_ids = model.generate(**inputs)
>>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
FlaxBlenderbotSmallModel
class transformers.FlaxBlenderbotSmallModel
< source >( config: BlenderbotSmallConfig input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (BlenderbotSmallConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
,可选,默认为jax.numpy.float32
) — 计算的数据类型。可以是jax.numpy.float32
、jax.numpy.float16
(在 GPU 上)和jax.numpy.bfloat16
(在 TPU 上)之一。这可用于在 GPU 或 TPU 上启用混合精度训练或半精度推理。如果指定,所有计算将以给定的
dtype
执行。请注意,这仅指定计算的 dtype,不影响模型参数的 dtype。
裸 BlenderbotSmall 模型 Transformer,输出原始隐藏状态,顶部没有任何特定的 head。此模型继承自 FlaxPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 Flax Linen flax.nn.Module 子类。将其用作常规 Flax 模块,并参考 Flax 文档,了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids: Array attention_mask: typing.Optional[jax.Array] = None decoder_input_ids: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None position_ids: typing.Optional[jax.Array] = None decoder_position_ids: typing.Optional[jax.Array] = 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: <function PRNGKey at 0x7f787eb14310> = None ) → transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或 tuple(torch.FloatTensor)
返回
transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxSeq2SeqModelOutput 或 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (BlenderbotSmallConfig) 和输入。
-
last_hidden_state (
jnp.ndarray
,形状为(batch_size, sequence_length, hidden_size)
) — 模型解码器最后一层输出端的隐藏状态序列。如果使用
past_key_values
,则仅输出形状为(batch_size, 1, hidden_size)
的序列的最后一个 hidden-state。 -
past_key_values (
tuple(tuple(jnp.ndarray))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(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)
的附加张量。包含预先计算的 hidden-states(self-attention 块和 cross-attention 块中的 key 和 values),可以用于(请参阅
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(jnp.ndarray)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。解码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
decoder_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
-
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
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。编码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
encoder_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。encoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
示例
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallModel
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> model = FlaxBlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
encode
< source >( input_ids: Array attention_mask: typing.Optional[jax.Array] = None position_ids: typing.Optional[jax.Array] = 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: <function PRNGKey at 0x7f787eb14310> = None ) → transformers.modeling_flax_outputs.FlaxBaseModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
jnp.ndarray
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。如果您提供 padding,默认情况下将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
jnp.ndarray
,形状为(batch_size, sequence_length)
,可选) — 掩码,用于避免在 padding 标记索引上执行 attention。掩码值在[0, 1]
中选择:- 1 表示未被掩码的标记,
- 0 表示被掩码的标记。
- position_ids (
numpy.ndarray
,形状为(batch_size, sequence_length)
,可选) — 位置嵌入中每个输入序列标记的位置索引。在范围[0, config.max_position_embeddings - 1]
中选择。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回的张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回的张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.modeling_flax_outputs.FlaxBaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxBaseModelOutput 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig'>
) 和输入。
-
last_hidden_state (
jnp.ndarray
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出处的 hidden-states 序列。 -
hidden_states (
tuple(jnp.ndarray)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出以及初始 embedding 输出处的 Hidden-states。
-
attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention weights,用于计算 self-attention heads 中的加权平均值。
示例
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)
decode
< source >( decoder_input_ids encoder_outputs encoder_attention_mask: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None decoder_position_ids: 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: <function PRNGKey at 0x7f787eb14310> = None ) → transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions 或 tuple(torch.FloatTensor)
参数
- decoder_input_ids (
jnp.ndarray
,形状为(batch_size, target_sequence_length)
) — 解码器输入序列标记在词汇表中的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
对于翻译和摘要训练,应提供
decoder_input_ids
。 如果未提供decoder_input_ids
,则模型将通过将input_ids
向右移动来创建此张量,以进行遵循论文的去噪预训练。 - encoder_outputs (
tuple(tuple(jnp.ndarray)
) — 元组由 (last_hidden_state
,可选:hidden_states
,可选:attentions
) 组成last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
,可选) 是编码器最后一层输出处的 hidden-states 序列。在解码器的 cross-attention 中使用。 - encoder_attention_mask (
jnp.ndarray
,形状为(batch_size, sequence_length)
,可选) — 掩码,用于避免在 padding 标记索引上执行 attention。掩码值在[0, 1]
中选择:- 1 表示未被掩码的标记,
- 0 表示被掩码的标记。
- decoder_attention_mask (
jnp.ndarray
,形状为(batch_size, target_sequence_length)
,可选) — 默认行为:生成一个张量,该张量忽略decoder_input_ids
中的 pad 标记。因果掩码也将默认使用。如果您想更改 padding 行为,则应根据您的需要进行修改。 有关默认策略的更多信息,请参见 论文 中的图 1。
- decoder_position_ids (
numpy.ndarray
,形状为(batch_size, sequence_length)
,可选) — 位置嵌入中每个解码器输入序列标记的位置索引。在范围[0, config.max_position_embeddings - 1]
中选择。 - past_key_values (
Dict[str, np.ndarray]
,可选,由init_cache
返回或在传递先前的past_key_values
时返回) — 预先计算的 hidden-states 字典(attention 块中的键和值),可用于快速自回归解码。预先计算的键和值 hidden-states 的形状为 [batch_size, max_length]。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回的张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回的张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。
返回
transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxBaseModelOutputWithPastAndCrossAttentions 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig'>
) 和输入。
-
last_hidden_state (
jnp.ndarray
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出处的 hidden-states 序列。如果使用
past_key_values
,则仅输出形状为(batch_size, 1, hidden_size)
的序列的最后一个 hidden-state。 -
past_key_values (
tuple(tuple(jnp.ndarray))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) —tuple(jnp.ndarray)
元组,长度为config.n_layers
,每个元组具有 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)
的附加张量。包含预先计算的 hidden-states(自 attention 块中的键和值,以及如果
config.is_encoder_decoder=True
,则可选地在 cross-attention 块中),可以用于(请参阅past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(jnp.ndarray)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出以及初始 embedding 输出处的 Hidden-states。
-
attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention weights,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
且config.add_cross_attention=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
示例
>>> import jax.numpy as jnp
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, 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)
>>> last_decoder_hidden_states = outputs.last_hidden_state
FlaxBlenderbotForConditionalGeneration
class transformers.FlaxBlenderbotSmallForConditionalGeneration
< source >( config: BlenderbotSmallConfig input_shape: typing.Tuple[int] = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (BlenderbotSmallConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
- dtype (
jax.numpy.dtype
,可选,默认为jax.numpy.float32
) — 计算的数据类型。可以是jax.numpy.float32
、jax.numpy.float16
(在 GPU 上)和jax.numpy.bfloat16
(在 TPU 上)之一。这可以用于在 GPU 或 TPU 上启用混合精度训练或半精度推理。如果指定,所有计算将使用给定的
dtype
执行。请注意,这仅指定计算的 dtype,不影响模型参数的 dtype。
带有语言建模头的 BLENDERBOT_SMALL 模型。可用于摘要。此模型继承自 FlaxPreTrainedModel。查看超类文档,了解库为其所有模型实现的通用方法(例如下载或保存、调整输入 embeddings 大小、剪枝头等)。
此模型也是 Flax Linen flax.nn.Module 子类。将其用作常规 Flax 模块,并参考 Flax 文档,了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids: Array attention_mask: typing.Optional[jax.Array] = None decoder_input_ids: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None position_ids: typing.Optional[jax.Array] = None decoder_position_ids: typing.Optional[jax.Array] = 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: <function PRNGKey at 0x7f787eb14310> = None ) → transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
jnp.ndarray
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。 默认情况下,如果您提供填充,则填充将被忽略。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
jnp.ndarray
,形状为(batch_size, sequence_length)
,可选) — 用于避免在填充 token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 未被 Mask 的 tokens,
- 0 表示 被 Mask 的 tokens。
- decoder_input_ids (
jnp.ndarray
,形状为(batch_size, target_sequence_length)
,可选) — 词汇表中解码器输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
对于翻译和摘要训练,应提供
decoder_input_ids
。 如果未提供decoder_input_ids
,则模型将通过将input_ids
向右移动以进行降噪预训练来创建此张量,这遵循了论文中的做法。 - decoder_attention_mask (
jnp.ndarray
,形状为(batch_size, target_sequence_length)
,可选) — 默认行为:生成一个张量,该张量忽略decoder_input_ids
中的 pad tokens。 默认情况下,还将使用因果 mask。如果您想更改填充行为,则应根据需要进行修改。 有关默认策略的更多信息,请参见 论文 中的图 1 。
- position_ids (
numpy.ndarray
,形状为(batch_size, sequence_length)
,可选) — 位置嵌入中每个输入序列 token 的位置索引。 在范围[0, config.max_position_embeddings - 1]
中选择。 - decoder_position_ids (
numpy.ndarray
,形状为(batch_size, sequence_length)
,可选) — 位置嵌入中每个解码器输入序列 token 的位置索引。 在范围[0, config.max_position_embeddings - 1]
中选择。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions 张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通的 tuple。
返回
transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxSeq2SeqLMOutput 或一个 torch.FloatTensor
的 tuple(如果传递了 return_dict=False
或当 config.return_dict=False
时),包括取决于配置 (BlenderbotSmallConfig) 和输入的各种元素。
-
logits (
jnp.ndarray
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
past_key_values (
tuple(tuple(jnp.ndarray))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(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)
的附加张量。包含预先计算的 hidden-states(self-attention 块和 cross-attention 块中的 key 和 values),可以用于(请参阅
past_key_values
输入)加速顺序解码。 -
decoder_hidden_states (
tuple(jnp.ndarray)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。解码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
decoder_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。decoder 的 cross-attention 层的 Attention 权重,在 attention softmax 之后,用于计算 cross-attention heads 中的加权平均值。
-
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
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。编码器在每一层输出端的 Hidden-states 以及初始嵌入输出。
-
encoder_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。encoder 的 Attention 权重,在 attention softmax 之后,用于计算 self-attention heads 中的加权平均值。
FlaxBlenderbotSmallPreTrainedModel
前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的 recipe 需要在此函数中定义,但之后应调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
摘要示例
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="np")
>>> # Generate Summary
>>> summary_ids = model.generate(inputs["input_ids"]).sequences
>>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
Mask 填充示例
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> TXT = "My friends are <mask> but they eat too many carbs."
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
>>> input_ids = tokenizer([TXT], return_tensors="np")["input_ids"]
>>> logits = model(input_ids).logits
>>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
>>> probs = jax.nn.softmax(logits[0, masked_index], axis=0)
>>> values, predictions = jax.lax.top_k(probs)
>>> tokenizer.decode(predictions).split()
encode
< source >( input_ids: Array attention_mask: typing.Optional[jax.Array] = None position_ids: typing.Optional[jax.Array] = 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: <function PRNGKey at 0x7f787eb14310> = None ) → transformers.modeling_flax_outputs.FlaxBaseModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
jnp.ndarray
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。 默认情况下,如果您提供填充,则填充将被忽略。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
jnp.ndarray
,形状为(batch_size, sequence_length)
,可选) — 用于避免在填充 token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 未被 Mask 的 tokens,
- 0 表示 被 Mask 的 tokens。
- position_ids (
numpy.ndarray
,形状为(batch_size, sequence_length)
,可选) — 位置嵌入中每个输入序列 token 的位置索引。 在范围[0, config.max_position_embeddings - 1]
中选择。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions 张量。 有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通的 tuple。
返回
transformers.modeling_flax_outputs.FlaxBaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxBaseModelOutput 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig'>
) 和输入。
-
last_hidden_state (
jnp.ndarray
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出处的 hidden-states 序列。 -
hidden_states (
tuple(jnp.ndarray)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出以及初始 embedding 输出处的 Hidden-states。
-
attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention weights,用于计算 self-attention heads 中的加权平均值。
示例
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
>>> encoder_outputs = model.encode(**inputs)
decode
< source >( decoder_input_ids encoder_outputs encoder_attention_mask: typing.Optional[jax.Array] = None decoder_attention_mask: typing.Optional[jax.Array] = None decoder_position_ids: 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 deterministic: bool = True params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None ) → transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
参数
- decoder_input_ids (
jnp.ndarray
,形状为(batch_size, target_sequence_length)
) — 词汇表中解码器输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
对于翻译和摘要训练,应提供
decoder_input_ids
。 如果未提供decoder_input_ids
,则模型将通过将input_ids
向右移动以进行降噪预训练来创建此张量,这遵循了论文中的做法。 - encoder_outputs (
tuple(tuple(jnp.ndarray)
) — Tuple 由 (last_hidden_state
, 可选:hidden_states
, 可选:attentions
) 组成,last_hidden_state
的形状为(batch_size, sequence_length, hidden_size)
,可选) 是编码器最后一层输出的 hidden-states 序列。 在解码器的交叉 attention 中使用。 - encoder_attention_mask (
jnp.ndarray
,形状为(batch_size, sequence_length)
,可选) — 用于避免在填充 token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 未被 Mask 的 tokens,
- 0 表示 被 Mask 的 tokens。
- decoder_attention_mask (
jnp.ndarray
,形状为(batch_size, target_sequence_length)
,可选) — 默认行为:生成一个张量,该张量忽略decoder_input_ids
中的 pad tokens。 默认情况下,还将使用因果 mask。如果您想更改填充行为,则应根据需要进行修改。 有关默认策略的更多信息,请参见 论文 中的图 1 。
- decoder_position_ids (
numpy.ndarray
,形状为(batch_size, sequence_length)
,可选) — 每个解码器输入序列 token 在位置嵌入中的位置索引。 在范围[0, config.max_position_embeddings - 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.FlaxCausalLMOutputWithCrossAttentions 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxCausalLMOutputWithCrossAttentions 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (<class 'transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig'>
) 和输入。
-
logits (
jnp.ndarray
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模头的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
hidden_states (
tuple(jnp.ndarray)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
元组(embeddings 的输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出以及初始 embedding 输出处的 Hidden-states。
-
attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention weights,用于计算 self-attention heads 中的加权平均值。
-
cross_attentions (
tuple(jnp.ndarray)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Cross attentions weights,用于计算 cross-attention heads 中的加权平均值。
-
past_key_values (
tuple(tuple(jnp.ndarray))
,可选,当传递use_cache=True
或当config.use_cache=True
时返回) — 长度为config.n_layers
的jnp.ndarray
元组的元组,如果模型在编码器-解码器设置中使用,则每个元组包含自注意力层和交叉注意力层的缓存键、值状态。 仅当config.is_decoder = True
时相关。包含预先计算的隐藏状态(attention 块中的 key 和 values),这些状态可以用于(参见
past_key_values
输入)加速顺序解码。
示例
>>> import jax.numpy as jnp
>>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
>>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, 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