Transformers 文档

BLOOM

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

此模型于 2022-11-09 发布,并于 2022-06-09 添加到 Hugging Face Transformers。

BLOOM

PyTorch

概述

通过 BigScience Workshop 提出了 BLOOM 模型及其各种版本。BigScience 受到其他开放科学倡议的启发,这些倡议汇集了研究人员的时间和资源,以集体实现更大的影响力。BLOOM 的架构与 GPT3(用于下一个 token 预测的自回归模型)基本相似,但已在 46 种不同的语言和 13 种编程语言上进行了训练。该模型有几个较小的版本,也在同一数据集上进行了训练。BLOOM 有以下版本可供选择:

资源

以下是官方 Hugging Face 和社区(用 🌎 表示)资源列表,可帮助您开始使用 BLOOM。如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将对其进行审查!资源最好能展示一些新的内容,而不是复制现有资源。

文本生成

另请参阅

⚡️ 推理

⚙️ 训练

BloomConfig

class transformers.BloomConfig

< >

( vocab_size = 250880 hidden_size = 64 n_layer = 2 n_head = 8 layer_norm_epsilon = 1e-05 initializer_range = 0.02 use_cache = True bos_token_id = 1 eos_token_id = 2 pad_token_id = None apply_residual_connection_post_layernorm = False hidden_dropout = 0.0 attention_dropout = 0.0 pretraining_tp = 1 slow_but_exact = False tie_word_embeddings = True **kwargs )

参数

  • vocab_size (int, 可选, 默认为 250880) — Bloom 模型的词汇表大小。定义调用 BloomModel 时传递的 inputs_ids 所能表示的不同 token 的最大数量。请参阅 此讨论,了解 vocab_size 的定义方式。
  • hidden_size (int, 可选, 默认为 64) — 嵌入和隐藏状态的维度。
  • n_layer (int, 可选, 默认为 2) — Transformer 编码器中的隐藏层数量。
  • n_head (int, 可选, 默认为 8) — Transformer 编码器每个注意力层的注意力头数量。
  • layer_norm_epsilon (float, 可选, 默认为 1e-5) — 层归一化层中使用的 epsilon。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • apply_residual_connection_post_layernorm (bool, 可选, 默认为 False) — 如果启用,则使用 Transformer 块中的隐藏状态层归一化作为残差。
  • hidden_dropout (float, 可选, 默认为 0.1) — 偏置 dropout 的 dropout 率。
  • attention_dropout (float, 可选, 默认为 0.1) — 应用于注意力概率的 dropout 率。
  • use_cache (bool, 可选, 默认为 True) — 模型是否应返回最后一个键/值注意力(并非所有模型都使用)。
  • pretraining_tp (int, 可选, 默认为 1) — 实验性功能。使用 Megatron 进行预训练时使用的张量并行度(tensor parallelism rank)。请参考 本文档 了解更多关于此功能的信息。此值对于确保预训练结果的精确可复现性至关重要。请参考 此问题。另请注意,这仅在 slow_but_exact=True 时启用。
  • slow_but_exact (bool, 可选, 默认为 False) — 实验性功能。是否使用缓慢但精确的注意力机制实现。在合并 TP rank 张量时,由于切片操作,Megatron 训练的模型和我们的模型之间的结果可能略有不同。请参考 此问题。获得更准确结果的一种方法是启用此功能。启用此功能会降低推理的计算时间。当主模型已使用 TP_rank=1 进行微调后,未来可能会解决此问题。

这是配置类,用于存储 BloomModel 的配置。它用于根据指定的参数实例化 Bloom 模型,定义模型架构。使用默认值实例化配置将产生与 bigscience/bloom 架构相似的配置。

配置对象继承自 PreTrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PreTrainedConfig 的文档。

示例

>>> from transformers import BloomConfig, BloomModel

>>> # Initializing a Bloom configuration
>>> configuration = BloomConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = BloomModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

BloomModel

class transformers.BloomModel

< >

( config: BloomConfig )

