Transformers 文档
BLOOM
并获得增强的文档体验
开始使用
此模型于 2022-11-09 发布,并于 2022-06-09 添加到 Hugging Face Transformers。
BLOOM
概述
通过 BigScience Workshop 提出了 BLOOM 模型及其各种版本。BigScience 受到其他开放科学倡议的启发,这些倡议汇集了研究人员的时间和资源,以集体实现更大的影响力。BLOOM 的架构与 GPT3(用于下一个 token 预测的自回归模型)基本相似,但已在 46 种不同的语言和 13 种编程语言上进行了训练。该模型有几个较小的版本,也在同一数据集上进行了训练。BLOOM 有以下版本可供选择:
资源
以下是官方 Hugging Face 和社区(用 🌎 表示)资源列表,可帮助您开始使用 BLOOM。如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将对其进行审查!资源最好能展示一些新的内容,而不是复制现有资源。
BloomForCausalLM由此 因果语言建模示例脚本 和 Notebook 支持。
另请参阅
⚡️ 推理
- 关于“优化故事:Bloom 推理”的博客 Optimization story: Bloom inference。
- 关于“使用 DeepSpeed 和 Accelerate 实现令人难以置信的快速 BLOOM 推理”的博客 Incredibly Fast BLOOM Inference with DeepSpeed and Accelerate。
⚙️ 训练
- 关于“BLOOM 训练背后的技术”的博客 The Technology Behind BLOOM Training。
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.configBloomModel
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.BaseModelOutputWithPastAndCrossAttentions 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor, 形状为(batch_size, input_ids_length)) —input_ids_length=sequence_length,如果past_key_values为None;否则为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()。
- past_key_values (
~cache_utils.Cache, 可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由模型在之前的解码阶段返回的past_key_values组成,此时use_cache=True或config.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.Tensorof 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.LongTensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.LongTensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_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.BaseModelOutputWithPastAndCrossAttentions 或 tuple(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=Truein the cross-attention blocks) that can be used (seepast_key_valuesinput) 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 whenoutput_attentions=Trueandconfig.add_cross_attention=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.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
< source >( 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
< source >( 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.LongTensorof shape(batch_size, input_ids_length)) —input_ids_length=sequence_lengthifpast_key_valuesisNoneelsepast_key_values.get_seq_length()(sequence_lengthof input past key value states). Indices of input sequence tokens in the vocabulary.If
past_key_valuesis used, onlyinput_idsthat do not have their past calculated should be passed asinput_ids.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- 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 thepast_key_valuesreturned by the model at a previous stage of decoding, whenuse_cache=Trueorconfig.use_cache=True.Only Cache instance is allowed as input, see our kv cache guide. If no
past_key_valuesare passed, DynamicCache will be initialized by default.The model will output the same cache format that is fed as input.
If
past_key_valuesare used, the user is expected to input only unprocessedinput_ids(those that don’t have their past key value states given to this model) of shape(batch_size, unprocessed_length)instead of allinput_idsof shape(batch_size, sequence_length). - attention_mask (
torch.Tensorof 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.Tensorof shape(batch_size, sequence_length, hidden_size), optional) — Optionally, instead of passinginput_idsyou can choose to directly pass an embedded representation. This is useful if you want more control over how to convertinput_idsindices into associated vectors than the model’s internal embedding lookup matrix. - labels (
torch.LongTensorof shape(batch_size, sequence_length), optional) — Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can setlabels = input_idsIndices are selected in[-100, 0, ..., config.vocab_size]All labels set to-100are ignored (masked), the loss is only computed for labels in[0, ..., config.vocab_size] - use_cache (
bool, optional) — If set toTrue,past_key_valueskey value states are returned and can be used to speed up decoding (seepast_key_values). - output_attentions (
bool, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentionsunder returned tensors for more detail. - output_hidden_states (
bool, optional) — Whether or not to return the hidden states of all layers. Seehidden_statesunder returned tensors for more detail. - return_dict (
bool, optional) — Whether or not to return a ModelOutput instead of a plain tuple. - cache_position (
torch.LongTensorof shape(sequence_length), optional) — Indices depicting the position of the input sequence tokens in the sequence. Contrarily toposition_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 to0) — If anint, compute logits for the lastlogits_to_keeptokens. If0, calculate logits for allinput_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 atorch.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 whenoutput_attentions=Trueis passed or whenconfig.output_attentions=True) — Tuple oftorch.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
< source >( 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
< source >( 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_values为None;否则为past_key_values.get_seq_length()(输入过去的关键值状态的sequence_length)。词汇表中输入序列 token 的索引。如果使用了
past_key_values,则只能将那些尚未计算过去值的input_ids作为input_ids传入。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由模型在解码的先前阶段返回的past_key_values组成,当use_cache=True或config.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。
- 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.SequenceClassifierOutputWithPast 或 tuple(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).lossBloomForTokenClassification
class transformers.BloomForTokenClassification
< source >( config: BloomConfig )
参数
- config (
BloomConfig) — 模型的配置类,包含模型的所有参数。使用配置初始化不会加载与模型相关的权重,仅加载配置。请查看 from_pretrained() 方法来加载模型权重。
一个带有 token 分类头的 Bloom transformer(在隐藏状态输出之上加一个线性层),例如用于命名实体识别(NER)任务。
此模型继承自 PreTrainedModel。查看其父类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。
forward
< source >( 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.TokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor, 形状为(batch_size, input_ids_length)) —input_ids_length=sequence_length,如果past_key_values为None;否则为past_key_values.get_seq_length()(输入过去的关键值状态的sequence_length)。词汇表中输入序列 token 的索引。如果使用了
past_key_values,则只能将那些尚未计算过去值的input_ids作为input_ids传入。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- past_key_values (
~cache_utils.Cache, 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常由模型在解码的先前阶段返回的past_key_values组成,当use_cache=True或config.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。
- 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.TokenClassifierOutput 或 tuple(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 logits和span 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.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensorof shape(batch_size, input_ids_length)) — 词汇表中输入序列 token 的索引。如果使用了
past_key_values,则只能将尚未计算过去值的input_ids作为input_ids传递。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensorof shape(batch_size, sequence_length), optional) — 用于避免对填充 token 索引执行 attention 的掩码。掩码值选择在[0, 1]之间:- 1 表示未掩码的 token,
- 0 表示已掩码的 token。
- inputs_embeds (
torch.FloatTensorof shape(batch_size, sequence_length, hidden_size), optional) — 可选,您可以选择直接传递嵌入表示,而不是传递input_ids。如果您想比模型内部的嵌入查找矩阵更精确地控制如何将input_ids索引转换为相关的向量,这将非常有用。 - start_positions (
torch.LongTensorof shape(batch_size,), optional) — 用于计算 token 分类损失的已标记跨度开始位置(索引)的标签。位置会钳制到序列长度(sequence_length)。序列外的其他位置不会计入损失计算。 - end_positions (
torch.LongTensorof 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.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
根据配置(BloomConfig)和输入,返回一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 对象或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时)。
-
loss (
torch.FloatTensorof shape(1,), 可选, 当提供labels时返回) — 总范围提取损失是起始位置和结束位置的交叉熵之和。 -
start_logits (
torch.FloatTensorof shape(batch_size, sequence_length)) — 范围起始分数(SoftMax 之前)。 -
end_logits (
torch.FloatTensorof 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)
...