Transformers 文档

DistilBERT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2019-10-02 发布,并于 2020-11-16 添加到 Hugging Face Transformers。

PyTorch SDPA FlashAttention

DistilBERT

DistilBERT 通过知识蒸馏进行预训练,以创建更小、推理速度更快且训练计算量更少的模型。通过预训练期间的三重损失目标(语言建模损失、蒸馏损失、余弦距离损失),DistilBERT 展现出与更大的 Transformer 语言模型相似的性能。

您可以在 DistilBERT 组织下找到所有原始 DistilBERT 检查点。

点击右侧边栏的 DistilBERT 模型,了解更多关于将 DistilBERT 应用于不同语言任务的示例。

下面的示例演示了如何使用 PipelineAutoModel 以及从命令行进行文本分类。

流水线
自动模型
Transformers CLI
import torch
from transformers import pipeline

classifier = pipeline(
    task="text-classification",
    model="distilbert-base-uncased-finetuned-sst-2-english",
    dtype=torch.float16,
    device=0
)

result = classifier("I love using Hugging Face Transformers!")
print(result)
# Output: [{'label': 'POSITIVE', 'score': 0.9998}]

注意事项

  • DistilBERT 没有 token_type_ids,您无需指明哪个 token 属于哪个段。只需使用分隔符 token tokenizer.sep_token (或 [SEP]) 分隔您的段即可。
  • DistilBERT 没有选择输入位置的选项 (position_ids 输入)。如果需要,可以添加此功能,如有需要请告知我们。

DistilBertConfig

class transformers.DistilBertConfig

< >

( vocab_size = 30522 max_position_embeddings = 512 sinusoidal_pos_embds = False n_layers = 6 n_heads = 12 dim = 768 hidden_dim = 3072 dropout = 0.1 attention_dropout = 0.1 activation = 'gelu' initializer_range = 0.02 qa_dropout = 0.1 seq_classif_dropout = 0.2 pad_token_id = 0 eos_token_id = None bos_token_id = None tie_word_embeddings = True **kwargs )

参数

  • vocab_size (int, 可选, 默认为 30522) — DistilBERT 模型词汇量大小。定义调用 DistilBertModel 时传入的 inputs_ids 可以表示的不同 token 的数量。
  • max_position_embeddings (int, 可选, 默认为 512) — 该模型可能使用的最大序列长度。通常将其设置得较大,以防万一(例如,512 或 1024 或 2048)。
  • sinusoidal_pos_embds (boolean, 可选, 默认为 False) — 是否使用正弦位置嵌入。
  • n_layers (int, 可选, 默认为 6) — Transformer 编码器中的隐藏层数。
  • n_heads (int, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数。
  • dim (int, 可选, 默认为 768) — 编码器层和池化层的维度。
  • hidden_dim (int, 可选, 默认为 3072) — Transformer 编码器中“中间”(通常称为前馈)层的大小。
  • dropout (float, 可选, 默认为 0.1) — 嵌入层、编码器和池化层中所有全连接层的 dropout 概率。
  • attention_dropout (float, 可选, 默认为 0.1) — 注意力概率的 dropout 比率。
  • activation (strCallable, 可选, 默认为 "gelu") — 编码器和池化层中的非线性激活函数 (函数或字符串)。如果为字符串,则支持 "gelu""relu""silu""gelu_new"
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • qa_dropout (float, 可选, 默认为 0.1) — 问题回答模型 DistilBertForQuestionAnswering 中使用的 dropout 概率。
  • seq_classif_dropout (float, 可选, 默认为 0.2) — 序列分类和多选题模型 DistilBertForSequenceClassification 中使用的 dropout 概率。

这是用于存储 DistilBertModel 配置的配置类。它用于根据指定的参数实例化 DistilBERT 模型,定义模型架构。使用默认值实例化配置将产生与 DistilBERT distilbert-base-uncased 架构相似的配置。

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

示例

>>> from transformers import DistilBertConfig, DistilBertModel

>>> # Initializing a DistilBERT configuration
>>> configuration = DistilBertConfig()

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

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

DistilBertTokenizer

class transformers.DistilBertTokenizer

< >

( *args do_lower_case: bool = True **kwargs )

DistilBertTokenizerFast

class transformers.DistilBertTokenizer

< >

( *args do_lower_case: bool = True **kwargs )

DistilBertModel

class transformers.DistilBertModel

< >

( config: PreTrainedConfig )

参数

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

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

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

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

forward

< >

( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None position_ids: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

参数

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

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

    输入 ID 是什么?

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

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

    注意力掩码是什么?

  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, hidden_size), 可选) — 可选地,您可以直接传递嵌入表示,而不是传递 input_ids。如果您想比模型的内部嵌入查找矩阵更精细地控制如何将 input_ids 索引转换为关联向量,这很有用。
  • position_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 索引输入序列 token 在位置嵌入中的位置。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

