Transformers 文档
DistilBERT
并获取增强的文档体验
开始使用
DistilBERT
概述
DistilBERT 模型在博客文章 更小、更快、更便宜、更轻:DistilBERT 介绍,BERT 的精馏版本 和论文 DistilBERT,BERT 的精馏版本:更小、更快、更便宜、更轻 中提出。DistilBERT 是一款通过精馏 BERT base 训练的小型、快速、廉价且轻量级的 Transformer 模型。它的参数比 google-bert/bert-base-uncased 少 40%,运行速度快 60%,同时在 GLUE 语言理解基准测试中保留了 BERT 超过 95% 的性能。
以下是论文的摘要
随着从大规模预训练模型进行迁移学习在自然语言处理 (NLP) 中变得越来越普遍,在边缘和/或计算训练或推理预算受限的情况下操作这些大型模型仍然具有挑战性。在这项工作中,我们提出了一种预训练一个更小的通用语言表示模型的方法,称为 DistilBERT,然后可以像其更大的同类模型一样,在各种任务上进行微调并获得良好的性能。虽然大多数先前的工作都研究了使用蒸馏来构建特定于任务的模型,但我们在预训练阶段利用知识蒸馏,并表明可以将 BERT 模型的大小减少 40%,同时保留其 97% 的语言理解能力,并提高 60% 的速度。为了利用较大模型在预训练期间学习到的归纳偏差,我们引入了三重损失,结合了语言建模、蒸馏和余弦距离损失。我们更小、更快、更轻的模型预训练成本更低,并且我们在概念验证实验和比较设备研究中证明了其在设备上计算方面的能力。
此模型由 victorsanh 贡献。此模型的 jax 版本由 kamalkraj 贡献。原始代码可以在这里找到。
使用技巧
DistilBERT 没有
token_type_ids
,您无需指明哪个 token 属于哪个 segment。只需使用分隔 tokentokenizer.sep_token
(或[SEP]
) 分隔您的 segment 即可。DistilBERT 没有选择输入位置的选项 (
position_ids
输入)。如果需要,可以添加此选项,如果您需要此选项,请告知我们。与 BERT 相同,但规模更小。通过预训练 BERT 模型的蒸馏进行训练,这意味着它经过训练以预测与较大模型相同的概率。实际目标是以下各项的组合:
- 找到与教师模型相同的概率
- 正确预测 masked tokens (但没有下一句预测目标)
- 学生模型和教师模型的隐藏状态之间的余弦相似度
使用缩放点积注意力 (SDPA)
PyTorch 在 torch.nn.functional
中包含一个原生的缩放点积注意力 (SDPA) 运算符。此函数包含多个实现,可以根据输入和正在使用的硬件应用。有关更多信息,请参阅官方文档或 GPU 推理页面。
当实现可用时,torch>=2.1.1
默认使用 SDPA,但您也可以在 from_pretrained()
中设置 attn_implementation="sdpa"
以显式请求使用 SDPA。
from transformers import DistilBertModel
model = DistilBertModel.from_pretrained("distilbert-base-uncased", torch_dtype=torch.float16, attn_implementation="sdpa")
为了获得最佳加速效果,我们建议以半精度 (例如 torch.float16
或 torch.bfloat16
) 加载模型。
在一个本地基准测试 (NVIDIA GeForce RTX 2060-8GB, PyTorch 2.3.1, OS Ubuntu 20.04) 中,使用 float16
和带有 MaskedLM head 的 distilbert-base-uncased
模型,我们看到了以下训练和推理期间的加速效果。
训练
num_training_steps | batch_size | seq_len | is cuda | 每个批次的时间 (eager - s) | 每个批次的时间 (sdpa - s) | 加速 (%) | Eager 峰值内存 (MB) | sdpa 峰值内存 (MB) | 内存节省 (%) |
---|---|---|---|---|---|---|---|---|---|
100 | 1 | 128 | False | 0.010 | 0.008 | 28.870 | 397.038 | 399.629 | -0.649 |
100 | 1 | 256 | False | 0.011 | 0.009 | 20.681 | 412.505 | 412.606 | -0.025 |
100 | 2 | 128 | False | 0.011 | 0.009 | 23.741 | 412.213 | 412.606 | -0.095 |
100 | 2 | 256 | False | 0.015 | 0.013 | 16.502 | 427.491 | 425.787 | 0.400 |
100 | 4 | 128 | False | 0.015 | 0.013 | 13.828 | 427.491 | 425.787 | 0.400 |
100 | 4 | 256 | False | 0.025 | 0.022 | 12.882 | 594.156 | 502.745 | 18.182 |
100 | 8 | 128 | False | 0.023 | 0.022 | 8.010 | 545.922 | 502.745 | 8.588 |
100 | 8 | 256 | False | 0.046 | 0.041 | 12.763 | 983.450 | 798.480 | 23.165 |
推理
num_batches | batch_size | seq_len | is cuda | is half | use mask | 每个 token 的延迟 eager (ms) | 每个 token 的延迟 SDPA (ms) | 加速 (%) | 内存 eager (MB) | 内存 BT (MB) | 内存节省 (%) |
---|---|---|---|---|---|---|---|---|---|---|---|
50 | 2 | 64 | True | True | True | 0.032 | 0.025 | 28.192 | 154.532 | 155.531 | -0.642 |
50 | 2 | 128 | True | True | True | 0.033 | 0.025 | 32.636 | 157.286 | 157.482 | -0.125 |
50 | 4 | 64 | True | True | True | 0.032 | 0.026 | 24.783 | 157.023 | 157.449 | -0.271 |
50 | 4 | 128 | True | True | True | 0.034 | 0.028 | 19.299 | 162.794 | 162.269 | 0.323 |
50 | 8 | 64 | True | True | True | 0.035 | 0.028 | 25.105 | 160.958 | 162.204 | -0.768 |
50 | 8 | 128 | True | True | True | 0.052 | 0.046 | 12.375 | 173.155 | 171.844 | 0.763 |
50 | 16 | 64 | True | True | True | 0.051 | 0.045 | 12.882 | 172.106 | 171.713 | 0.229 |
50 | 16 | 128 | True | True | True | 0.096 | 0.081 | 18.524 | 191.257 | 191.517 | -0.136 |
资源
以下是官方 Hugging Face 和社区 (用 🌎 表示) 资源列表,可帮助您开始使用 DistilBERT。如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
- 一篇关于使用 DistilBERT 开始使用 Python 进行情感分析的博文。
- 一篇关于如何使用 Blurr 训练 DistilBERT 进行序列分类的博文。
- 一篇关于如何使用 Ray 调整 DistilBERT 超参数的博文。
- 一篇关于如何使用 Hugging Face 和 Amazon SageMaker 训练 DistilBERT的博文。
- 一个关于如何 微调 DistilBERT 用于多标签分类的 notebook。 🌎
- 一个关于如何使用 PyTorch 微调 DistilBERT 用于多类别分类的 notebook。 🌎
- 一个关于如何在 TensorFlow 中 微调 DistilBERT 用于文本分类的 notebook。 🌎
- DistilBertForSequenceClassification 受到此示例脚本和notebook的支持。
- TFDistilBertForSequenceClassification 受到此示例脚本和notebook的支持。
- FlaxDistilBertForSequenceClassification 受到此示例脚本和notebook的支持。
- 文本分类任务指南
- DistilBertForTokenClassification 受到此示例脚本和notebook的支持。
- TFDistilBertForTokenClassification 受到此示例脚本和notebook的支持。
- FlaxDistilBertForTokenClassification 受到此示例脚本的支持。
- Token 分类是 🤗 Hugging Face Course 的章节。
- Token 分类任务指南
- DistilBertForMaskedLM 受到此示例脚本和notebook的支持。
- TFDistilBertForMaskedLM 受到此示例脚本和notebook的支持。
- FlaxDistilBertForMaskedLM 受到此示例脚本和notebook的支持。
- Masked language modeling 是 🤗 Hugging Face Course 的章节。
- Masked language modeling 任务指南
- DistilBertForQuestionAnswering 受到此示例脚本和notebook的支持。
- TFDistilBertForQuestionAnswering 受到此示例脚本和notebook的支持。
- FlaxDistilBertForQuestionAnswering 受到此示例脚本的支持。
- Question answering 是 🤗 Hugging Face Course 的章节。
- 问题解答任务指南
多项选择
- DistilBertForMultipleChoice 受到此示例脚本和notebook的支持。
- TFDistilBertForMultipleChoice 受到此示例脚本和notebook的支持。
- 多项选择任务指南
⚗️ 优化
- 一篇关于如何使用 🤗 Optimum 和 Intel 量化 DistilBERT 的博文。
- 一篇关于如何使用 🤗 Optimum 优化 Transformers 以在 GPU 上运行 的博文。
- 一篇关于使用 Hugging Face Optimum 优化 Transformers 的博文。
⚡️ 推理
- 一篇关于如何使用 DistilBERT 通过 Hugging Face Transformers 和 AWS Inferentia 加速 BERT 推理的博文。
- 一篇关于使用 Hugging Face 的 Transformers、DistilBERT 和 Amazon SageMaker 进行 Serverless 推理的博文。
🚀 部署
- 一篇关于如何在 Google Cloud 上 部署 DistilBERT 的博文。
- 一篇关于如何使用 Amazon SageMaker 部署 DistilBERT 的博文。
- 一篇关于如何使用 Hugging Face Transformers、Amazon SageMaker 和 Terraform 模块 部署 BERT 的博文。
结合 DistilBERT 和 Flash Attention 2
首先,请确保安装最新版本的 Flash Attention 2 以包含滑动窗口注意力功能。
pip install -U flash-attn --no-build-isolation
还要确保您的硬件与 Flash-Attention 2 兼容。请阅读 flash-attn 仓库的官方文档以了解更多信息。同时确保以半精度 (例如 torch.float16
) 加载您的模型
要加载和运行使用 Flash Attention 2 的模型,请参考以下代码片段
>>> import torch
>>> from transformers import AutoTokenizer, AutoModel
>>> device = "cuda" # the device to load the model onto
>>> tokenizer = AutoTokenizer.from_pretrained('distilbert/distilbert-base-uncased')
>>> model = AutoModel.from_pretrained("distilbert/distilbert-base-uncased", torch_dtype=torch.float16, attn_implementation="flash_attention_2")
>>> text = "Replace me by any text you'd like."
>>> encoded_input = tokenizer(text, return_tensors='pt').to(device)
>>> model.to(device)
>>> output = model(**encoded_input)
DistilBertConfig
class transformers.DistilBertConfig
< source >( 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 **kwargs )
参数
- vocab_size (
int
, 可选, 默认为 30522) — DistilBERT 模型的词汇表大小。定义了调用 DistilBertModel 或 TFDistilBertModel 时传递的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 编码器中 “intermediate” (通常称为 feed-forward) 层的尺寸。 - dropout (
float
, 可选, 默认为 0.1) — embeddings、编码器和池化器中所有全连接层的 dropout 概率。 - attention_dropout (
float
, 可选, 默认为 0.1) — 注意力概率的 dropout 比率。 - activation (
str
或Callable
, 可选, 默认为"gelu"
) — 编码器和池化器中的非线性激活函数 (函数或字符串)。如果是字符串,则支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - initializer_range (
float
, optional, defaults to 0.02) — 用于初始化所有权重矩阵的截断正态分布初始化器的标准差。 - qa_dropout (
float
, optional, defaults to 0.1) — 在问答模型 DistilBertForQuestionAnswering 中使用的 dropout 概率。 - seq_classif_dropout (
float
, optional, defaults to 0.2) — 在序列分类和多项选择模型 DistilBertForSequenceClassification 中使用的 dropout 概率。
这是用于存储 DistilBertModel 或 TFDistilBertModel 配置的配置类。 它用于根据指定的参数实例化 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
< source >( vocab_file do_lower_case = True do_basic_tokenize = True never_split = None unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None clean_up_tokenization_spaces = True **kwargs )
参数
- vocab_file (
str
) — 包含词汇表的文件。 - do_lower_case (
bool
, optional, defaults toTrue
) — 是否在分词时将输入转换为小写。 - do_basic_tokenize (
bool
, optional, defaults toTrue
) — 是否在 WordPiece 分词之前执行基本分词。 - never_split (
Iterable
, optional) — 在分词期间永远不会被分割的 token 集合。 仅在do_basic_tokenize=True
时有效 - unk_token (
str
, optional, defaults to"[UNK]"
) — 未知 token。词汇表中不存在的 token 无法转换为 ID,而是设置为此 token。 - sep_token (
str
, optional, defaults to"[SEP]"
) — 分隔符 token,用于从多个序列构建序列时,例如用于序列分类的两个序列,或用于问答的文本和问题。 它也用作使用特殊 token 构建的序列的最后一个 token。 - pad_token (
str
, optional, defaults to"[PAD]"
) — 用于填充的 token,例如在批量处理不同长度的序列时。 - cls_token (
str
, optional, defaults to"[CLS]"
) — 分类器 token,用于执行序列分类(对整个序列而不是每个 token 进行分类)。当使用特殊 token 构建序列时,它是序列的第一个 token。 - mask_token (
str
, optional, defaults to"[MASK]"
) — 用于遮盖值的 token。 这是使用掩码语言建模训练此模型时使用的 token。 这是模型将尝试预测的 token。 - tokenize_chinese_chars (
bool
, optional, defaults toTrue
) — 是否对中文字符进行分词。对于日语,这可能应该被禁用(参见此 issue)。
- strip_accents (
bool
, optional) — 是否去除所有重音符号。 如果未指定此选项,则将由lowercase
的值(与原始 BERT 中一样)确定。 - clean_up_tokenization_spaces (
bool
, optional, defaults toTrue
) — 是否在解码后清理空格,清理包括删除潜在的人为产物,如多余的空格。
构建 DistilBERT 分词器。 基于 WordPiece。
此分词器继承自 PreTrainedTokenizer,其中包含大多数主要方法。 用户应参考此超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
参数
- token_ids_0 (
List[int]
) — 将向其添加特殊 token 的 ID 列表。 - token_ids_1 (
List[int]
, optional) — 序列对的可选第二个 ID 列表。
返回值
List[int]
包含适当特殊 token 的 输入 ID 列表。
通过连接并添加特殊 token,从序列或序列对构建模型输入,用于序列分类任务。 BERT 序列具有以下格式
- 单序列:
[CLS] X [SEP]
- 序列对:
[CLS] A [SEP] B [SEP]
将 token (字符串) 序列转换为单个字符串。
create_token_type_ids_from_sequences
< source >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递的两个序列创建一个 mask,用于序列对分类任务。 BERT 序列
如果 token_ids_1
为 None
,则此方法仅返回 mask 的第一部分 (0s)。
get_special_tokens_mask
< 源码 >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None already_has_special_tokens: bool = False ) → List[int]
从一个未添加特殊 token 的 token 列表中检索序列 ID。当使用 tokenizer 的 prepare_for_model
方法添加特殊 token 时,会调用此方法。
DistilBertTokenizerFast
类 transformers.DistilBertTokenizerFast
< 源码 >( vocab_file = None tokenizer_file = None do_lower_case = True unk_token = '[UNK]' sep_token = '[SEP]' pad_token = '[PAD]' cls_token = '[CLS]' mask_token = '[MASK]' tokenize_chinese_chars = True strip_accents = None **kwargs )
参数
- vocab_file (
str
) — 包含词汇表的文件。 - do_lower_case (
bool
, optional, defaults toTrue
) — 指示在 token 化时是否将输入转换为小写。 - unk_token (
str
, optional, defaults to"[UNK]"
) — 未知 token。词汇表中不存在的 token 无法转换为 ID,而是会被设置为此 token。 - sep_token (
str
, optional, defaults to"[SEP]"
) — 分隔符 token,用于从多个序列构建序列时,例如,用于序列分类的两个序列,或者用于问答的文本和问题。它也用作使用特殊 token 构建的序列的最后一个 token。 - pad_token (
str
, optional, defaults to"[PAD]"
) — 用于填充的 token,例如在对不同长度的序列进行批处理时。 - cls_token (
str
, optional, defaults to"[CLS]"
) — 分类器 token,用于进行序列分类(对整个序列进行分类,而不是对每个 token 进行分类)。当使用特殊 token 构建时,它是序列的第一个 token。 - mask_token (
str
, optional, defaults to"[MASK]"
) — 用于掩码值的 token。这是使用掩码语言建模训练此模型时使用的 token。这是模型将尝试预测的 token。 - clean_text (
bool
, optional, defaults toTrue
) — 指示是否在 token 化之前清理文本,方法是删除任何控制字符并将所有空格替换为经典空格。 - tokenize_chinese_chars (
bool
, optional, defaults toTrue
) — 指示是否要 token 化中文字符。对于日语,这可能应该被停用(参见 此问题)。 - strip_accents (
bool
, optional) — 指示是否去除所有重音符号。如果未指定此选项,则将由lowercase
的值确定(与原始 BERT 中相同)。 - wordpieces_prefix (
str
, optional, defaults to"##"
) — 子词的前缀。
构建一个“快速” DistilBERT tokenizer(由 HuggingFace 的 tokenizers 库支持)。基于 WordPiece。
此 tokenizer 继承自 PreTrainedTokenizerFast,其中包含大多数主要方法。用户应参考此超类以获取有关这些方法的更多信息。
build_inputs_with_special_tokens
< 源码 >( token_ids_0 token_ids_1 = None ) → List[int]
参数
- token_ids_0 (
List[int]
) — 特殊 token 将被添加到其中的 ID 列表。 - token_ids_1 (
List[int]
, optional) — 可选的,用于序列对的第二个 ID 列表。
返回值
List[int]
包含适当特殊 token 的 输入 ID 列表。
通过连接并添加特殊 token,从序列或序列对构建模型输入,用于序列分类任务。 BERT 序列具有以下格式
- 单序列:
[CLS] X [SEP]
- 序列对:
[CLS] A [SEP] B [SEP]
create_token_type_ids_from_sequences
< 源码 >( token_ids_0: typing.List[int] token_ids_1: typing.Optional[typing.List[int]] = None ) → List[int]
从传递的两个序列创建一个 mask,用于序列对分类任务。 BERT 序列
如果 token_ids_1
为 None
,则此方法仅返回 mask 的第一部分 (0s)。
DistilBertModel
类 transformers.DistilBertModel
< 源码 >( config: PretrainedConfig )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
裸 DistilBERT 编码器/transformer,输出原始的隐藏状态,顶部没有任何特定的 head。
此模型继承自 PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, num_choices)
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 以获取详细信息。
- attention_mask (
torch.FloatTensor
,形状为(batch_size, num_choices)
,可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。Mask 值在[0, 1]
中选择:- 1 表示 tokens 未被 mask,
- 0 表示 tokens 被 mask。
- head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于 nullify self-attention 模块中选定 head 的 Mask。Mask 值在[0, 1]
中选择:- 1 表示 head 未被 mask,
- 0 表示 head 被 mask。
- inputs_embeds (
torch.FloatTensor
,形状为(batch_size, num_choices, hidden_size)
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更灵活地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。
返回值
transformers.modeling_outputs.BaseModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutput 或一个 torch.FloatTensor
的 tuple(如果传递了 return_dict=False
,或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
last_hidden_state (
torch.FloatTensor
,形状为(batch_size, sequence_length, hidden_size)
) — 模型最后一层的输出处的隐藏状态序列。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出的输出 + 每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
DistilBertModel forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, DistilBertModel
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = DistilBertModel.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
DistilBertForMaskedLM
class transformers.DistilBertForMaskedLM
< source >( config: PretrainedConfig )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
带有 masked language modeling
head 的 DistilBert 模型。
此模型继承自 PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.MaskedLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, num_choices)
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 以获取详细信息。
- attention_mask (
torch.FloatTensor
,形状为(batch_size, num_choices)
,可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。Mask 值在[0, 1]
中选择:- 1 表示 tokens 未被 mask,
- 0 表示 tokens 被 mask。
- head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 用于 nullify self-attention 模块中选定 head 的 Mask。Mask 值在[0, 1]
中选择:- 1 表示 head 未被 mask,
- 0 表示 head 被 mask。
- inputs_embeds (
torch.FloatTensor
,形状为(batch_size, num_choices, hidden_size)
,可选) — 可选地,您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更灵活地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 用于计算 masked language modeling loss 的标签。 索引应在[-100, 0, ..., config.vocab_size]
中(请参阅input_ids
文档字符串)。索引设置为-100
的 tokens 将被忽略(masked),loss 仅针对标签在[0, ..., config.vocab_size]
中的 tokens 计算。
返回值
transformers.modeling_outputs.MaskedLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.MaskedLMOutput 或一个 torch.FloatTensor
的 tuple(如果传递了 return_dict=False
,或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供了labels
时返回) — Masked language modeling (MLM) loss。 -
logits (
torch.FloatTensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(SoftMax 之前每个词汇表 token 的分数)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出的输出 + 每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
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)
>>> 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)
DistilBertForSequenceClassification
class transformers.DistilBertForSequenceClassification
< source >( config: PretrainedConfig )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型转换器,顶部带有一个序列分类/回归头(池化输出顶部的线性层),例如用于 GLUE 任务。
此模型继承自 PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
,形状为(batch_size, sequence_length)
, 可选) — 掩码,用于避免在 padding token 索引上执行 attention。掩码值在[0, 1]
中选择:- 1 表示 tokens 未被掩码,
- 0 表示 tokens 被掩码。
- head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使 self-attention 模块的选定 head 失效的掩码。掩码值在[0, 1]
中选择:- 1 表示 head 未被掩码,
- 0 表示 head 被掩码。
- inputs_embeds (
torch.FloatTensor
,形状为(batch_size, sequence_length, hidden_size)
, 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
,形状为(batch_size,)
, 可选) — 用于计算序列分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels == 1
,则计算回归损失(均方误差损失),如果config.num_labels > 1
,则计算分类损失(交叉熵损失)。
返回值
transformers.modeling_outputs.SequenceClassifierOutput 或 tuple(torch.FloatTensor)
transformers.modeling_outputs.SequenceClassifierOutput 或 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
, 可选, 当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
logits (
torch.FloatTensor
,形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)得分(SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出的输出 + 每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
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()
>>> # 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
多标签分类示例
>>> 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
< source >( config: PretrainedConfig )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个多项选择分类头(池化输出顶部的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。
此模型继承自 PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.MultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, num_choices, sequence_length)
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
,形状为(batch_size, num_choices, sequence_length)
, 可选) — 掩码,用于避免在 padding token 索引上执行 attention。掩码值在[0, 1]
中选择:- 1 表示 tokens 未被掩码,
- 0 表示 tokens 被掩码。
- head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使 self-attention 模块的选定 head 失效的掩码。掩码值在[0, 1]
中选择:- 1 表示 head 未被掩码,
- 0 表示 head 被掩码。
- inputs_embeds (
torch.FloatTensor
,形状为(batch_size, num_choices, sequence_length, hidden_size)
, 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
,形状为(batch_size,)
, 可选) — 用于计算多项选择分类损失的标签。索引应在[0, ..., num_choices-1]
中,其中num_choices
是输入张量第二个维度的大小。(参见上面的input_ids
)
返回值
transformers.modeling_outputs.MultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
transformers.modeling_outputs.MultipleChoiceModelOutput 或 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为 (1,), 可选, 当提供labels
时返回) — 分类损失。 -
logits (
torch.FloatTensor
,形状为(batch_size, num_choices)
) — num_choices 是输入张量的第二个维度。(参见上面的 input_ids)。分类得分(SoftMax 之前)。
-
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出的输出 + 每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
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
< source >( config: PretrainedConfig )
参数
- config (DistilBertConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个 token 分类头(隐藏状态输出之上的一个线性层),例如用于命名实体识别 (NER) 任务。
此模型继承自 PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为({0})
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
,形状为({0})
,可选) — 掩码,以避免在 padding token 索引上执行 attention。在[0, 1]
中选择的掩码值:- 1 表示 未被掩码 的 tokens,
- 0 表示 已被掩码 的 tokens。
- head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 掩码,用于 nullify self-attention 模块的选定 head。在[0, 1]
中选择的掩码值:- 1 表示 head 未被掩码,
- 0 表示 head 已被掩码。
- inputs_embeds (
torch.FloatTensor
,形状为({0}, hidden_size)
,可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更好地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 用于计算 token 分类损失的标签。索引应在[0, ..., config.num_labels - 1]
中。
返回值
transformers.modeling_outputs.TokenClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.TokenClassifierOutput 或一个 torch.FloatTensor
的 tuple (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供labels
时返回) — 分类损失。 -
logits (
torch.FloatTensor
,形状为(batch_size, sequence_length, config.num_labels)
) — 分类得分(在 SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出的输出 + 每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
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]]
>>> labels = predicted_token_class_ids
>>> loss = model(**inputs, labels=labels).loss
DistilBertForQuestionAnswering
class transformers.DistilBertForQuestionAnswering
< source >( config: PretrainedConfig )
参数
- config (DistilBertConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个 span 分类头,用于抽取式问答任务,如 SQuAD(隐藏状态输出之上的一个线性层,用于计算 span start logits
和 span end logits
)。
此模型继承自 PreTrainedModel。查看超类文档以了解库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝 head 等)。
此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解与通用用法和行为相关的所有事项。
forward
< source >( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None head_mask: typing.Optional[torch.Tensor] = None inputs_embeds: typing.Optional[torch.Tensor] = None start_positions: typing.Optional[torch.Tensor] = None end_positions: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, num_choices)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- attention_mask (
torch.FloatTensor
,形状为(batch_size, num_choices)
,可选) — 掩码,以避免在 padding token 索引上执行 attention。在[0, 1]
中选择的掩码值:- 1 表示 未被掩码 的 tokens,
- 0 表示 已被掩码 的 tokens。
- head_mask (
torch.FloatTensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 掩码,用于 nullify self-attention 模块的选定 head。在[0, 1]
中选择的掩码值:- 1 表示 head 未被掩码,
- 0 表示 head 已被掩码。
- inputs_embeds (
torch.FloatTensor
,形状为(batch_size, num_choices, hidden_size)
,可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更好地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通 tuple。 - start_positions (
torch.LongTensor
,形状为(batch_size,)
,可选) — 用于计算 token 分类损失的标签跨度起始位置(索引)。位置被限制在序列的长度 (sequence_length
) 内。序列之外的位置不计入损失计算。 - end_positions (
torch.LongTensor
,形状为(batch_size,)
,可选) — 用于计算 token 分类损失的标签跨度结束位置(索引)。位置被限制在序列的长度 (sequence_length
) 内。序列之外的位置不计入损失计算。
返回值
transformers.modeling_outputs.QuestionAnsweringModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.QuestionAnsweringModelOutput 或者一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
torch.FloatTensor
,形状为(1,)
,可选,当提供labels
时返回) — 总跨度提取损失是起始和结束位置交叉熵损失的总和。 -
start_logits (
torch.FloatTensor
,形状为(batch_size, sequence_length)
) — 跨度起始得分(SoftMax 之前)。 -
end_logits (
torch.FloatTensor
,形状为(batch_size, sequence_length)
) — 跨度结束得分(SoftMax 之前)。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递了output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的 Tuple(如果模型具有嵌入层,则为嵌入输出的输出 + 每层的输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递了output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的 Tuple(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
DistilBertForQuestionAnswering 的前向传播方法,覆盖了 __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]
>>> # 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
TFDistilBertModel
class transformers.TFDistilBertModel
< source >( config *inputs **kwargs )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。查看 from_pretrained() 方法来加载模型权重。
裸 DistilBERT 编码器/transformer,输出原始的隐藏状态,顶部没有任何特定的 head。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规使用和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 所有输入都作为关键字参数(如 PyTorch 模型),或者
- 所有输入都作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,您可以使用三种可能性来收集第一个位置参数中的所有输入张量
- 一个只包含
input_ids
且不包含其他内容的张量:model(input_ids)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个输入张量,与文档字符串中给出的输入名称相关联:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFBaseModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的Numpy array
或tf.Tensor
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。有关详细信息,请参见 PreTrainedTokenizer.call() 和 PreTrainedTokenizer.encode()。
- attention_mask (形状为
(batch_size, sequence_length)
的Numpy array
或tf.Tensor
,可选) — 掩码,以避免在 padding token 索引上执行 attention。在[0, 1]
中选择的掩码值:- 1 表示 tokens 未被掩盖,
- 0 表示 tokens 被掩盖。
- head_mask (形状为
(num_heads,)
或(num_layers, num_heads)
的Numpy array
或tf.Tensor
,可选) — 掩码,用于使 self-attention 模块的选定 head 失效。在[0, 1]
中选择的掩码值:- 1 表示 head 未被掩盖,
- 0 表示 head 被掩盖。
- inputs_embeds (形状为
(batch_size, sequence_length, hidden_size)
的tf.Tensor
,可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更灵活地控制如何将input_ids
索引转换为关联向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参见返回张量下的attentions
。此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - output_hidden_states (
bool
,可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是纯元组。此参数可以在即时模式下使用,在图模式下,该值将始终设置为 True。 - training (
bool
,可选,默认为False
) — 是否在训练模式下使用模型(诸如 dropout 模块之类的某些模块在训练和评估之间具有不同的行为)。
返回值
transformers.modeling_tf_outputs.TFBaseModelOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFBaseModelOutput 或者一个 tf.Tensor
元组(如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
last_hidden_state (形状为
(batch_size, sequence_length, hidden_size)
的tf.Tensor
) — 模型最后一层的输出处的隐藏状态序列。 -
hidden_states (
tuple(tf.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 形状为(batch_size, sequence_length, hidden_size)
的tf.Tensor
元组(embeddings 的输出一个,每层的输出一个)。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
TFDistilBertModel 前向传播方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFDistilBertModel
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> outputs = model(inputs)
>>> last_hidden_states = outputs.last_hidden_state
TFDistilBertForMaskedLM
class transformers.TFDistilBertForMaskedLM
< source >( config *inputs **kwargs )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,只会加载配置。查看 from_pretrained() 方法来加载模型权重。
带有 masked language modeling
head 的 DistilBert 模型。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规使用和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 所有输入都作为关键字参数(如 PyTorch 模型),或者
- 所有输入都作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,您可以使用三种可能性来收集第一个位置参数中的所有输入张量
- 一个只包含
input_ids
且不包含其他内容的张量:model(input_ids)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个输入张量,与文档字符串中给出的输入名称相关联:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFMaskedLMOutput 或 tuple(tf.Tensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的Numpy array
或tf.Tensor
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。有关详细信息,请参见 PreTrainedTokenizer.call() 和 PreTrainedTokenizer.encode()。
- attention_mask (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
,可选) — 掩码,用于避免在 padding token 索引上执行 attention。掩码值在[0, 1]
中选择:- 1 表示 token 未被掩码,
- 0 表示 token 被掩码。
- head_mask (
Numpy array
或tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 掩码,用于 nullify self-attention 模块的选定 head。掩码值在[0, 1]
中选择:- 1 表示 head 未被掩码,
- 0 表示 head 被掩码。
- inputs_embeds (
tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
,可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。 - training (
bool
,可选,默认为False
) — 是否在训练模式下使用模型(dropout 模块等某些模块在训练和评估之间具有不同的行为)。 - labels (
tf.Tensor
,形状为(batch_size, sequence_length)
,可选) — 用于计算 masked language modeling loss 的标签。索引应在[-100, 0, ..., config.vocab_size]
中(请参阅input_ids
docstring)。索引设置为-100
的 token 将被忽略(掩码),loss 仅针对标签在[0, ..., config.vocab_size]
中的 token 计算。
返回值
transformers.modeling_tf_outputs.TFMaskedLMOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFMaskedLMOutput 或 tf.Tensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
tf.Tensor
,形状为(n,)
,可选,当提供labels
时返回) — Masked language modeling (MLM) loss。 -
logits (
tf.Tensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(SoftMax 之前每个词汇 token 的分数)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
的元组(embedding 的输出一个,每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
TFDistilBertForMaskedLM 前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFDistilBertForMaskedLM
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = TFDistilBertForMaskedLM.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="tf")
>>> logits = model(**inputs).logits
>>> # retrieve index of [MASK]
>>> mask_token_index = tf.where((inputs.input_ids == tokenizer.mask_token_id)[0])
>>> selected_logits = tf.gather_nd(logits[0], indices=mask_token_index)
>>> predicted_token_id = tf.math.argmax(selected_logits, axis=-1)
TFDistilBertForSequenceClassification
class transformers.TFDistilBertForSequenceClassification
< source >( config *inputs **kwargs )
参数
- config (DistilBertConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法以加载模型权重。
DistilBert 模型转换器,顶部带有一个序列分类/回归头(池化输出顶部的线性层),例如用于 GLUE 任务。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规使用和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 所有输入都作为关键字参数(如 PyTorch 模型),或者
- 所有输入都作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,您可以使用三种可能性来收集第一个位置参数中的所有输入张量
- 一个只包含
input_ids
且不包含其他内容的张量:model(input_ids)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个输入张量,与文档字符串中给出的输入名称相关联:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或 tuple(tf.Tensor)
参数
- input_ids (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 token 的索引。可以使用 AutoTokenizer 获取索引。 有关详细信息,请参见 PreTrainedTokenizer.call() 和 PreTrainedTokenizer.encode()。
- attention_mask (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
,可选) — 掩码,用于避免在 padding token 索引上执行 attention。掩码值在[0, 1]
中选择:- 1 表示 token 未被掩码,
- 0 表示 token 被掩码。
- head_mask (
Numpy array
或tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
,可选) — 掩码,用于 nullify self-attention 模块的选定 head。掩码值在[0, 1]
中选择:- 1 表示 head 未被掩码,
- 0 表示 head 被掩码。
- inputs_embeds (
tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
,可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
,可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。 - training (
bool
,可选,默认为False
) — 是否在训练模式下使用模型(dropout 模块等某些模块在训练和评估之间具有不同的行为)。 - labels (
tf.Tensor
,形状为(batch_size,)
,可选) — 用于计算序列分类/回归 loss 的标签。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels == 1
,则计算回归 loss(均方 loss)。如果config.num_labels > 1
,则计算分类 loss(交叉熵)。
返回值
transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFSequenceClassifierOutput 或 tf.Tensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
tf.Tensor
,形状为(batch_size, )
,可选,当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)loss。 -
logits (
tf.Tensor
,形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)分数(SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
的元组(embedding 的输出一个,每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
TFDistilBertForSequenceClassification 前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFDistilBertForSequenceClassification
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="tf")
>>> logits = model(**inputs).logits
>>> predicted_class_id = int(tf.math.argmax(logits, axis=-1)[0])
>>> # 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 = TFDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased", num_labels=num_labels)
>>> labels = tf.constant(1)
>>> loss = model(**inputs, labels=labels).loss
TFDistilBertForMultipleChoice
class transformers.TFDistilBertForMultipleChoice
< 源代码 >( config *inputs **kwargs )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个多项选择分类头(池化输出顶部的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规使用和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 所有输入都作为关键字参数(如 PyTorch 模型),或者
- 所有输入都作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,您可以使用三种可能性来收集第一个位置参数中的所有输入张量
- 一个只包含
input_ids
且不包含其他内容的张量:model(input_ids)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个输入张量,与文档字符串中给出的输入名称相关联:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< 源代码 >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFMultipleChoiceModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
Numpy array
或tf.Tensor
,形状为(batch_size, num_choices, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获得索引。 参见 PreTrainedTokenizer.call() 和 PreTrainedTokenizer.encode() 以了解详情。
- attention_mask (
Numpy array
或tf.Tensor
,形状为(batch_size, num_choices, sequence_length)
, 可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 token 未被 Mask,
- 0 表示 token 已被 Mask。
- head_mask (
Numpy array
或tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使 self-attention 模块中选定的 head 失效的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 head 未被 Mask,
- 0 表示 head 已被 Mask。
- inputs_embeds (
tf.Tensor
,形状为(batch_size, num_choices, sequence_length, hidden_size)
, 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更灵活地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的 tuple。 此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。 - training (
bool
, 可选, 默认为False
) — 是否在训练模式下使用模型(dropout 模块等某些模块在训练和评估之间具有不同的行为)。 - labels (
tf.Tensor
,形状为(batch_size,)
, 可选) — 用于计算多项选择分类损失的标签。 索引应为[0, ..., num_choices]
,其中num_choices
是输入 tensors 的第二个维度的大小。(参见上面的input_ids
)
返回值
transformers.modeling_tf_outputs.TFMultipleChoiceModelOutput 或 tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFMultipleChoiceModelOutput 或 tf.Tensor
的 tuple (如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
loss (
tf.Tensor
,形状为 (batch_size, ), 可选, 当提供labels
时返回) — 分类损失。 -
logits (
tf.Tensor
,形状为(batch_size, num_choices)
) — num_choices 是输入 tensors 的第二个维度。(参见上面的 input_ids)。分类得分(SoftMax 之前)。
-
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
的元组(embedding 的输出一个,每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
TFDistilBertForMultipleChoice forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFDistilBertForMultipleChoice
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = TFDistilBertForMultipleChoice.from_pretrained("distilbert-base-uncased")
>>> 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."
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="tf", padding=True)
>>> inputs = {k: tf.expand_dims(v, 0) for k, v in encoding.items()}
>>> outputs = model(inputs) # batch size is 1
>>> # the linear classifier still needs to be trained
>>> logits = outputs.logits
TFDistilBertForTokenClassification
class transformers.TFDistilBertForTokenClassification
< 源代码 >( config *inputs **kwargs )
参数
- config (DistilBertConfig) — 带有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个 token 分类头(隐藏状态输出之上的一个线性层),例如用于命名实体识别 (NER) 任务。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规使用和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 所有输入都作为关键字参数(如 PyTorch 模型),或者
- 所有输入都作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,您可以使用三种可能性来收集第一个位置参数中的所有输入张量
- 一个只包含
input_ids
且不包含其他内容的张量:model(input_ids)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个输入张量,与文档字符串中给出的输入名称相关联:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< 源代码 >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None labels: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFTokenClassifierOutput 或 tuple(tf.Tensor)
参数
- input_ids (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获得索引。 参见 PreTrainedTokenizer.call() 和 PreTrainedTokenizer.encode() 以了解详情。
- attention_mask (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
, 可选) — 用于避免在 padding token 索引上执行 attention 的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 token 未被 Mask,
- 0 表示 token 已被 Mask。
- head_mask (
Numpy array
或tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, 可选) — 用于使 self-attention 模块中选定的 head 失效的 Mask。 Mask 值在[0, 1]
中选择:- 1 表示 head 未被 Mask,
- 0 表示 head 已被 Mask。
- inputs_embeds (
tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
, 可选) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更灵活地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参见返回的 tensors 下的attentions
。 此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参见返回的 tensors 下的hidden_states
。 此参数只能在 eager 模式下使用,在 graph 模式下将使用 config 中的值。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的 tuple。 此参数可以在 eager 模式下使用,在 graph 模式下该值将始终设置为 True。 - training (
bool
, optional, defaults toFalse
) — 是否在训练模式下使用模型(例如 dropout 模块等模块在训练和评估之间具有不同的行为)。 - labels (
tf.Tensor
of shape(batch_size, sequence_length)
, optional) — 用于计算 token 分类损失的标签。索引应在[0, ..., config.num_labels - 1]
中。
返回值
transformers.modeling_tf_outputs.TFTokenClassifierOutput or tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFTokenClassifierOutput 或者 tf.Tensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (DistilBertConfig) 和输入的各种元素。
-
loss (
tf.Tensor
of shape(n,)
, optional, 其中 n 是未被掩码的标签数量,当提供labels
时返回) — 分类损失。 -
logits (
tf.Tensor
of shape(batch_size, sequence_length, config.num_labels)
) — 分类得分(SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
的元组(embedding 的输出一个,每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
TFDistilBertForTokenClassification 的前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFDistilBertForTokenClassification
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = TFDistilBertForTokenClassification.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer(
... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="tf"
... )
>>> logits = model(**inputs).logits
>>> predicted_token_class_ids = tf.math.argmax(logits, axis=-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] for t in predicted_token_class_ids[0].numpy().tolist()]
TFDistilBertForQuestionAnswering
class transformers.TFDistilBertForQuestionAnswering
< source >( config *inputs **kwargs )
参数
- config (DistilBertConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有跨度分类头,用于抽取式问答任务,如 SQuAD(在 hidden-states 输出之上有一个线性层,用于计算 span start logits
和 span end logits
)。
此模型继承自 TFPreTrainedModel。查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 keras.Model 子类。将其用作常规 TF 2.0 Keras 模型,并参阅 TF 2.0 文档,了解与常规使用和行为相关的所有事项。
transformers
中的 TensorFlow 模型和层接受两种输入格式
- 所有输入都作为关键字参数(如 PyTorch 模型),或者
- 所有输入都作为列表、元组或字典放在第一个位置参数中。
支持第二种格式的原因是,Keras 方法在将输入传递给模型和层时更喜欢这种格式。由于这种支持,当使用诸如 model.fit()
之类的方法时,对于您来说,事情应该“正常工作” - 只需以 model.fit()
支持的任何格式传递您的输入和标签即可!但是,如果您想在 Keras 方法(如 fit()
和 predict()
)之外使用第二种格式,例如在使用 Keras Functional
API 创建您自己的层或模型时,您可以使用三种可能性来收集第一个位置参数中的所有输入张量
- 一个只包含
input_ids
且不包含其他内容的张量:model(input_ids)
- 一个长度可变的列表,其中包含一个或多个输入张量,顺序与文档字符串中给出的顺序相同:
model([input_ids, attention_mask])
或model([input_ids, attention_mask, token_type_ids])
- 一个字典,其中包含一个或多个输入张量,与文档字符串中给出的输入名称相关联:
model({"input_ids": input_ids, "token_type_ids": token_type_ids})
请注意,当使用 子类化 创建模型和层时,您无需担心任何这些,因为您可以像对待任何其他 Python 函数一样传递输入!
call
< source >( input_ids: TFModelInputType | None = None attention_mask: np.ndarray | tf.Tensor | None = None head_mask: np.ndarray | tf.Tensor | None = None inputs_embeds: np.ndarray | tf.Tensor | None = None output_attentions: Optional[bool] = None output_hidden_states: Optional[bool] = None return_dict: Optional[bool] = None start_positions: np.ndarray | tf.Tensor | None = None end_positions: np.ndarray | tf.Tensor | None = None training: Optional[bool] = False ) → transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput 或 tuple(tf.Tensor)
参数
- input_ids (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 token 的索引。索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.call() 和 PreTrainedTokenizer.encode()。
- attention_mask (
Numpy array
或tf.Tensor
,形状为(batch_size, sequence_length)
, optional) — 用于避免在 padding token 索引上执行 attention 的掩码。掩码值在[0, 1]
中选择:- 1 表示 token 未被掩码,
- 0 表示 token 已被掩码。
- head_mask (
Numpy array
或tf.Tensor
,形状为(num_heads,)
或(num_layers, num_heads)
, optional) — 用于使 self-attention 模块的选定 head 失效的掩码。掩码值在[0, 1]
中选择:- 1 表示 head 未被掩码,
- 0 表示 head 已被掩码。
- inputs_embeds (
tf.Tensor
,形状为(batch_size, sequence_length, hidden_size)
, optional) — (可选)您可以选择直接传递嵌入表示,而不是传递input_ids
。如果您希望比模型的内部嵌入查找矩阵更精细地控制如何将input_ids
索引转换为关联的向量,这将非常有用。 - output_attentions (
bool
, optional) — 是否返回所有 attention 层的 attentions 张量。有关更多详细信息,请参阅返回张量下的attentions
。此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - output_hidden_states (
bool
, optional) — 是否返回所有层的 hidden states。有关更多详细信息,请参阅返回张量下的hidden_states
。此参数只能在即时模式下使用,在图模式下将使用配置中的值。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通元组。此参数可以在即时模式下使用,在图模式下,该值将始终设置为 True。 - training (
bool
, optional, defaults toFalse
) — 是否在训练模式下使用模型(例如 dropout 模块等模块在训练和评估之间具有不同的行为)。 - start_positions (
tf.Tensor
,形状为(batch_size,)
, optional) — 用于计算 token 分类损失的标签跨度起点的标签位置(索引)。位置被限制在序列的长度 (sequence_length
) 内。序列之外的位置不计入损失计算。 - end_positions (
tf.Tensor
,形状为(batch_size,)
, optional) — 用于计算 token 分类损失的标签跨度终点的标签位置(索引)。位置被限制在序列的长度 (sequence_length
) 内。序列之外的位置不计入损失计算。
返回值
transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput or tuple(tf.Tensor)
一个 transformers.modeling_tf_outputs.TFQuestionAnsweringModelOutput 或者 tf.Tensor
的元组 (如果传递了 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (DistilBertConfig) 和输入的各种元素。
-
loss (
tf.Tensor
,形状为(batch_size, )
, optional, 当提供start_positions
和end_positions
时返回) — 总跨度抽取损失是起始和结束位置的交叉熵之和。 -
start_logits (
tf.Tensor
,形状为(batch_size, sequence_length)
) — 跨度起始得分(SoftMax 之前)。 -
end_logits (
tf.Tensor
,形状为(batch_size, sequence_length)
) — 跨度结束得分(SoftMax 之前)。 -
hidden_states (
tuple(tf.Tensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —tf.Tensor
的元组(embedding 的输出一个,每层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(tf.Tensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) — 形状为(batch_size, num_heads, sequence_length, sequence_length)
的tf.Tensor
元组(每层一个)。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
TFDistilBertForQuestionAnswering 的前向方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, TFDistilBertForQuestionAnswering
>>> import tensorflow as tf
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = TFDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="tf")
>>> outputs = model(**inputs)
>>> answer_start_index = int(tf.math.argmax(outputs.start_logits, axis=-1)[0])
>>> answer_end_index = int(tf.math.argmax(outputs.end_logits, axis=-1)[0])
>>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
FlaxDistilBertModel
class transformers.FlaxDistilBertModel
< source >( config: DistilBertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (DistilBertConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
裸 DistilBert 模型 transformer,输出原始 hidden-states,顶部没有任何特定的 head。
此模型继承自 FlaxPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 子类。将其用作常规 Flax linen Module,并参阅 Flax 文档以了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids attention_mask = None head_mask = None params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None )
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 了解详情。
- attention_mask (
numpy.ndarray
of shape(batch_size, sequence_length)
, 可选) — 掩码,用于避免在 padding token 索引上执行 attention。 掩码值在[0, 1]
中选择:- 1 表示 未被掩码 的 tokens,
- 0 表示 被掩码 的 tokens。
- output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
FlaxDistilBertPreTrainedModel
的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, FlaxDistilBertModel
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = FlaxDistilBertModel.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
FlaxDistilBertForMaskedLM
class transformers.FlaxDistilBertForMaskedLM
< source >( config: DistilBertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (DistilBertConfig) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有 language modeling
head 的 DistilBert 模型。
此模型继承自 FlaxPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 子类。将其用作常规 Flax linen Module,并参阅 Flax 文档以了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids attention_mask = None head_mask = None params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxMaskedLMOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 了解详情。
- attention_mask (
numpy.ndarray
of shape(batch_size, sequence_length)
, 可选) — 掩码,用于避免在 padding token 索引上执行 attention。 掩码值在[0, 1]
中选择:- 1 表示 未被掩码 的 tokens,
- 0 表示 被掩码 的 tokens。
- output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
transformers.modeling_flax_outputs.FlaxMaskedLMOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxMaskedLMOutput 或一个 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
logits (
jnp.ndarray
of shape(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(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 输出处的隐藏状态。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
FlaxDistilBertPreTrainedModel
的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, FlaxDistilBertForMaskedLM
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = FlaxDistilBertForMaskedLM.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("The capital of France is [MASK].", return_tensors="jax")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
FlaxDistilBertForSequenceClassification
class transformers.FlaxDistilBertForSequenceClassification
< source >( config: DistilBertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (DistilBertConfig) — 具有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
DistilBert 模型转换器,顶部带有一个序列分类/回归头(池化输出顶部的线性层),例如用于 GLUE 任务。
此模型继承自 FlaxPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 子类。将其用作常规 Flax linen Module,并参阅 Flax 文档以了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids attention_mask = None head_mask = None params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。可以使用 AutoTokenizer 获取索引。 请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 了解详情。
- attention_mask (
numpy.ndarray
of shape(batch_size, sequence_length)
, 可选) — 掩码,用于避免在 padding token 索引上执行 attention。 掩码值在[0, 1]
中选择:- 1 表示 未被掩码 的 tokens,
- 0 表示 被掩码 的 tokens。
- output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attentions tensors。 有关更多详细信息,请参阅返回的 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回的 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxSequenceClassifierOutput 或一个 torch.FloatTensor
元组 (如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
logits (形状为
(batch_size, config.num_labels)
的jnp.ndarray
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
的元组(embeddings 输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
FlaxDistilBertPreTrainedModel
的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, FlaxDistilBertForSequenceClassification
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = FlaxDistilBertForSequenceClassification.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
FlaxDistilBertForMultipleChoice
类 transformers.FlaxDistilBertForMultipleChoice
< source >( config: DistilBertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (DistilBertConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个多项选择分类头(池化输出顶部的线性层和一个 softmax),例如用于 RocStories/SWAG 任务。
此模型继承自 FlaxPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 子类。将其用作常规 Flax linen Module,并参阅 Flax 文档以了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids attention_mask = None head_mask = None params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxMultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, num_choices, sequence_length)
的numpy.ndarray
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.**call**()。
- attention_mask (形状为
(batch_size, num_choices, sequence_length)
的numpy.ndarray
,可选) — 用于避免对 padding token 索引执行 attention 的掩码。掩码值在[0, 1]
中选择:- 1 代表未被掩码的 tokens,
- 0 代表被掩码的 tokens。
- output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
transformers.modeling_flax_outputs.FlaxMultipleChoiceModelOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxMultipleChoiceModelOutput 或一个 torch.FloatTensor
元组 (如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
logits (形状为
(batch_size, num_choices)
的jnp.ndarray
) — *num_choices* 是输入 tensors 的第二个维度。(参见上面的 *input_ids*)。分类得分(SoftMax 之前)。
-
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
的元组(embeddings 输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
FlaxDistilBertPreTrainedModel
的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, FlaxDistilBertForMultipleChoice
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = FlaxDistilBertForMultipleChoice.from_pretrained("distilbert-base-uncased")
>>> 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."
>>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="jax", padding=True)
>>> outputs = model(**{k: v[None, :] for k, v in encoding.items()})
>>> logits = outputs.logits
FlaxDistilBertForTokenClassification
类 transformers.FlaxDistilBertForTokenClassification
< source >( config: DistilBertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (DistilBertConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
DistilBert 模型,顶部带有一个 token 分类头(隐藏状态输出之上的一个线性层),例如用于命名实体识别 (NER) 任务。
此模型继承自 FlaxPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 子类。将其用作常规 Flax linen Module,并参阅 Flax 文档以了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids attention_mask = None head_mask = None params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxTokenClassifierOutput 或 tuple(torch.FloatTensor)
参数
- input_ids (形状为
(batch_size, sequence_length)
的numpy.ndarray
) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.**call**()。
- attention_mask (形状为
(batch_size, sequence_length)
的numpy.ndarray
,可选) — 用于避免对 padding token 索引执行 attention 的掩码。掩码值在[0, 1]
中选择:- 1 代表未被掩码的 tokens,
- 0 代表被掩码的 tokens。
- output_attentions (
bool
, 可选) — 是否返回所有 attention 层的 attention tensors。 有关更多详细信息,请参阅返回 tensors 下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回 tensors 下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
transformers.modeling_flax_outputs.FlaxTokenClassifierOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_flax_outputs.FlaxTokenClassifierOutput 或一个 torch.FloatTensor
元组 (如果传递了 return_dict=False
或者当 config.return_dict=False
时),包含各种元素,具体取决于配置 (DistilBertConfig) 和输入。
-
logits (形状为
(batch_size, sequence_length, config.num_labels)
的jnp.ndarray
) — 分类得分(在 SoftMax 之前)。 -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
的元组(embeddings 输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
FlaxDistilBertPreTrainedModel
的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, FlaxDistilBertForTokenClassification
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = FlaxDistilBertForTokenClassification.from_pretrained("distilbert-base-uncased")
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="jax")
>>> outputs = model(**inputs)
>>> logits = outputs.logits
FlaxDistilBertForQuestionAnswering
类 transformers.FlaxDistilBertForQuestionAnswering
< source >( config: DistilBertConfig input_shape: typing.Tuple = (1, 1) seed: int = 0 dtype: dtype = <class 'jax.numpy.float32'> _do_init: bool = True **kwargs )
参数
- config (DistilBertConfig) — 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.
DistilBert 模型,顶部带有一个 span 分类头,用于抽取式问答任务,如 SQuAD(隐藏状态输出之上的一个线性层,用于计算 span start logits
和 span end logits
)。
此模型继承自 FlaxPreTrainedModel。查看超类文档以获取库为其所有模型实现的通用方法(例如,从 PyTorch 模型下载、保存和转换权重)
此模型也是 flax.linen.Module 子类。将其用作常规 Flax linen Module,并参阅 Flax 文档以了解与常规用法和行为相关的所有事项。
最后,此模型支持固有的 JAX 功能,例如
__call__
< source >( input_ids attention_mask = None head_mask = None params: dict = None dropout_rng: <function PRNGKey at 0x7f787eb14310> = None train: bool = False output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutput or tuple(torch.FloatTensor)
参数
- input_ids (
numpy.ndarray
of shape(batch_size, sequence_length)
) — Indices of input sequence tokens in the vocabulary.Indices can be obtained using AutoTokenizer. See PreTrainedTokenizer.encode() and PreTrainedTokenizer.call() for details.
- attention_mask (
numpy.ndarray
of shape(batch_size, sequence_length)
, optional) — Mask to avoid performing attention on padding token indices. Mask values selected in[0, 1]
:- 1 for tokens that are not masked,
- 0 for tokens that are masked.
- output_attentions (
bool
, optional) — Whether or not to return the attentions tensors of all attention layers. Seeattentions
under returned tensors for more detail. - output_hidden_states (
bool
, optional) — Whether or not to return the hidden states of all layers. Seehidden_states
under returned tensors for more detail. - return_dict (
bool
, optional) — Whether or not to return a ModelOutput instead of a plain tuple.
返回值
transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutput or tuple(torch.FloatTensor)
A transformers.modeling_flax_outputs.FlaxQuestionAnsweringModelOutput 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 (DistilBertConfig) and inputs.
-
start_logits (
jnp.ndarray
of shape(batch_size, sequence_length)
) — Span-start scores (before SoftMax). -
end_logits (
jnp.ndarray
of shape(batch_size, sequence_length)
) — Span-end scores (before SoftMax). -
hidden_states (
tuple(jnp.ndarray)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —jnp.ndarray
的元组(embeddings 输出一个,每层输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出以及初始 embedding 输出处的隐藏状态。
-
attentions (
tuple(jnp.ndarray)
, 可选, 当传递output_attentions=True
或当config.output_attentions=True
时返回) —jnp.ndarray
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 Attention 权重,用于计算 self-attention head 中的加权平均值。
FlaxDistilBertPreTrainedModel
的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward pass 的配方需要在该函数中定义,但之后应该调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoTokenizer, FlaxDistilBertForQuestionAnswering
>>> tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
>>> model = FlaxDistilBertForQuestionAnswering.from_pretrained("distilbert-base-uncased")
>>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
>>> inputs = tokenizer(question, text, return_tensors="jax")
>>> outputs = model(**inputs)
>>> start_scores = outputs.start_logits
>>> end_scores = outputs.end_logits