参数

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

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

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.LongTensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.LongTensor | None = None **kwargs ) transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, 形状为 (batch_size, input_ids_length)) — input_ids_length = sequence_length,如果 past_key_valuesNone;否则为 past_key_values.get_seq_length()(输入过去键值状态的 sequence_length)。词汇表中输入序列 token 的索引。

    如果使用了 past_key_values,则只能将未处理的 input_ids(即其过去状态未传递给此模型的 input_ids)作为 input_ids 传递,形状为 (batch_size, unprocessed_length)

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由模型在之前的解码阶段返回的 past_key_values 组成,此时 use_cache=Trueconfig.use_cache=True

    只允许 Cache 实例作为输入,请参阅我们的 kv 缓存指南。如果未传入 past_key_values,则默认初始化 DynamicCache

    模型将输出与输入相同的缓存格式。

    如果使用 past_key_values,用户需要只输入未处理的 input_ids(即其过去键值状态未传递给此模型的 input_ids),其形状为 (batch_size, unprocessed_length),而不是所有 input_ids 的形状 (batch_size, sequence_length)

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    注意力掩码是什么?

  • inputs_embeds (torch.LongTensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.

返回

transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentionstuple(torch.FloatTensor)

A transformers.modeling_outputs.BaseModelOutputWithPastAndCrossAttentions or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (BloomConfig) and inputs.

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

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

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

    Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if config.is_encoder_decoder=True in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

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

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

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

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

  • cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True and config.add_cross_attention=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

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

The BloomModel forward method, overrides the __call__ special method。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

BloomForCausalLM

class transformers.BloomForCausalLM

< >

( config: BloomConfig )

参数

  • config (BloomConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The Bloom Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None cache_position: torch.LongTensor | None = None logits_to_keep: int | torch.Tensor = 0 **kwargs ) transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — input_ids_length = sequence_length if past_key_values is None else past_key_values.get_seq_length() (sequence_length of input past key value states). Indices of input sequence tokens in the vocabulary.

    If past_key_values is used, only input_ids that do not have their past calculated should be passed as input_ids.

    Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.

    输入 ID 是什么?

  • past_key_values (~cache_utils.Cache, optional) — Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the past_key_values returned by the model at a previous stage of decoding, when use_cache=True or config.use_cache=True.

    Only Cache instance is allowed as input, see our kv cache guide. If no past_key_values are passed, DynamicCache will be initialized by default.

    The model will output the same cache format that is fed as input.

    If past_key_values are used, the user is expected to input only unprocessed input_ids (those that don’t have their past key value states given to this model) of shape (batch_size, unprocessed_length) instead of all input_ids of shape (batch_size, sequence_length).

  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

    • 1 for tokens that are not masked,
    • 0 for tokens that are masked.

    注意力掩码是什么?

  • inputs_embeds (torch.Tensor of shape (batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passing input_ids you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert input_ids indices into associated vectors than the model’s internal embedding lookup matrix.
  • labels (torch.LongTensor of shape (batch_size, sequence_length), optional) — Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set labels = input_ids Indices are selected in [-100, 0, ..., config.vocab_size] All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size]
  • use_cache (bool, optional) — If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).
  • output_attentions (bool, optional) — Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.
  • output_hidden_states (bool, optional) — Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.
  • return_dict (bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
  • cache_position (torch.LongTensor of shape (sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily to position_ids, this tensor is not affected by padding. It is used to update the cache in the correct position and to infer the complete sequence length.
  • logits_to_keep (Union[int, torch.Tensor], optional, defaults to 0) — If an int, compute logits for the last logits_to_keep tokens. If 0, calculate logits for all input_ids (special case). Only last token logits are needed for generation, and calculating them only for that token can save memory, which becomes pretty significant for long sequences or large vocabulary size. If a torch.Tensor, must be 1D corresponding to the indices to keep in the sequence length dimension. This is useful when using packed tensor format (single dimension for batch and sequence length).

返回

transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or tuple(torch.FloatTensor)

A transformers.modeling_outputs.CausalLMOutputWithCrossAttentions or a tuple of torch.FloatTensor (if return_dict=False is passed or when config.return_dict=False) comprising various elements depending on the configuration (BloomConfig) and inputs.

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

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

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

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

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

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

  • cross_attentions (tuple(torch.FloatTensor), optional, returned when output_attentions=True is passed or when config.output_attentions=True) — Tuple of torch.FloatTensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

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

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

The BloomForCausalLM forward method, overrides the __call__ special method。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

BloomForSequenceClassification

class transformers.BloomForSequenceClassification

< >

( config: BloomConfig )

参数

  • config (BloomConfig) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the from_pretrained() method to load the model weights.

The Bloom Model transformer with a sequence classification head on top (linear layer).

BloomForSequenceClassification uses the last token in order to do the classification, as other causal models (e.g. GPT-1) do.

由于它在最后一个 token 上进行分类,因此需要知道最后一个 token 的位置。如果在配置中定义了 pad_token_id,它会找到批次中每行中最后一个非填充 token。如果没有定义 pad_token_id,它会简单地取批次中每行的最后一个值。由于在传入 inputs_embeds 而非 input_ids 时无法猜测填充 token,因此它会执行相同的操作(取批次中每行的最后一个值)。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.SequenceClassifierOutputWithPast 或者 tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, 形状为 (batch_size, input_ids_length)) — input_ids_length = sequence_length,如果 past_key_valuesNone;否则为 past_key_values.get_seq_length()(输入过去的关键值状态的 sequence_length)。词汇表中输入序列 token 的索引。

    如果使用了 past_key_values,则只能将那些尚未计算过去值的 input_ids 作为 input_ids 传入。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 past_key_values 组成,当 use_cache=Trueconfig.use_cache=True 时。

    只允许使用 Cache 实例,请参阅我们的 kv cache 指南。如果未传入 past_key_values,则默认初始化 DynamicCache

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅传入未处理的 input_ids(其过去键值状态未提供给此模型的那些),形状为 (batch_size, unprocessed_length),而不是所有 input_ids,形状为 (batch_size, sequence_length)

  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免在 padding token 索引上执行 attention 的掩码。Mask 值选择在 [0, 1] 之间:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

  • inputs_embeds (torch.Tensor, 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以直接传入嵌入表示,而不是传入 input_ids。如果您希望比模型的内部嵌入查找矩阵对如何将 input_ids 索引转换为关联向量有更多控制,则此选项很有用。
  • labels (torch.LongTensor, 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attention 张量。有关更多详细信息,请参阅返回的张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回的张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个简单的元组。

返回

transformers.modeling_outputs.SequenceClassifierOutputWithPasttuple(torch.FloatTensor)

一个 transformers.modeling_outputs.SequenceClassifierOutputWithPast 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),包含根据配置(BloomConfig)和输入而变化的各种元素。

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 分类损失(如果 config.num_labels==1,则为回归损失)。

  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(SoftMax 之前)。

  • past_key_values (Cache, optional, 当传递 use_cache=True 或当 config.use_cache=True 时返回) — 它是 Cache 实例。更多详情,请参阅我们的 kv cache 指南

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

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

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

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

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

BloomForSequenceClassification 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, BloomForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom")
>>> model = BloomForSequenceClassification.from_pretrained("bigscience/bloom")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_id = logits.argmax().item()
>>> model.config.id2label[predicted_class_id]
...

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = BloomForSequenceClassification.from_pretrained("bigscience/bloom", num_labels=num_labels)

>>> labels = torch.tensor([1])
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, BloomForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom")
>>> model = BloomForSequenceClassification.from_pretrained("bigscience/bloom", problem_type="multi_label_classification")

>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]

>>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
>>> num_labels = len(model.config.id2label)
>>> model = BloomForSequenceClassification.from_pretrained(
...     "bigscience/bloom", num_labels=num_labels, problem_type="multi_label_classification"
... )

>>> labels = torch.sum(
...     torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
... ).to(torch.float)
>>> loss = model(**inputs, labels=labels).loss

BloomForTokenClassification

class transformers.BloomForTokenClassification

< >

( config: BloomConfig )

参数

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

一个带有 token 分类头的 Bloom transformer(在隐藏状态输出之上加一个线性层),例如用于命名实体识别(NER)任务。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None past_key_values: transformers.cache_utils.Cache | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.Tensor | None = None use_cache: bool | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor, 形状为 (batch_size, input_ids_length)) — input_ids_length = sequence_length,如果 past_key_valuesNone;否则为 past_key_values.get_seq_length()(输入过去的关键值状态的 sequence_length)。词汇表中输入序列 token 的索引。

    如果使用了 past_key_values,则只能将那些尚未计算过去值的 input_ids 作为 input_ids 传入。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • past_key_values (~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由模型在解码的先前阶段返回的 past_key_values 组成,当 use_cache=Trueconfig.use_cache=True 时。

    只允许使用 Cache 实例,请参阅我们的 kv cache 指南。如果未传入 past_key_values,则默认初始化 DynamicCache

    模型将输出与输入相同的缓存格式。

    如果使用了 past_key_values,用户应仅传入未处理的 input_ids(其过去键值状态未提供给此模型的那些),形状为 (batch_size, unprocessed_length),而不是所有 input_ids,形状为 (batch_size, sequence_length)

  • attention_mask (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 用于避免在 padding token 索引上执行 attention 的掩码。Mask 值选择在 [0, 1] 之间:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

  • inputs_embeds (torch.Tensor, 形状为 (batch_size, sequence_length, hidden_size), 可选) — 可选地,您可以直接传入嵌入表示,而不是传入 input_ids。如果您希望比模型的内部嵌入查找矩阵对如何将 input_ids 索引转换为关联向量有更多控制,则此选项很有用。
  • labels (torch.LongTensor, 形状为 (batch_size,), 可选) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attention 张量。有关更多详细信息,请参阅返回的张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回的张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个简单的元组。

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.TokenClassifierOutput 或一个 torch.FloatTensor 元组(如果传入 return_dict=False 或当 config.return_dict=False 时),包含根据配置(BloomConfig)和输入而变化的各种元素。

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

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

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

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

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

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

BloomForTokenClassification 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, BloomForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom")
>>> model = BloomForTokenClassification.from_pretrained("bigscience/bloom")

>>> inputs = tokenizer(
...     "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
... )

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> predicted_token_class_ids = logits.argmax(-1)

>>> # Note that tokens are classified rather then input words which means that
>>> # there might be more predicted token classes than words.
>>> # Multiple token classes might account for the same word
>>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes
...

>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
>>> round(loss.item(), 2)
...

BloomForQuestionAnswering

class transformers.BloomForQuestionAnswering

< >

( config model_args: ~utils.generic.ModelArgs | None = None adapter_args: ~utils.generic.AdapterArgs | None = None lora_args: ~utils.generic.LoRAArgs | None = None tokenizer_args: ~utils.generic.TokenizerArgs | None = None dataset_args: ~utils.generic.DatasetArgs | None = None data_args: ~utils.generic.DataArgs | None = None training_args: ~utils.generic.TrainingArgs | None = None generation_args: ~utils.generic.GenerationArgs | None = None vision_tower_args: ~utils.generic.VisionTowerArgs | None = None qlora_args: ~utils.generic.QLoRAArgs | None = None vision_tower_template_args: ~utils.generic.VisionTowerTemplateArgs | None = None video_tower_args: ~utils.generic.VideoTowerArgs | None = None vision_config: ~utils.generic.VisionConfig | None = None video_config: ~utils.generic.VideoConfig | None = None load_dataset: bool | None = None load_data_collator: bool | None = None load_processor: bool | None = None load_lora_adapter: bool | None = None load_adapter: bool | None = None load_qlora_adapter: bool | None = None **kwargs: typing_extensions.Unpack[transformers.modeling_utils.PreTrainedModelKwargs] )

参数

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

带有顶部跨度分类头的 Bloom Transformer,用于提取式问答任务,如 SQuAD(在隐藏状态输出之上添加一个线性层来计算span start logitsspan end logits)。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( input_ids: torch.LongTensor | None = None attention_mask: torch.FloatTensor | None = None inputs_embeds: torch.FloatTensor | None = None start_positions: torch.LongTensor | None = None end_positions: torch.LongTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None return_dict: bool | None = None **kwargs ) transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, input_ids_length)) — 词汇表中输入序列 token 的索引。

    如果使用了 past_key_values,则只能将尚未计算过去值的 input_ids 作为 input_ids 传递。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    输入 ID 是什么?

  • attention_mask (torch.FloatTensor of shape (batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行 attention 的掩码。掩码值选择在 [0, 1] 之间:

    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    Attention 掩码是什么?

  • inputs_embeds (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size), optional) — 可选,您可以选择直接传递嵌入表示,而不是传递 input_ids。如果您想比模型内部的嵌入查找矩阵更精确地控制如何将 input_ids 索引转换为相关的向量,这将非常有用。
  • start_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算 token 分类损失的已标记跨度开始位置(索引)的标签。位置会钳制到序列长度(sequence_length)。序列外的其他位置不会计入损失计算。
  • end_positions (torch.LongTensor of shape (batch_size,), optional) — 用于计算 token 分类损失的已标记跨度结束位置(索引)的标签。位置会钳制到序列长度(sequence_length)。序列外的其他位置不会计入损失计算。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attention 张量。有关更多详细信息,请参见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通元组。

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

根据配置(BloomConfig)和输入,返回一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 对象或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时)。

  • loss (torch.FloatTensor of shape (1,), 可选, 当提供 labels 时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。

  • start_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。

  • end_logits (torch.FloatTensor of shape (batch_size, sequence_length)) — 范围结束分数(SoftMax 之前)。

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

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

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

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

BloomForQuestionAnswering 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> from transformers import AutoTokenizer, BloomForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("bigscience/bloom")
>>> model = BloomForQuestionAnswering.from_pretrained("bigscience/bloom")

>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"

>>> inputs = tokenizer(question, text, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()

>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
>>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
...

>>> # target is "nice puppet"
>>> target_start_index = torch.tensor([14])
>>> target_end_index = torch.tensor([15])

>>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
>>> loss = outputs.loss
>>> round(loss.item(), 2)
...
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.