返回

transformers.modeling_outputs.BaseModelOutputtuple(torch.FloatTensor)

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

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

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

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

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

DistilBertForMaskedLM

class transformers.DistilBertForMaskedLM

< >

( config: PreTrainedConfig )

参数

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

带有顶部的 masked language modeling 头的 DistilBert 模型。

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

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

forward

< >

( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.LongTensor | None = None position_ids: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

参数

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

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

    什么是输入 ID?

  • attention_mask (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于避免对 padding token 索引执行 attention 的掩码。掩码值选择为 [0, 1]
    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention mask?

  • inputs_embeds (torch.FloatTensor, shape (batch_size, num_choices, hidden_size), optional) — 可选,而不是传递 input_ids,您可以选择直接传递嵌入表示。如果您希望比模型的内部嵌入查找矩阵对如何将 input_ids 索引转换为关联向量有更多控制,这将非常有用。
  • labels (torch.LongTensor, shape (batch_size, sequence_length), optional) — 用于计算掩码语言模型损失的标签。索引应在 [-100, 0, ..., config.vocab_size] 范围内(参见 input_ids 文档字符串)。索引设置为 -100 的 token 将被忽略(掩码),损失仅为具有 [0, ..., config.vocab_size] 范围内标签的 token 计算。
  • position_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 索引输入序列 token 在位置嵌入中的位置。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

返回

transformers.modeling_outputs.MaskedLMOutputtuple(torch.FloatTensor)

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

  • loss (形状为 (1,)torch.FloatTensor可选,当提供 labels 时返回) — 掩码语言建模 (MLM) 损失。

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

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

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

示例

>>> from transformers import AutoTokenizer, DistilBertForMaskedLM
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = DistilBertForMaskedLM.from_pretrained("distilbert-base-uncased")

>>> inputs = tokenizer("The capital of France is <mask>.", return_tensors="pt")

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

>>> # retrieve index of <mask>
>>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]

>>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
>>> tokenizer.decode(predicted_token_id)
...

>>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
>>> # mask labels of non-<mask> tokens
>>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)

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

DistilBertForSequenceClassification

class transformers.DistilBertForSequenceClassification

< >

( config: PreTrainedConfig )

参数

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

DistilBert Model transformer,顶部有一个序列分类/回归头(池化输出之上的一个线性层),例如用于 GLUE 任务。

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

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

forward

< >

( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.LongTensor | None = None position_ids: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 词汇表中输入序列 token 的索引。默认情况下会忽略 padding。

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

    什么是输入 ID?

  • attention_mask (torch.Tensor, shape (batch_size, sequence_length), optional) — 用于避免对 padding token 索引执行 attention 的掩码。掩码值选择为 [0, 1]
    • 1 表示未掩码的 token,
    • 0 表示已掩码的 token。

    什么是 attention masks?

  • inputs_embeds (torch.Tensor, shape (batch_size, sequence_length, hidden_size), optional) — 可选,而不是传递 input_ids,您可以选择直接传递嵌入表示。如果您希望比模型的内部嵌入查找矩阵对如何将 input_ids 索引转换为关联向量有更多控制,这将非常有用。
  • labels (torch.LongTensor, shape (batch_size,), optional) — 用于计算序列分类/回归损失的标签。索引应在 [0, ..., config.num_labels - 1] 范围内。如果 config.num_labels == 1,则计算回归损失(均方损失);如果 config.num_labels > 1,则计算分类损失(交叉熵)。
  • position_ids (torch.Tensor, shape (batch_size, sequence_length), optional) — 索引输入序列 token 在位置嵌入中的位置。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

返回

transformers.modeling_outputs.SequenceClassifierOutputtuple(torch.FloatTensor)

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

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

  • logits (形状为 (batch_size, config.num_labels)torch.FloatTensor) — 分类(如果 config.num_labels==1,则为回归)分数(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 后的注意力权重,用于计算自注意力头中的加权平均值。

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

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

单标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, DistilBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")

>>> 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 = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=num_labels)

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

多标签分类示例

>>> import torch
>>> from transformers import AutoTokenizer, DistilBertForSequenceClassification

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = DistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", 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 = DistilBertForSequenceClassification.from_pretrained(
...     "distilbert-base-uncased", 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

DistilBertForMultipleChoice

class transformers.DistilBertForMultipleChoice

< >

( config: PreTrainedConfig )

参数

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

带有多个选项分类头的 Distilbert 模型(在池化输出之上有一个线性层和 softmax),例如用于 RocStories/SWAG 任务。

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

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

forward

< >

( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.LongTensor | None = None position_ids: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, num_choices, sequence_length)) — Vocabulary中输入序列 token 的索引。Indices 可以使用 AutoTokenizer 获取。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是 input IDs?

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

    什么是 attention masks?

  • inputs_embeds (torch.FloatTensor of shape (batch_size, num_choices, 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,), optional) — For computing the multiple choice classification loss. Indices should be in [0, ..., num_choices-1] where num_choices is the size of the second dimension of the input tensors. (See input_ids above)
  • position_ids (torch.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    什么是 position IDs?

返回

transformers.modeling_outputs.MultipleChoiceModelOutputtuple(torch.FloatTensor)

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

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

  • logits (形状为 (batch_size, num_choices)torch.FloatTensor) — num_choices 是输入张量的第二维大小。(请参阅上面的 input_ids)。

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

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

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

示例

>>> from transformers import AutoTokenizer, DistilBertForMultipleChoice
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-cased")
>>> model = DistilBertForMultipleChoice.from_pretrained("distilbert-base-cased")

>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."
>>> labels = torch.tensor(0).unsqueeze(0)  # choice0 is correct (according to Wikipedia ;)), batch size 1

>>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels)  # batch size is 1

>>> # the linear classifier still needs to be trained
>>> loss = outputs.loss
>>> logits = outputs.logits

DistilBertForTokenClassification

class transformers.DistilBertForTokenClassification

< >

( config: PreTrainedConfig )

参数

  • config (PreTrainedConfig) — 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.

带有 token 分类头的 Distilbert transformer,位于顶部(在 hidden-states 输出之上有一个线性层),例如用于命名实体识别 (NER) 任务。

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

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

forward

< >

( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None labels: torch.LongTensor | None = None position_ids: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.Tensor of shape (batch_size, sequence_length), optional) — Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.

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

    什么是 input IDs?

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

    什么是 attention masks?

  • 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) — For computing the token classification loss. Indices should be in [0, ..., config.num_labels - 1].
  • position_ids (torch.Tensor of shape (batch_size, sequence_length), optional) — Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, config.n_positions - 1].

    什么是 position IDs?

返回

transformers.modeling_outputs.TokenClassifierOutputtuple(torch.FloatTensor)

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

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

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

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

示例

>>> from transformers import AutoTokenizer, DistilBertForTokenClassification
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = DistilBertForTokenClassification.from_pretrained("distilbert-base-uncased")

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

DistilBertForQuestionAnswering

class transformers.DistilBertForQuestionAnswering

< >

( config: PreTrainedConfig )

参数

  • config (PreTrainedConfig) — 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.

带有 span 分类头的 Distilbert transformer,用于抽取式问答任务,如 SQuAD(在 hidden-states 输出之上有一个线性层,用于计算 span start logitsspan end logits)。

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

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

forward

< >

( input_ids: torch.Tensor | None = None attention_mask: torch.Tensor | None = None inputs_embeds: torch.Tensor | None = None start_positions: torch.Tensor | None = None end_positions: torch.Tensor | None = None position_ids: torch.Tensor | None = None **kwargs: typing_extensions.Unpack[transformers.utils.generic.TransformersKwargs] ) transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size, num_choices)) — Indices of input sequence tokens in the vocabulary.

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

    什么是 input IDs?

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

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

    什么是 attention 掩码?

  • inputs_embeds (torch.FloatTensor, 形状为 (batch_size, num_choices, hidden_size), 可选) — 如果不想传递 input_ids,可以选择直接传递嵌入表示。如果你希望比模型的内部嵌入查找矩阵对如何将 input_ids 索引转换为相关向量有更多的控制,这会很有用。
  • start_positions (torch.Tensor, 形状为 (batch_size,), 可选) — 用于计算 token 分类损失的已标记跨度的起始位置 (索引) 的标签。位置会被限制在序列长度 (sequence_length) 内。序列外部的位置不计入损失计算。
  • end_positions (torch.Tensor, 形状为 (batch_size,), 可选) — 用于计算 token 分类损失的已标记跨度的结束位置 (索引) 的标签。位置会被限制在序列长度 (sequence_length) 内。序列外部的位置不计入损失计算。
  • position_ids (torch.Tensor, 形状为 (batch_size, sequence_length), 可选) — 每个输入序列 token 在位置嵌入中的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

返回

transformers.modeling_outputs.QuestionAnsweringModelOutputtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或一个元组 (如果传递了 return_dict=False 或者当 config.return_dict=False 时) ,其中包含根据配置 (DistilBertConfig) 和输入而变化的各种元素。

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

DistilBertForQuestionAnswering 的 forward 方法会覆盖 __call__ 特殊方法。

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

示例

>>> from transformers import AutoTokenizer, DistilBertForQuestionAnswering
>>> import torch

>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = DistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")

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